diff --git a/2-2.txt b/2-2.txt new file mode 100644 index 0000000..1c5d8ce --- /dev/null +++ b/2-2.txt @@ -0,0 +1,100 @@ +// inside directory +// microservice-externaldb/ +// officalNodeDockerfile +// node-microservice/ +// two-microservices/ + +// terminal commands +// vi officialNodeDockerfile +/* +FROM buildpack-deps:jessie + +#verify gpg and sha256: http://nodejs.org/dist/v0.10.30/SHASUMS256.txt.asc +#gpg: aka "Timothy J Fontaine (Work) " +#gpg: aka "Julien Gilli " +RUN gpg --keyserver pool.sks-keyservers.net --recv-keys 7937DFD2AB06298B229 + +EVN NODE_VERSION 0.10.40 +ENV NPM_VERSION 2.11.3 + +RUN curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-l" + && curl -SLO "https://nodesjs.ord/dist/v$NODE_VERSION/SHASUM256.txt.asc" + && gpg --verify SHASUMS256.txt.asc \ + && grep " node-v$NODE_VERSION-linux-x64.tar.gz\$" SHASUMS256.txt.asc | + && tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --stri + && rm "node-v$NODE_VERSION-linux-x64.tar.gz" SHASUMS256.txt.asc \ + && npm install -g npm@"$NPM_VERSION" \ + && npm cache clear + +CMD [ "node" ] +*/ + +// next terminal command +// docker run -it node +// docker pull node +// docker run -it node "drops into node terminal" +// console.log('hello'); + +// terminal commands +//cd node-microservice/ +//inside node-microservice/ +//Dockerfile +//node_modules/ +//package.json +//server.js + +//terminal +//vi server.js + +/* inside server.js +var express = require('express'); +var app = express(); + +app.get('/', function(req, res) { + res.json({'msg': 'helloworld'}) +}); + +var port = process.env.port || 3000; +app.listen(port, function() { + console.log('server started'); +}); +*/ + +//terminal +// node server.js & +// curl http://localhost:3000 +// vi Dockerfile + +/* inside DockerFile +FROM node:0.12.7 + +RUN mkdir -p /user/src/app +WORKDIR /usr/src/app + +COPY . /usr/src/app +RUN npm install + +EXPOSE 3000 + +CMD [ "npm", "start" ] +*/ + +//terminal +//npm install +//rm -r node_modules/ +//docker build -t myservice . +//docker run my-service +//docker run -P -d myservice +//docker ps +//curl http://localhost:37269 +//git init +//git add Dockerfile package.json server.js +//git commit -m 'initial commit dockerized app' + + + + + + + + diff --git a/2-2/Dockerfile b/2-2/Dockerfile new file mode 100644 index 0000000..7ac2798 --- /dev/null +++ b/2-2/Dockerfile @@ -0,0 +1,11 @@ +FROM node:0.12.7 + +RUN mkdir -p /user/src/app +WORKDIR /usr/src/app + +COPY . /usr/src/app +RUN npm install + +EXPOSE 3000 + +CMD [ "npm", "start" ] \ No newline at end of file diff --git a/2-2/node_modules/express/History.md b/2-2/node_modules/express/History.md new file mode 100644 index 0000000..c72241b --- /dev/null +++ b/2-2/node_modules/express/History.md @@ -0,0 +1,3062 @@ +4.13.4 / 2016-01-21 +=================== + + * deps: content-disposition@0.5.1 + - perf: enable strict mode + * deps: cookie@0.1.5 + - Throw on invalid values provided to `serialize` + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: finalhandler@0.4.1 + - deps: escape-html@~1.0.3 + * deps: merge-descriptors@1.0.1 + - perf: enable strict mode + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + * deps: proxy-addr@~1.0.10 + - deps: ipaddr.js@1.0.5 + - perf: enable strict mode + * deps: range-parser@~1.0.3 + - perf: enable strict mode + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + * deps: serve-static@~1.10.2 + - deps: escape-html@~1.0.3 + - deps: parseurl@~1.3.0 + - deps: send@0.13.1 + +4.13.3 / 2015-08-02 +=================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + +4.13.2 / 2015-07-31 +=================== + + * deps: accepts@~1.2.12 + - deps: mime-types@~2.1.4 + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +4.13.1 / 2015-07-05 +=================== + + * deps: accepts@~1.2.10 + - deps: mime-types@~2.1.2 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +4.13.0 / 2015-06-20 +=================== + + * Add settings to debug output + * Fix `res.format` error when only `default` provided + * Fix issue where `next('route')` in `app.param` would incorrectly skip values + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * Simplify `res.cookie` to call `res.append` + * Use `array-flatten` module for flattening arrays + * deps: accepts@~1.2.9 + - deps: mime-types@~2.1.1 + - perf: avoid argument reassignment & argument slice + - perf: avoid negotiator recursive construction + - perf: enable strict mode + - perf: remove unnecessary bitwise operator + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: finalhandler@0.4.0 + - Fix a false-positive when unpiping in Node.js 0.8 + - Support `statusCode` property on `Error` objects + - Use `unpipe` module for unpiping requests + - deps: escape-html@1.0.2 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: path-to-regexp@0.1.6 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * deps: serve-static@~1.10.0 + - Add `fallthrough` option + - Fix reading options from options prototype + - Improve the default redirect response headers + - Malformed URLs now `next()` instead of 400 + - deps: escape-html@1.0.2 + - deps: send@0.13.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: isolate `app.render` try block + * perf: remove argument reassignments in application + * perf: remove argument reassignments in request prototype + * perf: remove argument reassignments in response prototype + * perf: remove argument reassignments in routing + * perf: remove argument reassignments in `View` + * perf: skip attempting to decode zero length string + * perf: use saved reference to `http.STATUS_CODES` + +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 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * 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 + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * 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 + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw un-catchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.21.2 / 2015-07-31 +=================== + + * deps: connect@2.30.2 + - deps: body-parser@~1.13.3 + - deps: compression@~1.5.2 + - deps: errorhandler@~1.4.2 + - deps: method-override@~2.3.5 + - deps: serve-index@~1.7.2 + - deps: type-is@~1.6.6 + - deps: vhost@~3.0.1 + * deps: vary@~1.0.1 + - Fix setting empty header from empty `field` + - perf: enable strict mode + - perf: remove argument reassignments + +3.21.1 / 2015-07-05 +=================== + + * deps: basic-auth@~1.0.3 + * deps: connect@2.30.1 + - deps: body-parser@~1.13.2 + - deps: compression@~1.5.1 + - deps: errorhandler@~1.4.1 + - deps: morgan@~1.6.1 + - deps: pause@0.1.0 + - deps: qs@4.0.0 + - deps: serve-index@~1.7.1 + - deps: type-is@~1.6.4 + +3.21.0 / 2015-06-18 +=================== + + * deps: basic-auth@1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: connect@2.30.0 + - deps: body-parser@~1.13.1 + - deps: bytes@2.1.0 + - deps: compression@~1.5.0 + - deps: cookie@0.1.3 + - deps: cookie-parser@~1.3.5 + - deps: csurf@~1.8.3 + - deps: errorhandler@~1.4.0 + - deps: express-session@~1.11.3 + - deps: finalhandler@0.4.0 + - deps: fresh@0.3.0 + - deps: morgan@~1.6.0 + - deps: serve-favicon@~2.3.0 + - deps: serve-index@~1.7.0 + - deps: serve-static@~1.10.0 + - deps: type-is@~1.6.3 + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: mkdirp@0.5.1 + - Work in global strict mode + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + +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 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * 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 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes charset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Closes #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delimited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using using charset utf-8 + * Fixed show-exceptions page, now using using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie complation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'. + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error response support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independent specs for those who cant build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/2-2/node_modules/express/LICENSE b/2-2/node_modules/express/LICENSE new file mode 100644 index 0000000..aa927e4 --- /dev/null +++ b/2-2/node_modules/express/LICENSE @@ -0,0 +1,24 @@ +(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 +'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/2-2/node_modules/express/Readme.md b/2-2/node_modules/express/Readme.md new file mode 100644 index 0000000..6e08454 --- /dev/null +++ b/2-2/node_modules/express/Readme.md @@ -0,0 +1,138 @@ +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) + + Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). + + [![NPM Version][npm-image]][npm-url] + [![NPM Downloads][downloads-image]][downloads-url] + [![Linux Build][travis-image]][travis-url] + [![Windows Build][appveyor-image]][appveyor-url] + [![Test Coverage][coveralls-image]][coveralls-url] + +```js +var express = require('express') +var app = express() + +app.get('/', function (req, res) { + res.send('Hello World') +}) + +app.listen(3000) +``` + +## Installation + +```bash +$ npm install express +``` + +## Features + + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly + +## Docs & Community + + * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC + * [Github Organization](https://github.com/expressjs) for Official Middleware & Modules + * [Google Group](https://groups.google.com/group/express-js) for discussion + * [Gitter](https://gitter.im/expressjs/express) for support and discussion + * [Русскоязычная документация](http://jsman.ru/express/) + +###Security Issues + +If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). + +## Quick Start + + 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: + + Install the executable. The executable's major version will match Express's: + +```bash +$ npm install -g express-generator@4 +``` + + Create the app: + +```bash +$ express /tmp/foo && cd /tmp/foo +``` + + Install dependencies: + +```bash +$ npm install +``` + + Start the server: + +```bash +$ npm start +``` + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, web sites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), + you can quickly craft your perfect framework. + +## Examples + + To view the examples, clone the Express repo and install the dependencies: + +```bash +$ git clone git://github.com/expressjs/express.git --depth 1 +$ cd express +$ npm install +``` + + Then run whichever example you want: + +```bash +$ node examples/content-negotiation +``` + +## Tests + + To run the test suite, first install the dependencies, then run `npm test`: + +```bash +$ npm install +$ npm test +``` + +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) [![TJ's Gratipay][gratipay-image-visionmedia]][gratipay-url-visionmedia] + +The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) [![Doug's Gratipay][gratipay-image-dougwilson]][gratipay-url-dougwilson] + +[List of all contributors](https://github.com/expressjs/express/graphs/contributors) + +## License + + [MIT](LICENSE) + +[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 +[downloads-url]: https://npmjs.org/package/express +[travis-image]: https://img.shields.io/travis/expressjs/express/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/express +[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/expressjs/express/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master +[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 +[gratipay-url-dougwilson]: https://gratipay.com/dougwilson/ diff --git a/2-2/node_modules/express/index.js b/2-2/node_modules/express/index.js new file mode 100644 index 0000000..d219b0c --- /dev/null +++ b/2-2/node_modules/express/index.js @@ -0,0 +1,11 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +module.exports = require('./lib/express'); diff --git a/2-2/node_modules/express/lib/application.js b/2-2/node_modules/express/lib/application.js new file mode 100644 index 0000000..0ee4def --- /dev/null +++ b/2-2/node_modules/express/lib/application.js @@ -0,0 +1,643 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var finalhandler = require('finalhandler'); +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var merge = require('utils-merge'); +var resolve = require('path').resolve; +var slice = Array.prototype.slice; + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Variable for trust proxy inheritance back-compat + * @private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ + +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; + + this.defaultConfiguration(); +}; + +/** + * Initialize application configuration. + * @private + */ + +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + 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); + + 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; + this.settings.__proto__ = parent.settings; + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; + +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ + +app.handle = function handle(req, res, callback) { + var router = this._router; + + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ + +app.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires middleware functions'); + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + req.__proto__ = orig.request; + res.__proto__ = orig.response; + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } + + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; + + // store engine + this.engines[extension] = fn; + + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.param = function param(name, fn) { + this.lazyrouter(); + + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } + + return this; + } + + this._router.param(name, fn); + + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge app.locals + merge(renderOptions, this.locals); + + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } + + // merge options + merge(renderOptions, opts); + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} diff --git a/2-2/node_modules/express/lib/express.js b/2-2/node_modules/express/lib/express.js new file mode 100644 index 0000000..540c8be --- /dev/null +++ b/2-2/node_modules/express/lib/express.js @@ -0,0 +1,103 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + app.request = { __proto__: req, app: app }; + app.response = { __proto__: res, app: app }; + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.query = require('./middleware/query'); +exports.static = require('serve-static'); + +/** + * Replace removed middleware with an appropriate error message. + */ + +[ + 'json', + 'urlencoded', + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache', +].forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/2-2/node_modules/express/lib/middleware/init.js b/2-2/node_modules/express/lib/middleware/init.js new file mode 100644 index 0000000..f3119ed --- /dev/null +++ b/2-2/node_modules/express/lib/middleware/init.js @@ -0,0 +1,36 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ + +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; + + req.__proto__ = app.request; + res.__proto__ = app.response; + + res.locals = res.locals || Object.create(null); + + next(); + }; +}; + diff --git a/2-2/node_modules/express/lib/middleware/query.js b/2-2/node_modules/express/lib/middleware/query.js new file mode 100644 index 0000000..a665f3f --- /dev/null +++ b/2-2/node_modules/express/lib/middleware/query.js @@ -0,0 +1,51 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var parseUrl = require('parseurl'); +var qs = require('qs'); + +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = Object.create(options || null); + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + + if (opts !== undefined) { + if (opts.allowDots === undefined) { + opts.allowDots = false; + } + + if (opts.allowPrototypes === undefined) { + opts.allowPrototypes = true; + } + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; diff --git a/2-2/node_modules/express/lib/request.js b/2-2/node_modules/express/lib/request.js new file mode 100644 index 0000000..33cac18 --- /dev/null +++ b/2-2/node_modules/express/lib/request.js @@ -0,0 +1,489 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + */ + +var req = exports = module.exports = { + __proto__: http.IncomingMessage.prototype +}; + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ + +req.get = +req.header = function header(name) { + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", 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. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + +/** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param {Number} size + * @return {Array} + * @public + */ + +req.range = function(size){ + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ + +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; +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + proto = this.get('X-Forwarded-Proto') || proto; + return proto.split(/\s*,\s*/)[0]; +}); + +/** + * Short-hand for: + * + * req.protocol == 'https' + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + return addrs.slice(1).reverse(); +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +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, 0)) { + host = this.get('Host'); + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var s = this.res.statusCode; + + // GET or HEAD for weak freshness validation only + if ('GET' != method && 'HEAD' != method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((s >= 200 && s < 300) || 304 == s) { + return fresh(this.headers, (this.res._headers || {})); + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +}; diff --git a/2-2/node_modules/express/lib/response.js b/2-2/node_modules/express/lib/response.js new file mode 100644 index 0000000..641704b --- /dev/null +++ b/2-2/node_modules/express/lib/response.js @@ -0,0 +1,1053 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var contentDisposition = require('content-disposition'); +var deprecate = require('depd')('express'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var isAbsolute = require('./utils').isAbsolute; +var onFinished = require('on-finished'); +var path = require('path'); +var merge = require('utils-merge'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var statusCodes = http.STATUS_CODES; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = require('vary'); + +/** + * Response prototype. + */ + +var res = module.exports = { + __proto__: http.ServerResponse.prototype +}; + +/** + * Module variables. + * @private + */ + +var charsetRegExp = /;\s*charset\s*=/; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ + +res.status = function status(code) { + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ + +res.send = function send(body) { + var chunk = body; + var encoding; + var len; + var req = this.req; + var type; + + // settings + var app = this.app; + + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } + } + + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statusCodes[chunk]; + } + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + + // populate Content-Length + if (chunk !== undefined) { + if (!Buffer.isBuffer(chunk)) { + // convert chunk to Buffer; saves later double conversions + chunk = new Buffer(chunk, encoding); + encoding = undefined; + } + + len = chunk.length; + this.set('Content-Length', len); + } + + // 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); + } + } + + // freshness + if (req.fresh) this.statusCode = 304; + + // strip irrelevant headers + if (204 == this.statusCode || 304 == this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.json = function json(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = JSON.stringify(val, replacer, spaces); + + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.jsonp = function jsonp(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = JSON.stringify(val, replacer, spaces); + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.charset = 'utf-8'; + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = statusCodes[statusCode] || String(statusCode); + + this.statusCode = statusCode; + this.type('txt'); + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } + + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // create file stream + var file = send(req, path, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') { + next(err); + } + }); +}; + +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + * + * @public + */ + +res.download = function download(path, filename, callback) { + var done = callback; + var name = filename; + + // support function as second arg + if (typeof filename === 'function') { + done = filename; + name = null; + } + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // Resolve the full path for sendFile + var fullPath = resolve(path); + + return this.sendFile(fullPath, { headers: headers }, done); +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ + +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + + return this.set('Content-Type', ct); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

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

hey

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

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

'; + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ + +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } + + vary(this, field); + + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// 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() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + 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; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} diff --git a/2-2/node_modules/express/lib/router/index.js b/2-2/node_modules/express/lib/router/index.js new file mode 100644 index 0000000..504ed9c --- /dev/null +++ b/2-2/node_modules/express/lib/router/index.js @@ -0,0 +1,645 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Route = require('./route'); +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 flatten = require('array-flatten'); +var parseUrl = require('parseurl'); + +/** + * Module variables. + * @private + */ + +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} options + * @return {Router} which is an callable function + * @public + */ + +var proto = module.exports = function(options) { + var opts = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + router.__proto__ = proto; + + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; + + return router; +}; + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } + + // apply param functions + var params = this._params; + var len = params.length; + 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); + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } + + // ensure we end up with a + // middleware function + if ('function' != typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; + +/** + * Dispatch a req, res into the router. + * @private + */ + +proto.handle = function handle(req, res, out) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var search = 1 + req.url.indexOf('?'); + var pathlength = search ? search - 1 : req.url.length; + var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://'); + var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''; + var idx = 0; + var removed = ''; + var slashAdded = false; + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } + + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; + + // 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 = ''; + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } + + // 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); + } + + if (route) { + return layer.handle_request(req, res, next); + } + + trim_prefix(layer, layerError, layerPath, path); + }); + } + + function trim_prefix(layer, layerError, layerPath, path) { + var c = path[layerPath.length]; + if (c && '/' !== c && '.' !== c) return next(layerError); + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + if (layerPath.length !== 0) { + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); + + // Ensure leading slash + if (!fqdn && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Process any parameters for the layer. + * @private + */ + +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; + + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); + } + + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } + + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + + if (!key) { + return done(); + } + + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; + + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; + + // next param + return param(paramCalled.error); + } + + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } + + param(); +}; + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +proto.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var callbacks = flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires middleware functions'); + } + + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; + + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn)); + } + + // add the middleware + debug('use %s %s', path, fn.name || ''); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + } + + return this; +}; + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public + */ + +proto.route = function route(path) { + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; +}; + +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +// 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; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(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) { + return params; + } + + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } + + var i = 0; + var o = 0; + + // determine numeric gaps + while (i in params) { + i++; + } + + while (o in parent) { + o++; + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } + + return mixin(obj, params); +} + +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); + + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + + return function(err){ + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; +} + +// 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() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} diff --git a/2-2/node_modules/express/lib/router/layer.js b/2-2/node_modules/express/lib/router/layer.js new file mode 100644 index 0000000..fe9210c --- /dev/null +++ b/2-2/node_modules/express/lib/router/layer.js @@ -0,0 +1,176 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var pathRegexp = require('path-to-regexp'); +var debug = require('debug')('express:router:layer'); + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Module exports. + * @public + */ + +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %s', path); + var opts = options || {}; + + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); + + if (path === '/' && opts.end === false) { + this.regexp.fast_slash = true; + } +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; + + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } + + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); + } + + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match(path) { + if (path == null) { + // no path, nothing matches + this.params = undefined; + this.path = undefined; + return false; + } + + if (this.regexp.fast_slash) { + // fast path non-ending match for / (everything matches) + this.params = {}; + this.path = ''; + return true; + } + + var m = this.regexp.exec(path); + + if (!m) { + this.params = undefined; + this.path = undefined; + return false; + } + + // store values + this.params = {}; + this.path = m[0]; + + var keys = this.keys; + var params = this.params; + + for (var i = 1; i < m.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(m[i]); + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } + + return true; +}; + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } + + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } + + throw err; + } +} diff --git a/2-2/node_modules/express/lib/router/route.js b/2-2/node_modules/express/lib/router/route.js new file mode 100644 index 0000000..2788d7b --- /dev/null +++ b/2-2/node_modules/express/lib/router/route.js @@ -0,0 +1,210 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:router:route'); +var flatten = require('array-flatten'); +var Layer = require('./layer'); +var methods = require('methods'); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Module exports. + * @public + */ + +module.exports = Route; + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ + +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %s', path); + + // route handlers for various http methods + this.methods = {}; +} + +/** + * Determine if the route handles a given method. + * @private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } + + var name = method.toLowerCase(); + + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } + + return Boolean(this.methods[name]); +}; + +/** + * @return {Array} supported HTTP methods + * @private + */ + +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; +}; + +/** + * dispatch req, res into this route + * @private + */ + +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); + } + + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = this; + + next(); + + function next(err) { + if (err && err === 'route') { + return done(); + } + + var layer = stack[idx++]; + if (!layer) { + return done(err); + } + + if (layer.method && layer.method !== method) { + return next(err); + } + + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires callback functions but got a ' + type; + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); + } + + return this; +}; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires callback functions but got a ' + type; + throw new Error(msg); + } + + debug('%s %s', method, this.path); + + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + } + + return this; + }; +}); diff --git a/2-2/node_modules/express/lib/utils.js b/2-2/node_modules/express/lib/utils.js new file mode 100644 index 0000000..3d54247 --- /dev/null +++ b/2-2/node_modules/express/lib/utils.js @@ -0,0 +1,300 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @api private + */ + +var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var mime = require('send').mime; +var basename = require('path').basename; +var etag = require('etag'); +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); + +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = function (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? new Buffer(body, encoding) + : body; + + return etag(buf, {weak: false}); +}; + +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = function wetag(body, encoding){ + var buf = !Buffer.isBuffer(body) + ? new Buffer(body, encoding) + : body; + + return etag(buf, {weak: true}); +}; + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +exports.isAbsolute = function(path){ + if ('/' == path[0]) return true; + if (':' == path[1] && '\\' == path[2]) return true; + if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; + +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' == pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowDots: false, + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} diff --git a/2-2/node_modules/express/lib/view.js b/2-2/node_modules/express/lib/view.js new file mode 100644 index 0000000..52415d4 --- /dev/null +++ b/2-2/node_modules/express/lib/view.js @@ -0,0 +1,173 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:view'); +var path = require('path'); +var fs = require('fs'); +var utils = require('./utils'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ + +function View(name, options) { + var opts = options || {}; + + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; + } + + if (!opts.engines[this.ext]) { + // load engine + opts.engines[this.ext] = require(this.ext.substr(1)).__express; + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); + + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/2-2/node_modules/express/node_modules/accepts/HISTORY.md b/2-2/node_modules/express/node_modules/accepts/HISTORY.md new file mode 100644 index 0000000..397636e --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/HISTORY.md @@ -0,0 +1,170 @@ +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +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 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/2-2/node_modules/express/node_modules/accepts/LICENSE b/2-2/node_modules/express/node_modules/accepts/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/2-2/node_modules/express/node_modules/accepts/README.md b/2-2/node_modules/express/node_modules/accepts/README.md new file mode 100644 index 0000000..ae36676 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/README.md @@ -0,0 +1,135 @@ +# accepts + +[![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] + +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 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 `*` + +## Installation + +```sh +npm install accepts +``` + +## API + +```js +var accepts = require('accepts') +``` + +### 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) +``` + +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 +[npm-url]: https://npmjs.org/package/accepts +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/accepts +[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 +[downloads-url]: https://npmjs.org/package/accepts diff --git a/2-2/node_modules/express/node_modules/accepts/index.js b/2-2/node_modules/express/node_modules/accepts/index.js new file mode 100644 index 0000000..e80192a --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/index.js @@ -0,0 +1,231 @@ +/*! + * 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') + +/** + * 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 = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +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 = this.negotiator.mediaTypes(mimes.filter(validMime)); + var first = accepts[0]; + if (!first) return false; + return types[mimes.indexOf(first)]; +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +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 +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +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 +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +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 +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime(type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ + +function validMime(type) { + return typeof type === 'string'; +} diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..61b54b4 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md @@ -0,0 +1,183 @@ +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +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 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md new file mode 100644 index 0000000..e26295d --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md @@ -0,0 +1,103 @@ +# mime-types + +[![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] + +The ultimate javascript content-type utility. + +Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, + so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db) +- No `.define()` functionality + +Otherwise, the API is compatible. + +## Install + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://github.com/jshttp/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[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/node/v/mime-types.svg +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js new file mode 100644 index 0000000..f7008b2 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js @@ -0,0 +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 + +/** + * 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) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..41a667a --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -0,0 +1,306 @@ +1.21.0 / 2016-01-06 +=================== + + * Add `application/emergencycalldata.comment+xml` + * Add `application/emergencycalldata.deviceinfo+xml` + * Add `application/emergencycalldata.providerinfo+xml` + * Add `application/emergencycalldata.serviceinfo+xml` + * Add `application/emergencycalldata.subscriberinfo+xml` + * Add `application/vnd.filmit.zfc` + * Add `application/vnd.google-apps.document` + * Add `application/vnd.google-apps.presentation` + * Add `application/vnd.google-apps.spreadsheet` + * Add `application/vnd.mapbox-vector-tile` + * Add `application/vnd.ms-printdevicecapabilities+xml` + * Add `application/vnd.ms-windows.devicepairing` + * Add `application/vnd.ms-windows.nwprinting.oob` + * Add `application/vnd.tml` + * Add `audio/evs` + +1.20.0 / 2015-11-10 +=================== + + * Add `application/cdni` + * Add `application/csvm+json` + * Add `application/rfc+xml` + * Add `application/vnd.3gpp.access-transfer-events+xml` + * Add `application/vnd.3gpp.srvcc-ext+xml` + * Add `application/vnd.ms-windows.wsd.oob` + * Add `application/vnd.oxli.countgraph` + * Add `application/vnd.pagerduty+json` + * Add `text/x-suse-ymp` + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.3gpp-prose-pc3ch+xml` + * Add `application/vnd.3gpp.srvcc-info+xml` + * Add `application/vnd.apple.pkpass` + * Add `application/vnd.drive+json` + +1.18.0 / 2015-09-03 +=================== + + * Add `application/pkcs12` + * Add `application/vnd.3gpp-prose+xml` + * Add `application/vnd.3gpp.mid-call+xml` + * Add `application/vnd.3gpp.state-and-event-info+xml` + * Add `application/vnd.anki` + * Add `application/vnd.firemonkeys.cloudcell` + * Add `application/vnd.openblox.game+xml` + * Add `application/vnd.openblox.game-binary` + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +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 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md new file mode 100644 index 0000000..7662440 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md @@ -0,0 +1,82 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +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 + +```bash +npm install mime-db +``` + +### 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 +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + 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 can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +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 +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[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 +[node-url]: http://nodejs.org/download/ diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json new file mode 100644 index 0000000..412ba9e --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json @@ -0,0 +1,6552 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana" + }, + "application/3gpp-ims+xml": { + "source": "iana" + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana" + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana" + }, + "application/bacnet-xdd+zip": { + "source": "iana" + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana" + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana" + }, + "application/ccxml+xml": { + "source": "iana", + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana" + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana" + }, + "application/cellml+xml": { + "source": "iana" + }, + "application/cfw": { + "source": "iana" + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana" + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana" + }, + "application/cstadata+xml": { + "source": "iana" + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "extensions": ["mdp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana" + }, + "application/dicom": { + "source": "iana" + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana" + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/emergencycalldata.comment+xml": { + "source": "iana" + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana" + }, + "application/emma+xml": { + "source": "iana", + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana" + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana" + }, + "application/epub+zip": { + "source": "iana", + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana" + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false, + "extensions": ["woff"] + }, + "application/font-woff2": { + "compressible": false, + "extensions": ["woff2"] + }, + "application/framework-attributes+xml": { + "source": "iana" + }, + "application/gml+xml": { + "source": "apache", + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana" + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana" + }, + "application/ibe-pkg-reply+xml": { + "source": "iana" + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana" + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana" + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana" + }, + "application/kpml-response+xml": { + "source": "iana" + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana" + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana" + }, + "application/mathml-presentation+xml": { + "source": "iana" + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana" + }, + "application/mbms-deregister+xml": { + "source": "iana" + }, + "application/mbms-envelope+xml": { + "source": "iana" + }, + "application/mbms-msk+xml": { + "source": "iana" + }, + "application/mbms-msk-response+xml": { + "source": "iana" + }, + "application/mbms-protection-description+xml": { + "source": "iana" + }, + "application/mbms-reception-report+xml": { + "source": "iana" + }, + "application/mbms-register+xml": { + "source": "iana" + }, + "application/mbms-register-response+xml": { + "source": "iana" + }, + "application/mbms-schedule+xml": { + "source": "iana" + }, + "application/mbms-user-service-description+xml": { + "source": "iana" + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana" + }, + "application/media_control+xml": { + "source": "iana" + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mods+xml": { + "source": "iana", + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana" + }, + "application/mrb-publish+xml": { + "source": "iana" + }, + "application/msc-ivr+xml": { + "source": "iana" + }, + "application/msc-mixer+xml": { + "source": "iana" + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "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", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana" + }, + "application/parityfec": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana" + }, + "application/pidf-diff+xml": { + "source": "iana" + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana" + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/provenance+xml": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana" + }, + "application/pskc+xml": { + "source": "iana", + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf"] + }, + "application/reginfo+xml": { + "source": "iana", + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana" + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana" + }, + "application/rls-services+xml": { + "source": "iana", + "extensions": ["rs"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana" + }, + "application/samlmetadata+xml": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana" + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/sep+xml": { + "source": "iana" + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana" + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana" + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "extensions": ["ssml"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/ttml+xml": { + "source": "iana" + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana" + }, + "application/urc-ressheet+xml": { + "source": "iana" + }, + "application/urc-targetdesc+xml": { + "source": "iana" + }, + "application/urc-uisocketdesc+xml": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana" + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana" + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana" + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana" + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "extensions": ["mpkg"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avistar+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "extensions": ["cdxml"] + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana" + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana" + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana" + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume-movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana" + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana" + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana" + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana" + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana" + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana" + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana" + }, + "application/vnd.etsi.cug+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana" + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana" + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana" + }, + "application/vnd.etsi.sci+xml": { + "source": "iana" + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana" + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana" + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana" + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana" + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana" + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana" + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana" + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana" + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana" + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+xml": { + "source": "iana", + "extensions": ["lasxml"] + }, + "application/vnd.liberty-request+xml": { + "source": "iana" + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana" + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana" + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana" + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache" + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana" + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana" + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana" + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana" + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana" + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana" + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana" + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana" + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana" + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana" + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana" + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana" + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana" + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana" + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana" + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana" + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana" + }, + "application/vnd.omads-email+xml": { + "source": "iana" + }, + "application/vnd.omads-file+xml": { + "source": "iana" + }, + "application/vnd.omads-folder+xml": { + "source": "iana" + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana" + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "apache", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "apache", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "apache", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana" + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana" + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos+xml": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "apache" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana" + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana" + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana" + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana" + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana" + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana" + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana" + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana" + }, + "application/vnd.wv.ssp+xml": { + "source": "iana" + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana" + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "extensions": ["vxml"] + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/watcherinfo+xml": { + "source": "iana" + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-otf": { + "source": "apache", + "compressible": true, + "extensions": ["otf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-ttf": { + "source": "apache", + "compressible": true, + "extensions": ["ttf","ttc"] + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "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, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "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, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana" + }, + "application/xaml+xml": { + "source": "apache", + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana" + }, + "application/xcap-caps+xml": { + "source": "iana" + }, + "application/xcap-diff+xml": { + "source": "iana", + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana" + }, + "application/xcap-error+xml": { + "source": "iana" + }, + "application/xcap-ns+xml": { + "source": "iana" + }, + "application/xcon-conference-info+xml": { + "source": "iana" + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana" + }, + "application/xenc+xml": { + "source": "iana", + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache" + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana" + }, + "application/xmpp+xml": { + "source": "iana" + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yin+xml": { + "source": "iana", + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana" + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4a","m4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/opentype": { + "compressible": true, + "extensions": ["otf"] + }, + "image/bmp": { + "source": "apache", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/fits": { + "source": "iana" + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jp2": { + "source": "iana" + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana" + }, + "image/jpx": { + "source": "iana" + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana" + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana" + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tiff","tif"] + }, + "image/tiff-fx": { + "source": "iana" + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana" + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana" + }, + "image/vnd.valve.source.texture": { + "source": "iana" + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "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"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana" + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana" + }, + "message/global-delivery-status": { + "source": "iana" + }, + "message/global-disposition-notification": { + "source": "iana" + }, + "message/global-headers": { + "source": "iana" + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana" + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana" + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hjson": { + "extensions": ["hjson"] + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana" + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["markdown","md","mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "apache" + }, + "video/3gpp": { + "source": "apache", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "apache" + }, + "video/3gpp2": { + "source": "apache", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "apache" + }, + "video/bt656": { + "source": "apache" + }, + "video/celb": { + "source": "apache" + }, + "video/dv": { + "source": "apache" + }, + "video/h261": { + "source": "apache", + "extensions": ["h261"] + }, + "video/h263": { + "source": "apache", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "apache" + }, + "video/h263-2000": { + "source": "apache" + }, + "video/h264": { + "source": "apache", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "apache" + }, + "video/h264-svc": { + "source": "apache" + }, + "video/jpeg": { + "source": "apache", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "apache" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "apache", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "apache" + }, + "video/mp2p": { + "source": "apache" + }, + "video/mp2t": { + "source": "apache", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "apache", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "apache" + }, + "video/mpeg": { + "source": "apache", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "apache" + }, + "video/mpv": { + "source": "apache" + }, + "video/nv": { + "source": "apache" + }, + "video/ogg": { + "source": "apache", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "apache" + }, + "video/pointer": { + "source": "apache" + }, + "video/quicktime": { + "source": "apache", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raw": { + "source": "apache" + }, + "video/rtp-enc-aescm128": { + "source": "apache" + }, + "video/rtx": { + "source": "apache" + }, + "video/smpte292m": { + "source": "apache" + }, + "video/ulpfec": { + "source": "apache" + }, + "video/vc1": { + "source": "apache" + }, + "video/vnd.cctv": { + "source": "apache" + }, + "video/vnd.dece.hd": { + "source": "apache", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "apache", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "apache" + }, + "video/vnd.dece.pd": { + "source": "apache", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "apache", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "apache", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "apache" + }, + "video/vnd.directv.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dvb.file": { + "source": "apache", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "apache", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "apache" + }, + "video/vnd.motorola.video": { + "source": "apache" + }, + "video/vnd.motorola.videop": { + "source": "apache" + }, + "video/vnd.mpegurl": { + "source": "apache", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "apache", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "apache" + }, + "video/vnd.nokia.videovoip": { + "source": "apache" + }, + "video/vnd.objectvideo": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "apache" + }, + "video/vnd.sealed.mpeg4": { + "source": "apache" + }, + "video/vnd.sealed.swf": { + "source": "apache" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "apache" + }, + "video/vnd.uvvu.mp4": { + "source": "apache", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "apache", + "extensions": ["viv"] + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json new file mode 100644 index 0000000..e6c9732 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json @@ -0,0 +1,94 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.21.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "devDependencies": { + "bluebird": "3.1.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "1.0.1", + "gnode": "0.1.1", + "istanbul": "0.4.1", + "mocha": "1.21.5", + "raw-body": "2.1.5", + "stream-to-array": "2.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "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": "9ab92f0a912a602408a64db5741dfef6f82c597f", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "homepage": "https://github.com/jshttp/mime-db", + "_id": "mime-db@1.21.0", + "_shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "_from": "mime-db@>=1.21.0 <1.22.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" + } + ], + "dist": { + "shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json new file mode 100644 index 0000000..d1a5ffa --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json @@ -0,0 +1,84 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "dependencies": { + "mime-db": "~1.21.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec test/test.js", + "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": "329f1c77e1a77c8fac59b15038e3808e9e314d96", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "homepage": "https://github.com/jshttp/mime-types", + "_id": "mime-types@2.1.9", + "_shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "_from": "mime-types@>=2.1.6 <2.2.0", + "_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" + } + ], + "dist": { + "shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md new file mode 100644 index 0000000..aa2a7c4 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md @@ -0,0 +1,76 @@ +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE new file mode 100644 index 0000000..ea6b9e2 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +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 +'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/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md new file mode 100644 index 0000000..ef507fa --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md @@ -0,0 +1,203 @@ +# negotiator + +[![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] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +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 + +```js +negotiator = new Negotiator(request) + +availableLanguages = 'en', 'es', 'fr' + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +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 + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +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 + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +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 +[npm-url]: https://npmjs.org/package/negotiator +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/negotiator +[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 +[downloads-url]: https://npmjs.org/package/negotiator diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js new file mode 100644 index 0000000..edae9cf --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js @@ -0,0 +1,62 @@ + +var preferredCharsets = require('./lib/charset'); +var preferredEncodings = require('./lib/encoding'); +var preferredLanguages = require('./lib/language'); +var preferredMediaTypes = require('./lib/mediaType'); + +module.exports = Negotiator; +Negotiator.Negotiator = Negotiator; + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available) { + var set = this.encodings(available); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available) { + return preferredEncodings(this.request.headers['accept-encoding'], available); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; diff --git a/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js new file mode 100644 index 0000000..7abd17c --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js @@ -0,0 +1,102 @@ +module.exports = preferredCharsets; +preferredCharsets.preferredCharsets = preferredCharsets; + +function parseAcceptCharset(accept) { + 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) { + var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +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; + } + } + + return priority; +} + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + 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/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js new file mode 100644 index 0000000..7fed673 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,118 @@ +module.exports = preferredEncodings; +preferredEncodings.preferredEncodings = preferredEncodings; + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + 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 (!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 + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +function parseEncoding(s, i) { + var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); + + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +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; + } + } + + return priority; +} + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +function preferredEncodings(accept, provided) { + 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/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js new file mode 100644 index 0000000..ed9e1ec --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js @@ -0,0 +1,112 @@ +module.exports = preferredLanguages; +preferredLanguages.preferredLanguages = preferredLanguages; + +function parseAcceptLanguage(accept) { + 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) { + var match = s.match(/^\s*(\S+?)(?:-(\S+?))?\s*(?:;(.*))?$/); + if (!match) return null; + + var prefix = match[1], + suffix = match[2], + full = prefix; + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +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; + } + } + + return priority; +} + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + 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/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 0000000..4170c25 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,179 @@ +/** + * 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) { + 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) { + var match = s.match(/\s*(\S+?)\/([^;\s]+)\s*(?:;(.*))?/); + if (!match) return null; + + var type = match[1], + subtype = match[2], + full = "" + type + "/" + subtype, + params = {}, + q = 1; + + if (match[3]) { + params = match[3].split(';').map(function(s) { + return s.trim().split('='); + }).reduce(function (set, p) { + 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) { + q = parseFloat(params.q); + delete params.q; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i, + full: full + }; +} + +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; + } + } + + return priority; +} + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } + +} + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + 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/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json new file mode 100644 index 0000000..66d2824 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json @@ -0,0 +1,86 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "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/" + } + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/negotiator.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "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": "cbb717b3f164f25820f90b160cda6d0166b9d922", + "bugs": { + "url": "https://github.com/jshttp/negotiator/issues" + }, + "homepage": "https://github.com/jshttp/negotiator", + "_id": "negotiator@0.5.3", + "_shasum": "269d5c476810ec92edbe7b6c2f28316384f9a7e8", + "_from": "negotiator@0.5.3", + "_npmVersion": "1.4.28", + "_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": "269d5c476810ec92edbe7b6c2f28316384f9a7e8", + "tarball": "http://registry.npmjs.org/negotiator/-/negotiator-0.5.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.5.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/accepts/package.json b/2-2/node_modules/express/node_modules/accepts/package.json new file mode 100644 index 0000000..6455e64 --- /dev/null +++ b/2-2/node_modules/express/node_modules/accepts/package.json @@ -0,0 +1,98 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "1.2.13", + "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": "git+https://github.com/jshttp/accepts.git" + }, + "dependencies": { + "mime-types": "~2.1.6", + "negotiator": "0.5.3" + }, + "devDependencies": { + "istanbul": "0.3.19", + "mocha": "~1.21.5" + }, + "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/" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ], + "gitHead": "b7e15ecb25dacc0b2133ed0553d64f8a79537e01", + "bugs": { + "url": "https://github.com/jshttp/accepts/issues" + }, + "homepage": "https://github.com/jshttp/accepts", + "_id": "accepts@1.2.13", + "_shasum": "e5f1f3928c6d95fd96558c36ec3d9d0de4a6ecea", + "_from": "accepts@>=1.2.12 <1.3.0", + "_npmVersion": "1.4.28", + "_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": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "e5f1f3928c6d95fd96558c36ec3d9d0de4a6ecea", + "tarball": "http://registry.npmjs.org/accepts/-/accepts-1.2.13.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.2.13.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/array-flatten/LICENSE b/2-2/node_modules/express/node_modules/array-flatten/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/2-2/node_modules/express/node_modules/array-flatten/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/2-2/node_modules/express/node_modules/array-flatten/README.md b/2-2/node_modules/express/node_modules/array-flatten/README.md new file mode 100644 index 0000000..91fa5b6 --- /dev/null +++ b/2-2/node_modules/express/node_modules/array-flatten/README.md @@ -0,0 +1,43 @@ +# Array Flatten + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +> Flatten an array of nested arrays into a single flat array. Accepts an optional depth. + +## Installation + +``` +npm install array-flatten --save +``` + +## Usage + +```javascript +var flatten = require('array-flatten') + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) +//=> [1, 2, 3, 4, 5, 6, 7, 8, 9] + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) +//=> [1, 2, 3, [4, [5], 6], 7, 8, 9] + +(function () { + flatten(arguments) //=> [1, 2, 3] +})(1, [2, 3]) +``` + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat +[npm-url]: https://npmjs.org/package/array-flatten +[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat +[downloads-url]: https://npmjs.org/package/array-flatten +[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat +[travis-url]: https://travis-ci.org/blakeembrey/array-flatten +[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat +[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master diff --git a/2-2/node_modules/express/node_modules/array-flatten/array-flatten.js b/2-2/node_modules/express/node_modules/array-flatten/array-flatten.js new file mode 100644 index 0000000..089117b --- /dev/null +++ b/2-2/node_modules/express/node_modules/array-flatten/array-flatten.js @@ -0,0 +1,64 @@ +'use strict' + +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result +} + +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result +} + +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) +} diff --git a/2-2/node_modules/express/node_modules/array-flatten/package.json b/2-2/node_modules/express/node_modules/array-flatten/package.json new file mode 100644 index 0000000..f80f937 --- /dev/null +++ b/2-2/node_modules/express/node_modules/array-flatten/package.json @@ -0,0 +1,62 @@ +{ + "name": "array-flatten", + "version": "1.1.1", + "description": "Flatten an array of nested arrays into a single flat array", + "main": "array-flatten.js", + "files": [ + "array-flatten.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/blakeembrey/array-flatten.git" + }, + "keywords": [ + "array", + "flatten", + "arguments", + "depth" + ], + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/blakeembrey/array-flatten/issues" + }, + "homepage": "https://github.com/blakeembrey/array-flatten", + "devDependencies": { + "istanbul": "^0.3.13", + "mocha": "^2.2.4", + "pre-commit": "^1.0.7", + "standard": "^3.7.3" + }, + "gitHead": "1963a9189229d408e1e8f585a00c8be9edbd1803", + "_id": "array-flatten@1.1.1", + "_shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2", + "_from": "array-flatten@1.1.1", + "_npmVersion": "2.11.3", + "_nodeVersion": "2.3.3", + "_npmUser": { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + }, + "maintainers": [ + { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + } + ], + "dist": { + "shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2", + "tarball": "http://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/content-disposition/HISTORY.md b/2-2/node_modules/express/node_modules/content-disposition/HISTORY.md new file mode 100644 index 0000000..76d494c --- /dev/null +++ b/2-2/node_modules/express/node_modules/content-disposition/HISTORY.md @@ -0,0 +1,45 @@ +0.5.1 / 2016-01-17 +================== + + * perf: enable strict mode + +0.5.0 / 2014-10-11 +================== + + * Add `parse` function + +0.4.0 / 2014-09-21 +================== + + * Expand non-Unicode `filename` to the full ISO-8859-1 charset + +0.3.0 / 2014-09-20 +================== + + * Add `fallback` option + * Add `type` option + +0.2.0 / 2014-09-19 +================== + + * Reduce ambiguity of file names with hex escape in buggy browsers + +0.1.2 / 2014-09-19 +================== + + * Fix periodic invalid Unicode filename header + +0.1.1 / 2014-09-19 +================== + + * Fix invalid characters appearing in `filename*` parameter + +0.1.0 / 2014-09-18 +================== + + * Make the `filename` argument optional + +0.0.0 / 2014-09-18 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/content-disposition/LICENSE b/2-2/node_modules/express/node_modules/content-disposition/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/2-2/node_modules/express/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/content-disposition/README.md b/2-2/node_modules/express/node_modules/content-disposition/README.md new file mode 100644 index 0000000..5cebce4 --- /dev/null +++ b/2-2/node_modules/express/node_modules/content-disposition/README.md @@ -0,0 +1,141 @@ +# content-disposition + +[![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] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + +```js +var contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + +```js +var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'); +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +var contentDisposition = require('content-disposition') +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +var filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest(req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + var stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://tools.ietf.org/html/rfc2616 +[rfc-5987]: https://tools.ietf.org/html/rfc5987 +[rfc-6266]: https://tools.ietf.org/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition.svg?style=flat +[npm-url]: https://npmjs.org/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/content-disposition +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg?style=flat +[downloads-url]: https://npmjs.org/package/content-disposition diff --git a/2-2/node_modules/express/node_modules/content-disposition/index.js b/2-2/node_modules/express/node_modules/content-disposition/index.js new file mode 100644 index 0000000..4a352dc --- /dev/null +++ b/2-2/node_modules/express/node_modules/content-disposition/index.js @@ -0,0 +1,445 @@ +/*! + * content-disposition + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * Module dependencies. + */ + +var basename = require('path').basename + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + */ + +var encodeUriAttrCharRegExp = /[\x00-\x20"'\(\)*,\/:;<=>?@\[\\\]\{\}\x7f]/g + +/** + * RegExp to match percent encoding escape. + */ + +var hexEscapeRegExp = /%[0-9A-Fa-f]{2}/ +var hexEscapeReplaceRegExp = /%([0-9A-Fa-f]{2})/g + +/** + * RegExp to match non-latin1 characters. + */ + +var nonLatin1RegExp = /[^\x20-\x7e\xa0-\xff]/g + +/** + * 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 for various RFC 2616 grammar + * + * 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 = + * HT = + * CTL = + * OCTET = + */ + +var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g +var textRegExp = /^[\x20-\x7e\x80-\xff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + */ + +var extValueRegExp = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+\-\.^_`|~])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + */ + +var dispositionTypeRegExp = /^([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *(?:$|;)/ + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @api public + */ + +function contentDisposition(filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @api private + */ + +function createparams(filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && nonLatin1RegExp.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = textRegExp.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || hexEscapeRegExp.test(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @api private + */ + +function format(obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !tokenRegExp.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // 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] + + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 6987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @api private + */ + +function decodefield(str) { + var match = extValueRegExp.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + + // to binary string + var binary = encoded.replace(hexEscapeReplaceRegExp, pdecode) + + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = new Buffer(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @api private + */ + +function getlatin1(val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(nonLatin1RegExp, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @api private + */ + +function parse(string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = dispositionTypeRegExp.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = paramRegExp.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + 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 (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + 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') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @api private + */ + +function pdecode(str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @api private + */ + +function pencode(char) { + var hex = String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() + return hex.length === 1 + ? '%0' + hex + : '%' + hex +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @api private + */ + +function qstring(val) { + var str = String(val) + + return '"' + str.replace(quoteRegExp, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @api private + */ + +function ustring(val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(encodeUriAttrCharRegExp, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + */ + +function ContentDisposition(type, parameters) { + this.type = type + this.parameters = parameters +} diff --git a/2-2/node_modules/express/node_modules/content-disposition/package.json b/2-2/node_modules/express/node_modules/content-disposition/package.json new file mode 100644 index 0000000..1b22eb9 --- /dev/null +++ b/2-2/node_modules/express/node_modules/content-disposition/package.json @@ -0,0 +1,66 @@ +{ + "name": "content-disposition", + "description": "Create and parse Content-Disposition header", + "version": "0.5.1", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-disposition.git" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "7b391db3af5629d4c698f1de21802940bb9f22a5", + "bugs": { + "url": "https://github.com/jshttp/content-disposition/issues" + }, + "homepage": "https://github.com/jshttp/content-disposition", + "_id": "content-disposition@0.5.1", + "_shasum": "87476c6a67c8daa87e32e87616df883ba7fb071b", + "_from": "content-disposition@0.5.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "87476c6a67c8daa87e32e87616df883ba7fb071b", + "tarball": "http://registry.npmjs.org/content-disposition/-/content-disposition-0.5.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/content-type/HISTORY.md b/2-2/node_modules/express/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..8a623a2 --- /dev/null +++ b/2-2/node_modules/express/node_modules/content-type/HISTORY.md @@ -0,0 +1,9 @@ +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/2-2/node_modules/express/node_modules/content-type/LICENSE b/2-2/node_modules/express/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/2-2/node_modules/express/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/2-2/node_modules/express/node_modules/content-type/README.md b/2-2/node_modules/express/node_modules/content-type/README.md new file mode 100644 index 0000000..3ed6741 --- /dev/null +++ b/2-2/node_modules/express/node_modules/content-type/README.md @@ -0,0 +1,92 @@ +# content-type + +[![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] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a content 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 media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({type: 'image/svg+xml'}) +``` + +Format an object into a content type string. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-type.svg +[npm-url]: https://npmjs.org/package/content-type +[node-version-image]: https://img.shields.io/node/v/content-type.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg +[travis-url]: https://travis-ci.org/jshttp/content-type +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-type +[downloads-image]: https://img.shields.io/npm/dm/content-type.svg +[downloads-url]: https://npmjs.org/package/content-type diff --git a/2-2/node_modules/express/node_modules/content-type/index.js b/2-2/node_modules/express/node_modules/content-type/index.js new file mode 100644 index 0000000..6a2ea9f --- /dev/null +++ b/2-2/node_modules/express/node_modules/content-type/index.js @@ -0,0 +1,214 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) */g +var textRegExp = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var qescRegExp = /\\([\u000b\u0020-\u00ff])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var quoteRegExp = /([\\"])/g + +/** + * RegExp to match type in RFC 6838 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+\/[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !typeRegExp.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // 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} + * @public + */ + +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string === 'object') { + // support req/res-like objects as argument + string = getcontenttype(string) + + if (typeof string !== 'string') { + throw new TypeError('content-type header is missing from object'); + } + } + + 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).trim() + : string.trim() + + if (!typeRegExp.test(type)) { + throw new TypeError('invalid media type') + } + + var key + var match + var obj = new ContentType(type.toLowerCase()) + 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') + } + + obj.parameters[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @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} + * @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') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType(type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/2-2/node_modules/express/node_modules/content-type/package.json b/2-2/node_modules/express/node_modules/content-type/package.json new file mode 100644 index 0000000..e23403c --- /dev/null +++ b/2-2/node_modules/express/node_modules/content-type/package.json @@ -0,0 +1,65 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-type.git" + }, + "devDependencies": { + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail 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": "3aa58f9c5a358a3634b8601602177888b4a477d8", + "bugs": { + "url": "https://github.com/jshttp/content-type/issues" + }, + "homepage": "https://github.com/jshttp/content-type", + "_id": "content-type@1.0.1", + "_shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "_from": "content-type@>=1.0.1 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "tarball": "http://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/cookie-signature/.npmignore b/2-2/node_modules/express/node_modules/cookie-signature/.npmignore new file mode 100644 index 0000000..f1250e5 --- /dev/null +++ b/2-2/node_modules/express/node_modules/cookie-signature/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/2-2/node_modules/express/node_modules/cookie-signature/History.md b/2-2/node_modules/express/node_modules/cookie-signature/History.md new file mode 100644 index 0000000..78513cc --- /dev/null +++ b/2-2/node_modules/express/node_modules/cookie-signature/History.md @@ -0,0 +1,38 @@ +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 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/cookie-signature/Readme.md b/2-2/node_modules/express/node_modules/cookie-signature/Readme.md new file mode 100644 index 0000000..2559e84 --- /dev/null +++ b/2-2/node_modules/express/node_modules/cookie-signature/Readme.md @@ -0,0 +1,42 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +(The MIT License) + +Copyright (c) 2012 LearnBoost <tj@learnboost.com> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/2-2/node_modules/express/node_modules/cookie-signature/index.js b/2-2/node_modules/express/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..b8c9463 --- /dev/null +++ b/2-2/node_modules/express/node_modules/cookie-signature/index.js @@ -0,0 +1,51 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie 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) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("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); + + return sha1(mac) == sha1(val) ? str : false; +}; + +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} diff --git a/2-2/node_modules/express/node_modules/cookie-signature/package.json b/2-2/node_modules/express/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..28f87d0 --- /dev/null +++ b/2-2/node_modules/express/node_modules/cookie-signature/package.json @@ -0,0 +1,59 @@ +{ + "name": "cookie-signature", + "version": "1.0.6", + "description": "Sign and unsign cookies", + "keywords": [ + "cookie", + "sign", + "unsign" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@learnboost.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/visionmedia/node-cookie-signature.git" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, + "main": "index", + "gitHead": "391b56cf44d88c493491b7e3fc53208cfb976d2a", + "bugs": { + "url": "https://github.com/visionmedia/node-cookie-signature/issues" + }, + "homepage": "https://github.com/visionmedia/node-cookie-signature", + "_id": "cookie-signature@1.0.6", + "_shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c", + "_from": "cookie-signature@1.0.6", + "_npmVersion": "2.3.0", + "_nodeVersion": "0.10.36", + "_npmUser": { + "name": "natevw", + "email": "natevw@yahoo.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "natevw", + "email": "natevw@yahoo.com" + } + ], + "dist": { + "shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c", + "tarball": "http://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/cookie/HISTORY.md b/2-2/node_modules/express/node_modules/cookie/HISTORY.md new file mode 100644 index 0000000..c9803ce --- /dev/null +++ b/2-2/node_modules/express/node_modules/cookie/HISTORY.md @@ -0,0 +1,72 @@ +0.1.5 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.1.4 / 2015-09-17 +================== + + * Throw better error for invalid argument to parse + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.1.3 / 2015-05-19 +================== + + * Reduce the scope of try-catch deopt + * Remove argument reassignments + +0.1.2 / 2014-04-16 +================== + + * Remove unnecessary files from npm package + +0.1.1 / 2014-02-23 +================== + + * Fix bad parse when cookie value contained a comma + * Fix support for `maxAge` of `0` + +0.1.0 / 2013-05-01 +================== + + * Add `decode` option + * Add `encode` option + +0.0.6 / 2013-04-08 +================== + + * Ignore cookie parts missing `=` + +0.0.5 / 2012-10-29 +================== + + * Return raw cookie value if value unescape errors + +0.0.4 / 2012-06-21 +================== + + * Use encode/decodeURIComponent for cookie encoding/decoding + - Improve server/client interoperability + +0.0.3 / 2012-06-06 +================== + + * Only escape special characters per the cookie RFC + +0.0.2 / 2012-06-01 +================== + + * Fix `maxAge` option to not throw error + +0.0.1 / 2012-05-28 +================== + + * Add more tests + +0.0.0 / 2012-05-28 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/cookie/LICENSE b/2-2/node_modules/express/node_modules/cookie/LICENSE new file mode 100644 index 0000000..e849495 --- /dev/null +++ b/2-2/node_modules/express/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +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 +'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/2-2/node_modules/express/node_modules/cookie/README.md b/2-2/node_modules/express/node_modules/cookie/README.md new file mode 100644 index 0000000..acdb5c2 --- /dev/null +++ b/2-2/node_modules/express/node_modules/cookie/README.md @@ -0,0 +1,64 @@ +# cookie + +[![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] + +cookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers. + +See [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies. + +## how? + +``` +npm install cookie +``` + +```javascript +var cookie = require('cookie'); + +var hdr = cookie.serialize('foo', 'bar'); +// hdr = 'foo=bar'; + +var cookies = cookie.parse('foo=bar; cat=meow; dog=ruff'); +// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' }; +``` + +## more + +The serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values. + +### path +> cookie path + +### expires +> absolute expiration date for the cookie (Date object) + +### maxAge +> relative max age of the cookie from when the client receives it (seconds) + +### domain +> domain for the cookie + +### secure +> true or false + +### httpOnly +> true or false + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/cookie.svg +[npm-url]: https://npmjs.org/package/cookie +[node-version-image]: https://img.shields.io/node/v/cookie.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/cookie/master.svg +[travis-url]: https://travis-ci.org/jshttp/cookie +[coveralls-image]: https://img.shields.io/coveralls/jshttp/cookie/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[downloads-image]: https://img.shields.io/npm/dm/cookie.svg +[downloads-url]: https://npmjs.org/package/cookie diff --git a/2-2/node_modules/express/node_modules/cookie/index.js b/2-2/node_modules/express/node_modules/cookie/index.js new file mode 100644 index 0000000..b8389a1 --- /dev/null +++ b/2-2/node_modules/express/node_modules/cookie/index.js @@ -0,0 +1,156 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var decode = decodeURIComponent; +var encode = encodeURIComponent; + +/** + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF + */ + +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var pairs = str.split(/; */); + var dec = opt.decode || decode; + + pairs.forEach(function(pair) { + var eq_idx = pair.indexOf('=') + + // skip things that don't look like key=value + if (eq_idx < 0) { + return; + } + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + }); + + return obj; +} + +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var pairs = [name + '=' + value]; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + pairs.push('Max-Age=' + maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + + pairs.push('Domain=' + opt.domain); + } + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + pairs.push('Path=' + opt.path); + } + + if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString()); + if (opt.httpOnly) pairs.push('HttpOnly'); + if (opt.secure) pairs.push('Secure'); + + return pairs.join('; '); +} + +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ + +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} diff --git a/2-2/node_modules/express/node_modules/cookie/package.json b/2-2/node_modules/express/node_modules/cookie/package.json new file mode 100644 index 0000000..01399d0 --- /dev/null +++ b/2-2/node_modules/express/node_modules/cookie/package.json @@ -0,0 +1,76 @@ +{ + "name": "cookie", + "description": "cookie parsing and serialization", + "version": "0.1.5", + "author": { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "cookie", + "cookies" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/cookie.git" + }, + "devDependencies": { + "istanbul": "0.3.20", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --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": "0dfc4876575cef2609cdc1082fccf832743822c2", + "bugs": { + "url": "https://github.com/jshttp/cookie/issues" + }, + "homepage": "https://github.com/jshttp/cookie", + "_id": "cookie@0.1.5", + "_shasum": "6ab9948a4b1ae21952cd2588530a4722d4044d7c", + "_from": "cookie@0.1.5", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "6ab9948a4b1ae21952cd2588530a4722d4044d7c", + "tarball": "http://registry.npmjs.org/cookie/-/cookie-0.1.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/debug/.jshintrc b/2-2/node_modules/express/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/2-2/node_modules/express/node_modules/debug/.npmignore b/2-2/node_modules/express/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/2-2/node_modules/express/node_modules/debug/History.md b/2-2/node_modules/express/node_modules/debug/History.md new file mode 100644 index 0000000..854c971 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/History.md @@ -0,0 +1,195 @@ + +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 +================== + + * 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/2-2/node_modules/express/node_modules/debug/Makefile b/2-2/node_modules/express/node_modules/debug/Makefile new file mode 100644 index 0000000..5cf4a59 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/Makefile @@ -0,0 +1,36 @@ + +# 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 dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +distclean: clean + @rm -rf node_modules + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean distclean diff --git a/2-2/node_modules/express/node_modules/debug/Readme.md b/2-2/node_modules/express/node_modules/debug/Readme.md new file mode 100644 index 0000000..b4f45e3 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/Readme.md @@ -0,0 +1,188 @@ +# 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'); +``` + +### 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 + - 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/2-2/node_modules/express/node_modules/debug/bower.json b/2-2/node_modules/express/node_modules/debug/bower.json new file mode 100644 index 0000000..6af573f --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/bower.json @@ -0,0 +1,28 @@ +{ + "name": "visionmedia-debug", + "main": "dist/debug.js", + "version": "2.2.0", + "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/2-2/node_modules/express/node_modules/debug/browser.js b/2-2/node_modules/express/node_modules/debug/browser.js new file mode 100644 index 0000000..7c76452 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/browser.js @@ -0,0 +1,168 @@ + +/** + * 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; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : 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) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.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/2-2/node_modules/express/node_modules/debug/component.json b/2-2/node_modules/express/node_modules/debug/component.json new file mode 100644 index 0000000..ca10637 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.2.0", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/2-2/node_modules/express/node_modules/debug/debug.js b/2-2/node_modules/express/node_modules/debug/debug.js new file mode 100644 index 0000000..7571a86 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * 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/2-2/node_modules/express/node_modules/debug/node.js b/2-2/node_modules/express/node_modules/debug/node.js new file mode 100644 index 0000000..1d392a8 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/node.js @@ -0,0 +1,209 @@ + +/** + * 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/2-2/node_modules/express/node_modules/debug/node_modules/ms/.npmignore b/2-2/node_modules/express/node_modules/debug/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/2-2/node_modules/express/node_modules/debug/node_modules/ms/History.md b/2-2/node_modules/express/node_modules/debug/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/debug/node_modules/ms/LICENSE b/2-2/node_modules/express/node_modules/debug/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/2-2/node_modules/express/node_modules/debug/node_modules/ms/README.md b/2-2/node_modules/express/node_modules/debug/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/2-2/node_modules/express/node_modules/debug/node_modules/ms/index.js b/2-2/node_modules/express/node_modules/debug/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/2-2/node_modules/express/node_modules/debug/node_modules/ms/package.json b/2-2/node_modules/express/node_modules/debug/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/debug/package.json b/2-2/node_modules/express/node_modules/debug/package.json new file mode 100644 index 0000000..24bb9c9 --- /dev/null +++ b/2-2/node_modules/express/node_modules/debug/package.json @@ -0,0 +1,73 @@ +{ + "name": "debug", + "version": "2.2.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "license": "MIT", + "dependencies": { + "ms": "0.7.1" + }, + "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": "b38458422b5aa8aa6d286b10dfe427e8a67e2b35", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@2.2.0", + "scripts": {}, + "_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "_from": "debug@>=2.2.0 <2.3.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "tarball": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/depd/History.md b/2-2/node_modules/express/node_modules/depd/History.md new file mode 100644 index 0000000..ace1171 --- /dev/null +++ b/2-2/node_modules/express/node_modules/depd/History.md @@ -0,0 +1,84 @@ +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/2-2/node_modules/express/node_modules/depd/LICENSE b/2-2/node_modules/express/node_modules/depd/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/2-2/node_modules/express/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/2-2/node_modules/express/node_modules/depd/Readme.md b/2-2/node_modules/express/node_modules/depd/Readme.md new file mode 100644 index 0000000..09bb979 --- /dev/null +++ b/2-2/node_modules/express/node_modules/depd/Readme.md @@ -0,0 +1,281 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction() { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: http://nodejs.org/download/ +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/2-2/node_modules/express/node_modules/depd/index.js b/2-2/node_modules/express/node_modules/depd/index.js new file mode 100644 index 0000000..fddcae8 --- /dev/null +++ b/2-2/node_modules/express/node_modules/depd/index.js @@ -0,0 +1,521 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace(str, namespace) { + var val = str.split(/[ ,]+/) + + namespace = String(namespace).toLowerCase() + + for (var i = 0 ; i < val.length; i++) { + if (!(str = val[i])) continue; + + // namespace contained + if (str === '*' || str.toLowerCase() === namespace) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor(obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter() { return value } + + if (descriptor.writable) { + descriptor.set = function setter(val) { return value = val } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString(arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString(stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate(message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log(message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + callSite = callSiteLocation(stack[1]) + callSite.name = site.name + file = callSite[0] + } else { + // get call site + i = 2 + site = callSiteLocation(stack[i]) + callSite = site + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? site.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + if (!message) { + message = callSite === site || !callSite.name + ? defaultMessage(site) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, message, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var msg = format.call(this, message, caller, stack.slice(i)) + process.stderr.write(msg + '\n', 'utf8') + + return +} + +/** + * Get call site location as array. + */ + +function callSiteLocation(callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage(site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain(msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor(msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' // bold cyan + + ' \x1b[33;1mdeprecated\x1b[22;39m' // bold yellow + + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation(callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace(obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter() { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter() { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError(namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return stackString = createStackString.call(this, stack) + }, + set: function setter(val) { + stackString = val + } + }) + + return error +} diff --git a/2-2/node_modules/express/node_modules/depd/lib/browser/index.js b/2-2/node_modules/express/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..f464e05 --- /dev/null +++ b/2-2/node_modules/express/node_modules/depd/lib/browser/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate(message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + return +} diff --git a/2-2/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js b/2-2/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js new file mode 100644 index 0000000..4b73381 --- /dev/null +++ b/2-2/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js @@ -0,0 +1,35 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = bufferConcat + +/** + * Concatenate an array of Buffers. + */ + +function bufferConcat(bufs) { + var length = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + length += bufs[i].length + } + + var buf = new Buffer(length) + var pos = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + bufs[i].copy(buf, pos) + pos += bufs[i].length + } + + return buf +} diff --git a/2-2/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js b/2-2/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 0000000..9ecef34 --- /dev/null +++ b/2-2/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation(callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString(callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName(obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/2-2/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js b/2-2/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 0000000..a05fceb --- /dev/null +++ b/2-2/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount(emitter, type) { + return emitter.listeners(type).length +} diff --git a/2-2/node_modules/express/node_modules/depd/lib/compat/index.js b/2-2/node_modules/express/node_modules/depd/lib/compat/index.js new file mode 100644 index 0000000..aa3c1de --- /dev/null +++ b/2-2/node_modules/express/node_modules/depd/lib/compat/index.js @@ -0,0 +1,84 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('buffer') +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'bufferConcat', function bufferConcat() { + return Buffer.concat || require('./buffer-concat') +}) + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace(obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount() { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty(obj, prop, getter) { + function get() { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString(obj) { + return obj.toString() +} diff --git a/2-2/node_modules/express/node_modules/depd/package.json b/2-2/node_modules/express/node_modules/depd/package.json new file mode 100644 index 0000000..9da460a --- /dev/null +++ b/2-2/node_modules/express/node_modules/depd/package.json @@ -0,0 +1,67 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "1.1.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/dougwilson/nodejs-depd.git" + }, + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail test/", + "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": "78c659de20283e3a6bee92bda455e6daff01686a", + "bugs": { + "url": "https://github.com/dougwilson/nodejs-depd/issues" + }, + "homepage": "https://github.com/dougwilson/nodejs-depd", + "_id": "depd@1.1.0", + "_shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "_from": "depd@>=1.1.0 <1.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "tarball": "http://registry.npmjs.org/depd/-/depd-1.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/depd/-/depd-1.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/escape-html/LICENSE b/2-2/node_modules/express/node_modules/escape-html/LICENSE new file mode 100644 index 0000000..2e70de9 --- /dev/null +++ b/2-2/node_modules/express/node_modules/escape-html/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2013 TJ Holowaychuk +Copyright (c) 2015 Andreas Lubbe +Copyright (c) 2015 Tiancheng "Timothy" Gu + +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/2-2/node_modules/express/node_modules/escape-html/Readme.md b/2-2/node_modules/express/node_modules/escape-html/Readme.md new file mode 100644 index 0000000..653d9ea --- /dev/null +++ b/2-2/node_modules/express/node_modules/escape-html/Readme.md @@ -0,0 +1,43 @@ + +# escape-html + + Escape string for use in HTML + +## Example + +```js +var escape = require('escape-html'); +var html = escape('foo & bar'); +// -> foo & bar +``` + +## Benchmark + +``` +$ npm run-script bench + +> escape-html@1.0.3 bench nodejs-escape-html +> 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 + + 1 test completed. + 2 tests completed. + 3 tests completed. + + no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) + single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) + many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) +``` + +## License + + MIT \ No newline at end of file diff --git a/2-2/node_modules/express/node_modules/escape-html/index.js b/2-2/node_modules/express/node_modules/escape-html/index.js new file mode 100644 index 0000000..bf9e226 --- /dev/null +++ b/2-2/node_modules/express/node_modules/escape-html/index.js @@ -0,0 +1,78 @@ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} diff --git a/2-2/node_modules/express/node_modules/escape-html/package.json b/2-2/node_modules/express/node_modules/escape-html/package.json new file mode 100644 index 0000000..eb73427 --- /dev/null +++ b/2-2/node_modules/express/node_modules/escape-html/package.json @@ -0,0 +1,57 @@ +{ + "name": "escape-html", + "description": "Escape string for use in HTML", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "escape", + "html", + "utility" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/component/escape-html.git" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4" + }, + "files": [ + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "bench": "node benchmark/index.js" + }, + "gitHead": "7ac2ea3977fcac3d4c5be8d2a037812820c65f28", + "bugs": { + "url": "https://github.com/component/escape-html/issues" + }, + "homepage": "https://github.com/component/escape-html", + "_id": "escape-html@1.0.3", + "_shasum": "0258eae4d3d0c0974de1c169188ef0051d1d1988", + "_from": "escape-html@>=1.0.3 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "0258eae4d3d0c0974de1c169188ef0051d1d1988", + "tarball": "http://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/etag/HISTORY.md b/2-2/node_modules/express/node_modules/etag/HISTORY.md new file mode 100644 index 0000000..bd0f26d --- /dev/null +++ b/2-2/node_modules/express/node_modules/etag/HISTORY.md @@ -0,0 +1,71 @@ +1.7.0 / 2015-06-08 +================== + + * Always include entity length in ETags for hash length extensions + * Generate non-Stats ETags using MD5 only (no longer CRC32) + * Improve stat performance by removing hashing + * Remove base64 padding in ETags to shorten + * Use MD5 instead of MD4 in weak ETags over 1KB + +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 +================== + + * deps: crc@3.2.1 + - Minor fixes + +1.5.0 / 2014-10-14 +================== + + * Improve string performance + * Slightly improve speed for weak ETags over 1KB + +1.4.0 / 2014-09-21 +================== + + * Support "fake" stats objects + * Support Node.js 0.6 + +1.3.1 / 2014-09-14 +================== + + * Use the (new and improved) `crc` for crc32 + +1.3.0 / 2014-08-29 +================== + + * Default strings to strong ETags + * Improve speed for weak ETags over 1KB + +1.2.1 / 2014-08-29 +================== + + * Use the (much faster) `buffer-crc32` for crc32 + +1.2.0 / 2014-08-24 +================== + + * Add support for file stat objects + +1.1.0 / 2014-08-24 +================== + + * Add fast-path for empty entity + * Add weak ETag generation + * Shrink size of generated ETags + +1.0.1 / 2014-08-24 +================== + + * Fix behavior of string containing Unicode + +1.0.0 / 2014-05-18 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/etag/LICENSE b/2-2/node_modules/express/node_modules/etag/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/2-2/node_modules/express/node_modules/etag/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/2-2/node_modules/express/node_modules/etag/README.md b/2-2/node_modules/express/node_modules/etag/README.md new file mode 100644 index 0000000..8da9e05 --- /dev/null +++ b/2-2/node_modules/express/node_modules/etag/README.md @@ -0,0 +1,165 @@ +# etag + +[![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] + +Create simple ETags + +## Installation + +```sh +$ npm install etag +``` + +## API + +```js +var etag = require('etag') +``` + +### etag(entity, [options]) + +Generate a strong ETag for the given entity. This should be the complete +body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By +default, a strong ETag is generated except for `fs.Stats`, which will +generate a weak ETag (this can be overwritten by `options.weak`). + +```js +res.setHeader('ETag', etag(body)) +``` + +#### Options + +`etag` accepts these properties in the options object. + +##### weak + +Specifies if the generated ETag will include the weak validator mark (that +is, the leading `W/`). The actual entity tag is the same. The default value +is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +```bash +$ npm run-script bench + +> 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 + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 289,198 ops/sec ±1.09% (190 runs sampled) +* buffer - weak x 287,838 ops/sec ±0.91% (189 runs sampled) +* string - strong x 284,586 ops/sec ±1.05% (192 runs sampled) +* string - weak x 287,439 ops/sec ±0.82% (192 runs sampled) + +> node benchmark/body1-1kb.js + + 1KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 212,423 ops/sec ±0.75% (193 runs sampled) +* buffer - weak x 211,871 ops/sec ±0.74% (194 runs sampled) + string - strong x 205,291 ops/sec ±0.86% (194 runs sampled) + string - weak x 208,463 ops/sec ±0.79% (192 runs sampled) + +> node benchmark/body2-5kb.js + + 5KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 92,901 ops/sec ±0.58% (195 runs sampled) +* buffer - weak x 93,045 ops/sec ±0.65% (192 runs sampled) + string - strong x 89,621 ops/sec ±0.68% (194 runs sampled) + string - weak x 90,070 ops/sec ±0.70% (196 runs sampled) + +> node benchmark/body3-10kb.js + + 10KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 54,220 ops/sec ±0.85% (192 runs sampled) +* buffer - weak x 54,069 ops/sec ±0.83% (191 runs sampled) + string - strong x 53,078 ops/sec ±0.53% (194 runs sampled) + string - weak x 53,849 ops/sec ±0.47% (197 runs sampled) + +> node benchmark/body4-100kb.js + + 100KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 6,673 ops/sec ±0.15% (197 runs sampled) +* buffer - weak x 6,716 ops/sec ±0.12% (198 runs sampled) + string - strong x 6,357 ops/sec ±0.14% (197 runs sampled) + string - weak x 6,344 ops/sec ±0.21% (197 runs sampled) + +> node benchmark/stats.js + + stats + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* real - strong x 1,671,989 ops/sec ±0.13% (197 runs sampled) +* real - weak x 1,681,297 ops/sec ±0.12% (198 runs sampled) + fake - strong x 927,063 ops/sec ±0.14% (198 runs sampled) + fake - weak x 914,461 ops/sec ±0.41% (191 runs sampled) +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master +[downloads-image]: https://img.shields.io/npm/dm/etag.svg +[downloads-url]: https://npmjs.org/package/etag diff --git a/2-2/node_modules/express/node_modules/etag/index.js b/2-2/node_modules/express/node_modules/etag/index.js new file mode 100644 index 0000000..b582c84 --- /dev/null +++ b/2-2/node_modules/express/node_modules/etag/index.js @@ -0,0 +1,132 @@ +/*! + * etag + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = etag + +/** + * Module dependencies. + * @private + */ + +var crypto = require('crypto') +var Stats = require('fs').Stats + +/** + * Module variables. + * @private + */ + +var base64PadCharRegExp = /=+$/ +var toString = Object.prototype.toString + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag(entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-1B2M2Y8AsgTpgAmY7PhCfg"' + } + + // compute hash of entity + var hash = crypto + .createHash('md5') + .update(entity, 'utf8') + .digest('base64') + .replace(base64PadCharRegExp, '') + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag(entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats(obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + 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' + && 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag(stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} diff --git a/2-2/node_modules/express/node_modules/etag/package.json b/2-2/node_modules/express/node_modules/etag/package.json new file mode 100644 index 0000000..8dc110c --- /dev/null +++ b/2-2/node_modules/express/node_modules/etag/package.json @@ -0,0 +1,73 @@ +{ + "name": "etag", + "description": "Create simple ETags", + "version": "1.7.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "David Björklund", + "email": "david.bjorklund@gmail.com" + } + ], + "license": "MIT", + "keywords": [ + "etag", + "http", + "res" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/etag.git" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.3.14", + "mocha": "~1.21.4", + "seedrandom": "2.3.11" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "a511f5c8c930fd9546dbd88acb080f96bc788cfc", + "bugs": { + "url": "https://github.com/jshttp/etag/issues" + }, + "homepage": "https://github.com/jshttp/etag", + "_id": "etag@1.7.0", + "_shasum": "03d30b5f67dd6e632d2945d30d6652731a34d5d8", + "_from": "etag@>=1.7.0 <1.8.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "03d30b5f67dd6e632d2945d30d6652731a34d5d8", + "tarball": "http://registry.npmjs.org/etag/-/etag-1.7.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/etag/-/etag-1.7.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/finalhandler/HISTORY.md b/2-2/node_modules/express/node_modules/finalhandler/HISTORY.md new file mode 100644 index 0000000..78dddc0 --- /dev/null +++ b/2-2/node_modules/express/node_modules/finalhandler/HISTORY.md @@ -0,0 +1,98 @@ +0.4.1 / 2015-12-02 +================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + +0.4.0 / 2015-06-14 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + * Support `statusCode` property on `Error` objects + * Use `unpipe` module for unpiping requests + * deps: escape-html@1.0.2 + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.3.1 / 2014-10-16 +================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + +0.3.0 / 2014-09-17 +================== + + * Terminate in progress response only on error + * Use `on-finished` to determine request status + +0.2.0 / 2014-09-03 +================== + + * Set `X-Content-Type-Options: nosniff` header + * deps: debug@~2.0.0 + +0.1.0 / 2014-07-16 +================== + + * Respond after request fully read + - prevents hung responses and socket hang ups + * deps: debug@1.0.4 + +0.0.3 / 2014-07-11 +================== + + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.0.2 / 2014-06-19 +================== + + * Handle invalid status codes + +0.0.1 / 2014-06-05 +================== + + * deps: debug@1.0.2 + +0.0.0 / 2014-06-05 +================== + + * Extracted from connect/express diff --git a/2-2/node_modules/express/node_modules/finalhandler/LICENSE b/2-2/node_modules/express/node_modules/finalhandler/LICENSE new file mode 100644 index 0000000..b60a5ad --- /dev/null +++ b/2-2/node_modules/express/node_modules/finalhandler/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/2-2/node_modules/express/node_modules/finalhandler/README.md b/2-2/node_modules/express/node_modules/finalhandler/README.md new file mode 100644 index 0000000..6b171d4 --- /dev/null +++ b/2-2/node_modules/express/node_modules/finalhandler/README.md @@ -0,0 +1,133 @@ +# finalhandler + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js function to invoke as the final step to respond to HTTP request. + +## Installation + +```sh +$ npm install finalhandler +``` + +## API + +```js +var finalhandler = require('finalhandler') +``` + +### finalhandler(req, res, [options]) + +Returns function to be invoked as the final step for the given `req` and `res`. +This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will +write out a 404 response to the `res`. If it is truthy, an error response will +be written out to the `res`, and `res.statusCode` is set from `err.status`. + +The final handler will also unpipe anything from `req` when it is invoked. + +#### options.env + +By default, the environment is determined by `NODE_ENV` variable, but it can be +overridden by this option. + +#### options.onerror + +Provide a function to be called with the `err` when it exists. Can be used for +writing errors to a central location without excessive function generation. Called +as `onerror(err, req, res)`. + +## Examples + +### always 404 + +```js +var finalhandler = require('finalhandler') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + done() +}) + +server.listen(3000) +``` + +### perform simple action + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) +``` + +### use with middleware-style functions + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +var serve = serveStatic('public') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + serve(req, res, done) +}) + +server.listen(3000) +``` + +### keep log of all errors + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res, {onerror: logerror}) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) + +function logerror(err) { + console.error(err.stack || err.toString()) +} +``` + +## License + +[MIT](LICENSE) + +[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 +[node-url]: http://nodejs.org/download/ +[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 +[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg +[downloads-url]: https://npmjs.org/package/finalhandler diff --git a/2-2/node_modules/express/node_modules/finalhandler/index.js b/2-2/node_modules/express/node_modules/finalhandler/index.js new file mode 100644 index 0000000..0de7c6b --- /dev/null +++ b/2-2/node_modules/express/node_modules/finalhandler/index.js @@ -0,0 +1,151 @@ +/*! + * finalhandler + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('finalhandler') +var escapeHtml = require('escape-html') +var http = require('http') +var onFinished = require('on-finished') +var unpipe = require('unpipe') + +/** + * Module variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished + +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler(req, res, options) { + var opts = options || {} + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + + return function (err) { + var status = res.statusCode + + // ignore 404 on in-flight response + if (!err && res._header) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect err.statusCode + if (err.statusCode) { + status = err.statusCode + } + + // respect err.status + if (err.status) { + status = err.status + } + + // default status code to 500 + if (!status || status < 400) { + status = 500 + } + + // production gets a basic error message + var msg = env === 'production' + ? http.STATUS_CODES[status] + : err.stack || err.toString() + msg = escapeHtml(msg) + .replace(/\n/g, '
') + .replace(/ /g, '  ') + '\n' + } else { + status = 404 + msg = 'Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl || req.url) + '\n' + } + + debug('default %s', status) + + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } + + // cannot actually respond + if (res._header) { + return req.socket.destroy() + } + + send(req, res, status, msg) + } +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {string} body + * @private + */ + +function send(req, res, status, body) { + function write() { + res.statusCode = status + + // security header for content sniffing + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() +} diff --git a/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md b/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md new file mode 100644 index 0000000..85e0f8d --- /dev/null +++ b/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE b/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE new file mode 100644 index 0000000..aed0138 --- /dev/null +++ b/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md b/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md new file mode 100644 index 0000000..e536ad2 --- /dev/null +++ b/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js b/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js new file mode 100644 index 0000000..15c3d97 --- /dev/null +++ b/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json b/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json new file mode 100644 index 0000000..4af1b49 --- /dev/null +++ b/2-2/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json @@ -0,0 +1,59 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/unpipe.git" + }, + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "d2df901c06487430e78dca62b6edb8bb2fc5e99d", + "bugs": { + "url": "https://github.com/stream-utils/unpipe/issues" + }, + "homepage": "https://github.com/stream-utils/unpipe", + "_id": "unpipe@1.0.0", + "_shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "_from": "unpipe@>=1.0.0 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "tarball": "http://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/finalhandler/package.json b/2-2/node_modules/express/node_modules/finalhandler/package.json new file mode 100644 index 0000000..0afe7fc --- /dev/null +++ b/2-2/node_modules/express/node_modules/finalhandler/package.json @@ -0,0 +1,81 @@ +{ + "name": "finalhandler", + "description": "Node.js final http responder", + "version": "0.4.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/finalhandler.git" + }, + "dependencies": { + "debug": "~2.2.0", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "unpipe": "~1.0.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "2.3.4", + "readable-stream": "2.0.4", + "supertest": "1.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "ac2036774059eb93dbac8475580e52433204d4d4", + "bugs": { + "url": "https://github.com/pillarjs/finalhandler/issues" + }, + "homepage": "https://github.com/pillarjs/finalhandler", + "_id": "finalhandler@0.4.1", + "_shasum": "85a17c6c59a94717d262d61230d4b0ebe3d4a14d", + "_from": "finalhandler@0.4.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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "85a17c6c59a94717d262d61230d4b0ebe3d4a14d", + "tarball": "http://registry.npmjs.org/finalhandler/-/finalhandler-0.4.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-0.4.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/fresh/HISTORY.md b/2-2/node_modules/express/node_modules/fresh/HISTORY.md new file mode 100644 index 0000000..3c95fbb --- /dev/null +++ b/2-2/node_modules/express/node_modules/fresh/HISTORY.md @@ -0,0 +1,38 @@ +0.3.0 / 2015-05-12 +================== + + * Add weak `ETag` matching support + +0.2.4 / 2014-09-07 +================== + + * Support Node.js 0.6 + +0.2.3 / 2014-09-07 +================== + + * Move repository to jshttp + +0.2.2 / 2014-02-19 +================== + + * Revert "Fix for blank page on Safari reload" + +0.2.1 / 2014-01-29 +================== + + * Fix for blank page on Safari reload + +0.2.0 / 2013-08-11 +================== + + * Return stale for `Cache-Control: no-cache` + +0.1.0 / 2012-06-15 +================== + * Add `If-None-Match: *` support + +0.0.1 / 2012-06-10 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/fresh/LICENSE b/2-2/node_modules/express/node_modules/fresh/LICENSE new file mode 100644 index 0000000..f527394 --- /dev/null +++ b/2-2/node_modules/express/node_modules/fresh/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/fresh/README.md b/2-2/node_modules/express/node_modules/fresh/README.md new file mode 100644 index 0000000..0813e30 --- /dev/null +++ b/2-2/node_modules/express/node_modules/fresh/README.md @@ -0,0 +1,58 @@ +# fresh + +[![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] + +HTTP response freshness testing + +## Installation + +``` +$ npm install fresh +``` + +## API + +```js +var fresh = require('fresh') +``` + +### fresh(req, res) + + Check freshness of `req` and `res` headers. + + When the cache is "fresh" __true__ is returned, + otherwise __false__ is returned to indicate that + the cache is now stale. + +## Example + +```js +var req = { 'if-none-match': 'tobi' }; +var res = { 'etag': 'luna' }; +fresh(req, res); +// => false + +var req = { 'if-none-match': 'tobi' }; +var res = { 'etag': 'tobi' }; +fresh(req, res); +// => true +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/fresh.svg +[npm-url]: https://npmjs.org/package/fresh +[node-version-image]: https://img.shields.io/node/v/fresh.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg +[travis-url]: https://travis-ci.org/jshttp/fresh +[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master +[downloads-image]: https://img.shields.io/npm/dm/fresh.svg +[downloads-url]: https://npmjs.org/package/fresh diff --git a/2-2/node_modules/express/node_modules/fresh/index.js b/2-2/node_modules/express/node_modules/fresh/index.js new file mode 100644 index 0000000..a900873 --- /dev/null +++ b/2-2/node_modules/express/node_modules/fresh/index.js @@ -0,0 +1,57 @@ + +/** + * Expose `fresh()`. + */ + +module.exports = fresh; + +/** + * Check freshness of `req` and `res` headers. + * + * When the cache is "fresh" __true__ is returned, + * otherwise __false__ is returned to indicate that + * the cache is now stale. + * + * @param {Object} req + * @param {Object} res + * @return {Boolean} + * @api public + */ + +function fresh(req, res) { + // defaults + var etagMatches = true; + var notModified = true; + + // fields + var modifiedSince = req['if-modified-since']; + var noneMatch = req['if-none-match']; + var lastModified = res['last-modified']; + var etag = res['etag']; + var cc = req['cache-control']; + + // unconditional request + if (!modifiedSince && !noneMatch) return false; + + // check for no-cache cache request directive + if (cc && cc.indexOf('no-cache') !== -1) return false; + + // parse if-none-match + if (noneMatch) noneMatch = noneMatch.split(/ *, */); + + // if-none-match + if (noneMatch) { + etagMatches = noneMatch.some(function (match) { + return match === '*' || match === etag || match === 'W/' + etag; + }); + } + + // if-modified-since + if (modifiedSince) { + modifiedSince = new Date(modifiedSince); + lastModified = new Date(lastModified); + notModified = lastModified <= modifiedSince; + } + + return !! (etagMatches && notModified); +} diff --git a/2-2/node_modules/express/node_modules/fresh/package.json b/2-2/node_modules/express/node_modules/fresh/package.json new file mode 100644 index 0000000..74332c4 --- /dev/null +++ b/2-2/node_modules/express/node_modules/fresh/package.json @@ -0,0 +1,87 @@ +{ + "name": "fresh", + "description": "HTTP response freshness testing", + "version": "0.3.0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "fresh", + "http", + "conditional", + "cache" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/fresh.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "14616c9748368ca08cd6a955dd88ab659b778634", + "bugs": { + "url": "https://github.com/jshttp/fresh/issues" + }, + "homepage": "https://github.com/jshttp/fresh", + "_id": "fresh@0.3.0", + "_shasum": "651f838e22424e7566de161d8358caa199f83d4f", + "_from": "fresh@0.3.0", + "_npmVersion": "1.4.28", + "_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": "651f838e22424e7566de161d8358caa199f83d4f", + "tarball": "http://registry.npmjs.org/fresh/-/fresh-0.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/merge-descriptors/HISTORY.md b/2-2/node_modules/express/node_modules/merge-descriptors/HISTORY.md new file mode 100644 index 0000000..486771f --- /dev/null +++ b/2-2/node_modules/express/node_modules/merge-descriptors/HISTORY.md @@ -0,0 +1,21 @@ +1.0.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.0.0 / 2015-03-01 +================== + + * Add option to only add new descriptors + * Add simple argument validation + * Add jsdoc to source file + +0.0.2 / 2013-12-14 +================== + + * Move repository to `component` organization + +0.0.1 / 2013-10-29 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/merge-descriptors/LICENSE b/2-2/node_modules/express/node_modules/merge-descriptors/LICENSE new file mode 100644 index 0000000..274bfd8 --- /dev/null +++ b/2-2/node_modules/express/node_modules/merge-descriptors/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 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 +'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/2-2/node_modules/express/node_modules/merge-descriptors/README.md b/2-2/node_modules/express/node_modules/merge-descriptors/README.md new file mode 100644 index 0000000..d593c0e --- /dev/null +++ b/2-2/node_modules/express/node_modules/merge-descriptors/README.md @@ -0,0 +1,48 @@ +# Merge Descriptors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Merge objects using descriptors. + +```js +var thing = { + get name() { + return 'jon' + } +} + +var animal = { + +} + +merge(animal, thing) + +animal.name === 'jon' +``` + +## API + +### merge(destination, source) + +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 + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/merge-descriptors.svg +[npm-url]: https://npmjs.org/package/merge-descriptors +[travis-image]: https://img.shields.io/travis/component/merge-descriptors/master.svg +[travis-url]: https://travis-ci.org/component/merge-descriptors +[coveralls-image]: https://img.shields.io/coveralls/component/merge-descriptors/master.svg +[coveralls-url]: https://coveralls.io/r/component/merge-descriptors?branch=master +[downloads-image]: https://img.shields.io/npm/dm/merge-descriptors.svg +[downloads-url]: https://npmjs.org/package/merge-descriptors diff --git a/2-2/node_modules/express/node_modules/merge-descriptors/index.js b/2-2/node_modules/express/node_modules/merge-descriptors/index.js new file mode 100644 index 0000000..573b132 --- /dev/null +++ b/2-2/node_modules/express/node_modules/merge-descriptors/index.js @@ -0,0 +1,60 @@ +/*! + * merge-descriptors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * 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 +} diff --git a/2-2/node_modules/express/node_modules/merge-descriptors/package.json b/2-2/node_modules/express/node_modules/merge-descriptors/package.json new file mode 100644 index 0000000..a65d2e8 --- /dev/null +++ b/2-2/node_modules/express/node_modules/merge-descriptors/package.json @@ -0,0 +1,138 @@ +{ + "name": "merge-descriptors", + "description": "Merge objects using descriptors", + "version": "1.0.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Mike Grabowski", + "email": "grabbou@gmail.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/component/merge-descriptors.git" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --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": "f26c49c3b423b0b2ac31f6e32a84e1632f2d7ac2", + "bugs": { + "url": "https://github.com/component/merge-descriptors/issues" + }, + "homepage": "https://github.com/component/merge-descriptors", + "_id": "merge-descriptors@1.0.1", + "_shasum": "b00aaa556dd8b44568150ec9d1b953f3f90cbb61", + "_from": "merge-descriptors@1.0.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "anthonyshort", + "email": "antshort@gmail.com" + }, + { + "name": "clintwood", + "email": "clint@anotherway.co.za" + }, + { + "name": "dfcreative", + "email": "df.creative@gmail.com" + }, + { + "name": "dominicbarnes", + "email": "dominic@dbarnes.info" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "ianstormtaylor", + "email": "ian@ianstormtaylor.com" + }, + { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + { + "name": "mattmueller", + "email": "mattmuelle@gmail.com" + }, + { + "name": "queckezz", + "email": "fabian.eichenberger@gmail.com" + }, + { + "name": "stephenmathieson", + "email": "me@stephenmathieson.com" + }, + { + "name": "thehydroimpulse", + "email": "dnfagnan@gmail.com" + }, + { + "name": "timaschew", + "email": "timaschew@gmail.com" + }, + { + "name": "timoxley", + "email": "secoif@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + { + "name": "trevorgerhardt", + "email": "trevorgerhardt@gmail.com" + }, + { + "name": "yields", + "email": "yields@icloud.com" + } + ], + "dist": { + "shasum": "b00aaa556dd8b44568150ec9d1b953f3f90cbb61", + "tarball": "http://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/methods/HISTORY.md b/2-2/node_modules/express/node_modules/methods/HISTORY.md new file mode 100644 index 0000000..c0ecf07 --- /dev/null +++ b/2-2/node_modules/express/node_modules/methods/HISTORY.md @@ -0,0 +1,29 @@ +1.1.2 / 2016-01-17 +================== + + * perf: enable strict mode + +1.1.1 / 2014-12-30 +================== + + * Improve `browserify` support + +1.1.0 / 2014-07-05 +================== + + * Add `CONNECT` method + +1.0.1 / 2014-06-02 +================== + + * Fix module to work with harmony transform + +1.0.0 / 2014-05-08 +================== + + * Add `PURGE` method + +0.1.0 / 2013-10-28 +================== + + * Add `http.METHODS` support diff --git a/2-2/node_modules/express/node_modules/methods/LICENSE b/2-2/node_modules/express/node_modules/methods/LICENSE new file mode 100644 index 0000000..220dc1a --- /dev/null +++ b/2-2/node_modules/express/node_modules/methods/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013-2014 TJ Holowaychuk +Copyright (c) 2015-2016 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/2-2/node_modules/express/node_modules/methods/README.md b/2-2/node_modules/express/node_modules/methods/README.md new file mode 100644 index 0000000..672a32b --- /dev/null +++ b/2-2/node_modules/express/node_modules/methods/README.md @@ -0,0 +1,51 @@ +# Methods + +[![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] + +HTTP verbs that Node.js core's HTTP parser supports. + +This module provides an export that is just like `http.METHODS` from Node.js core, +with the following differences: + + * All method names are lower-cased. + * Contains a fallback list of methods for Node.js versions that do not have a + `http.METHODS` export (0.10 and lower). + * Provides the fallback list when using tools like `browserify` without pulling + in the `http` shim module. + +## Install + +```bash +$ npm install methods +``` + +## API + +```js +var methods = require('methods') +``` + +### methods + +This is an array of lower-cased method names that Node.js supports. If Node.js +provides the `http.METHODS` export, then this is the same array lower-cased, +otherwise it is a snapshot of the verbs from Node.js 0.10. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat +[npm-url]: https://npmjs.org/package/methods +[node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/methods +[coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master +[downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat +[downloads-url]: https://npmjs.org/package/methods diff --git a/2-2/node_modules/express/node_modules/methods/index.js b/2-2/node_modules/express/node_modules/methods/index.js new file mode 100644 index 0000000..667a50b --- /dev/null +++ b/2-2/node_modules/express/node_modules/methods/index.js @@ -0,0 +1,69 @@ +/*! + * methods + * Copyright(c) 2013-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var http = require('http'); + +/** + * Module exports. + * @public + */ + +module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); + +/** + * Get the current Node.js methods. + * @private + */ + +function getCurrentNodeMethods() { + return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { + return method.toLowerCase(); + }); +} + +/** + * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * @private + */ + +function getBasicNodeMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect' + ]; +} diff --git a/2-2/node_modules/express/node_modules/methods/package.json b/2-2/node_modules/express/node_modules/methods/package.json new file mode 100644 index 0000000..fd072fc --- /dev/null +++ b/2-2/node_modules/express/node_modules/methods/package.json @@ -0,0 +1,88 @@ +{ + "name": "methods", + "description": "HTTP methods that node supports", + "version": "1.1.2", + "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+https://github.com/jshttp/methods.git" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE" + ], + "engines": { + "node": ">= 0.6" + }, + "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/" + }, + "browser": { + "http": false + }, + "keywords": [ + "http", + "methods" + ], + "gitHead": "25d257d913f1b94bd2d73581521ff72c81469140", + "bugs": { + "url": "https://github.com/jshttp/methods/issues" + }, + "homepage": "https://github.com/jshttp/methods", + "_id": "methods@1.1.2", + "_shasum": "5529a4d67654134edcc5266656835b0f851afcee", + "_from": "methods@>=1.1.2 <1.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "5529a4d67654134edcc5266656835b0f851afcee", + "tarball": "http://registry.npmjs.org/methods/-/methods-1.1.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/on-finished/HISTORY.md b/2-2/node_modules/express/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000..98ff0e9 --- /dev/null +++ b/2-2/node_modules/express/node_modules/on-finished/HISTORY.md @@ -0,0 +1,88 @@ +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +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 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/on-finished/LICENSE b/2-2/node_modules/express/node_modules/on-finished/LICENSE new file mode 100644 index 0000000..5931fd2 --- /dev/null +++ b/2-2/node_modules/express/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/on-finished/README.md b/2-2/node_modules/express/node_modules/on-finished/README.md new file mode 100644 index 0000000..a0e1157 --- /dev/null +++ b/2-2/node_modules/express/node_modules/on-finished/README.md @@ -0,0 +1,154 @@ +# on-finished + +[![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] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to 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, res) { + // clean up open fds, etc. + // err contains the error is request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to 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 = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg +[downloads-url]: https://npmjs.org/package/on-finished diff --git a/2-2/node_modules/express/node_modules/on-finished/index.js b/2-2/node_modules/express/node_modules/on-finished/index.js new file mode 100644 index 0000000..9abd98f --- /dev/null +++ b/2-2/node_modules/express/node_modules/on-finished/index.js @@ -0,0 +1,196 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener(msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish(error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket) + callback(socket) + } +} diff --git a/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE b/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md b/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js b/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json b/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json new file mode 100644 index 0000000..1d223fb --- /dev/null +++ b/2-2/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json @@ -0,0 +1,64 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jonathanong/ee-first.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "512e0ce4cc3643f603708f965a97b61b1a9c0441", + "bugs": { + "url": "https://github.com/jonathanong/ee-first/issues" + }, + "homepage": "https://github.com/jonathanong/ee-first", + "_id": "ee-first@1.1.1", + "_shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "_from": "ee-first@1.1.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/on-finished/package.json b/2-2/node_modules/express/node_modules/on-finished/package.json new file mode 100644 index 0000000..7b2ebdd --- /dev/null +++ b/2-2/node_modules/express/node_modules/on-finished/package.json @@ -0,0 +1,71 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.3.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/on-finished.git" + }, + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "34babcb58126a416fcf5205768204f2e12699dda", + "bugs": { + "url": "https://github.com/jshttp/on-finished/issues" + }, + "homepage": "https://github.com/jshttp/on-finished", + "_id": "on-finished@2.3.0", + "_shasum": "20f1336481b083cd75337992a16971aa2d906947", + "_from": "on-finished@>=2.3.0 <2.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "20f1336481b083cd75337992a16971aa2d906947", + "tarball": "http://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/parseurl/HISTORY.md b/2-2/node_modules/express/node_modules/parseurl/HISTORY.md new file mode 100644 index 0000000..395041e --- /dev/null +++ b/2-2/node_modules/express/node_modules/parseurl/HISTORY.md @@ -0,0 +1,47 @@ +1.3.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.3.0 / 2014-08-09 +================== + + * Add `parseurl.original` for parsing `req.originalUrl` with fallback + * Return `undefined` if `req.url` is `undefined` + +1.2.0 / 2014-07-21 +================== + + * Cache URLs based on original value + * Remove no-longer-needed URL mis-parse work-around + * Simplify the "fast-path" `RegExp` + +1.1.3 / 2014-07-08 +================== + + * Fix typo + +1.1.2 / 2014-07-08 +================== + + * Seriously fix Node.js 0.8 compatibility + +1.1.1 / 2014-07-08 +================== + + * Fix Node.js 0.8 compatibility + +1.1.0 / 2014-07-08 +================== + + * Incorporate URL href-only parse fast-path + +1.0.1 / 2014-03-08 +================== + + * Add missing `require` + +1.0.0 / 2014-03-08 +================== + + * Genesis from `connect` diff --git a/2-2/node_modules/express/node_modules/parseurl/LICENSE b/2-2/node_modules/express/node_modules/parseurl/LICENSE new file mode 100644 index 0000000..ec7dfe7 --- /dev/null +++ b/2-2/node_modules/express/node_modules/parseurl/LICENSE @@ -0,0 +1,24 @@ + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/parseurl/README.md b/2-2/node_modules/express/node_modules/parseurl/README.md new file mode 100644 index 0000000..f4796eb --- /dev/null +++ b/2-2/node_modules/express/node_modules/parseurl/README.md @@ -0,0 +1,120 @@ +# parseurl + +[![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] + +Parse a URL with memoization. + +## Install + +```bash +$ npm install parseurl +``` + +## API + +```js +var parseurl = require('parseurl') +``` + +### parseurl(req) + +Parse the URL of the given request object (looks at the `req.url` property) +and return the result. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.url` does +not change will return a cached parsed object, rather than parsing again. + +### parseurl.original(req) + +Parse the original URL of the given request object and return the result. +This works by trying to parse `req.originalUrl` if it is a string, otherwise +parses `req.url`. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.originalUrl` +does not change will return a cached parsed object, rather than parsing again. + +## Benchmark + +```bash +$ npm run-script bench + +> parseurl@1.3.1 bench nodejs-parseurl +> node benchmark/index.js + +> node benchmark/fullurl.js + + Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 1,290,780 ops/sec ±0.46% (195 runs sampled) + nativeurl x 56,401 ops/sec ±0.22% (196 runs sampled) + parseurl x 55,231 ops/sec ±0.22% (194 runs sampled) + +> node benchmark/pathquery.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 1,986,668 ops/sec ±0.27% (190 runs sampled) + nativeurl x 98,740 ops/sec ±0.21% (195 runs sampled) + parseurl x 2,628,171 ops/sec ±0.36% (195 runs sampled) + +> node benchmark/samerequest.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 2,184,468 ops/sec ±0.40% (194 runs sampled) + nativeurl x 99,437 ops/sec ±0.71% (194 runs sampled) + parseurl x 10,498,005 ops/sec ±0.61% (186 runs sampled) + +> node benchmark/simplepath.js + + Parsing URL "/foo/bar" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 4,535,825 ops/sec ±0.27% (191 runs sampled) + nativeurl x 98,769 ops/sec ±0.54% (191 runs sampled) + parseurl x 4,164,865 ops/sec ±0.34% (192 runs sampled) + +> node benchmark/slash.js + + Parsing URL "/" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 4,908,405 ops/sec ±0.42% (191 runs sampled) + nativeurl x 100,945 ops/sec ±0.59% (188 runs sampled) + parseurl x 4,333,208 ops/sec ±0.27% (194 runs sampled) +``` + +## License + + [MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/parseurl.svg +[npm-url]: https://npmjs.org/package/parseurl +[node-version-image]: https://img.shields.io/node/v/parseurl.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/pillarjs/parseurl/master.svg +[travis-url]: https://travis-ci.org/pillarjs/parseurl +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/parseurl/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master +[downloads-image]: https://img.shields.io/npm/dm/parseurl.svg +[downloads-url]: https://npmjs.org/package/parseurl diff --git a/2-2/node_modules/express/node_modules/parseurl/index.js b/2-2/node_modules/express/node_modules/parseurl/index.js new file mode 100644 index 0000000..56cc6ec --- /dev/null +++ b/2-2/node_modules/express/node_modules/parseurl/index.js @@ -0,0 +1,138 @@ +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var url = require('url') +var parse = url.parse +var Url = url.Url + +/** + * Pattern for a simple path case. + * See: https://github.com/joyent/node/pull/7878 + */ + +var simplePathRegExp = /^(\/\/?(?!\/)[^\?#\s]*)(\?[^#\s]*)?$/ + +/** + * Exports. + */ + +module.exports = parseurl +module.exports.original = originalurl + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @api public + */ + +function parseurl(req) { + var url = req.url + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return req._parsedUrl = parsed +}; + +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @api public + */ + +function originalurl(req) { + var url = req.originalUrl + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return req._parsedOriginalUrl = parsed +}; + +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @api private + */ + +function fastparse(str) { + // Try fast path regexp + // See: https://github.com/joyent/node/pull/7878 + var simplePath = typeof str === 'string' && simplePathRegExp.exec(str) + + // Construct simple URL + if (simplePath) { + var pathname = simplePath[1] + var search = simplePath[2] || null + var url = Url !== undefined + ? new Url() + : {} + url.path = str + url.href = str + url.pathname = pathname + url.search = search + url.query = search && search.substr(1) + + return url + } + + return parse(str) +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @api private + */ + +function fresh(url, parsedUrl) { + return typeof parsedUrl === 'object' + && parsedUrl !== null + && (Url === undefined || parsedUrl instanceof Url) + && parsedUrl._raw === url +} diff --git a/2-2/node_modules/express/node_modules/parseurl/package.json b/2-2/node_modules/express/node_modules/parseurl/package.json new file mode 100644 index 0000000..7ba6287 --- /dev/null +++ b/2-2/node_modules/express/node_modules/parseurl/package.json @@ -0,0 +1,89 @@ +{ + "name": "parseurl", + "description": "parse a url with memoization", + "version": "1.3.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/parseurl.git" + }, + "license": "MIT", + "devDependencies": { + "benchmark": "2.0.0", + "beautify-benchmark": "0.2.4", + "fast-url-parser": "1.1.3", + "istanbul": "0.4.2", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --check-leaks --bail --reporter spec test/", + "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": "6d22d376d75b927ab2b5347ce3a1d6735133dd43", + "bugs": { + "url": "https://github.com/pillarjs/parseurl/issues" + }, + "homepage": "https://github.com/pillarjs/parseurl", + "_id": "parseurl@1.3.1", + "_shasum": "c8ab8c9223ba34888aa64a297b28853bec18da56", + "_from": "parseurl@>=1.3.1 <1.4.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" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "c8ab8c9223ba34888aa64a297b28853bec18da56", + "tarball": "http://registry.npmjs.org/parseurl/-/parseurl-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/path-to-regexp/History.md b/2-2/node_modules/express/node_modules/path-to-regexp/History.md new file mode 100644 index 0000000..7f65878 --- /dev/null +++ b/2-2/node_modules/express/node_modules/path-to-regexp/History.md @@ -0,0 +1,36 @@ +0.1.7 / 2015-07-28 +================== + + * Fixed regression with escaped round brackets and matching groups. + +0.1.6 / 2015-06-19 +================== + + * Replace `index` feature by outputting all parameters, unnamed and named. + +0.1.5 / 2015-05-08 +================== + + * Add an index property for position in match result. + +0.1.4 / 2015-03-05 +================== + + * Add license information + +0.1.3 / 2014-07-06 +================== + + * Better array support + * Improved support for trailing slash in non-ending mode + +0.1.0 / 2014-03-06 +================== + + * add options.end + +0.0.2 / 2013-02-10 +================== + + * Update to match current express + * add .license property to component.json diff --git a/2-2/node_modules/express/node_modules/path-to-regexp/LICENSE b/2-2/node_modules/express/node_modules/path-to-regexp/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/2-2/node_modules/express/node_modules/path-to-regexp/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/2-2/node_modules/express/node_modules/path-to-regexp/Readme.md b/2-2/node_modules/express/node_modules/path-to-regexp/Readme.md new file mode 100644 index 0000000..95452a6 --- /dev/null +++ b/2-2/node_modules/express/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,35 @@ +# Path-to-RegExp + +Turn an Express-style path string such as `/user/:name` into a regular expression. + +**Note:** This is a legacy branch. You should upgrade to `1.x`. + +## Usage + +```javascript +var pathToRegexp = require('path-to-regexp'); +``` + +### pathToRegexp(path, keys, options) + + - **path** A string in the express format, an array of such strings, or a regular expression + - **keys** An array to be populated with the keys present in the url. Once the function completes, this will be an array of strings. + - **options** + - **options.sensitive** Defaults to false, set this to true to make routes case sensitive + - **options.strict** Defaults to false, set this to true to make the trailing slash matter. + - **options.end** Defaults to true, set this to false to only match the prefix of the URL. + +```javascript +var keys = []; +var exp = pathToRegexp('/foo/:bar', keys); +//keys = ['bar'] +//exp = /^\/foo\/(?:([^\/]+?))\/?$/i +``` + +## Live Demo + +You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/). + +## License + + MIT diff --git a/2-2/node_modules/express/node_modules/path-to-regexp/index.js b/2-2/node_modules/express/node_modules/path-to-regexp/index.js new file mode 100644 index 0000000..500d1da --- /dev/null +++ b/2-2/node_modules/express/node_modules/path-to-regexp/index.js @@ -0,0 +1,129 @@ +/** + * Expose `pathtoRegexp`. + */ + +module.exports = pathtoRegexp; + +/** + * Match matching groups in a regular expression. + */ +var MATCHING_GROUP_REGEXP = /\((?!\?)/g; + +/** + * Normalize the given path string, + * returning a regular expression. + * + * An empty array should be passed, + * which will contain the placeholder + * key names. For example "/user/:id" will + * then contain ["id"]. + * + * @param {String|RegExp|Array} path + * @param {Array} keys + * @param {Object} options + * @return {RegExp} + * @api private + */ + +function pathtoRegexp(path, keys, options) { + options = options || {}; + keys = keys || []; + var strict = options.strict; + var end = options.end !== false; + var flags = options.sensitive ? '' : 'i'; + var extraOffset = 0; + var keysOffset = keys.length; + var i = 0; + var name = 0; + var m; + + if (path instanceof RegExp) { + while (m = MATCHING_GROUP_REGEXP.exec(path.source)) { + keys.push({ + name: name++, + optional: false, + offset: m.index + }); + } + + return path; + } + + if (Array.isArray(path)) { + // Map array parts into regexps and return their source. We also pass + // the same keys and options instance into every generation to get + // consistent matching groups before we join the sources together. + path = path.map(function (value) { + return pathtoRegexp(value, keys, options).source; + }); + + return new RegExp('(?:' + path.join('|') + ')', flags); + } + + path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) + .replace(/\/\(/g, '/(?:') + .replace(/([\/\.])/g, '\\$1') + .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) { + slash = slash || ''; + format = format || ''; + capture = capture || '([^\\/' + format + ']+?)'; + optional = optional || ''; + + keys.push({ + name: key, + optional: !!optional, + offset: offset + extraOffset + }); + + var result = '' + + (optional ? '' : slash) + + '(?:' + + format + (optional ? slash : '') + capture + + (star ? '((?:[\\/' + format + '].+?)?)' : '') + + ')' + + optional; + + extraOffset += result.length - match.length; + + return result; + }) + .replace(/\*/g, function (star, index) { + var len = keys.length + + while (len-- > keysOffset && keys[len].offset > index) { + keys[len].offset += 3; // Replacement length minus asterisk length. + } + + return '(.*)'; + }); + + // This is a workaround for handling unnamed matching groups. + while (m = MATCHING_GROUP_REGEXP.exec(path)) { + var escapeCount = 0; + var index = m.index; + + while (path.charAt(--index) === '\\') { + escapeCount++; + } + + // It's possible to escape the bracket. + if (escapeCount % 2 === 1) { + continue; + } + + if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) { + keys.splice(keysOffset + i, 0, { + name: name++, // Unnamed matching groups must be consistently linear. + optional: false, + offset: m.index + }); + } + + i++; + } + + // If the path is non-ending, match until the end or a slash. + path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)')); + + return new RegExp(path, flags); +}; diff --git a/2-2/node_modules/express/node_modules/path-to-regexp/package.json b/2-2/node_modules/express/node_modules/path-to-regexp/package.json new file mode 100644 index 0000000..118b1e6 --- /dev/null +++ b/2-2/node_modules/express/node_modules/path-to-regexp/package.json @@ -0,0 +1,185 @@ +{ + "name": "path-to-regexp", + "description": "Express style path to RegExp utility", + "version": "0.1.7", + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "keywords": [ + "express", + "regexp" + ], + "component": { + "scripts": { + "path-to-regexp": "index.js" + } + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/component/path-to-regexp.git" + }, + "devDependencies": { + "mocha": "^1.17.1", + "istanbul": "^0.2.6" + }, + "gitHead": "039118d6c3c186d3f176c73935ca887a32a33d93", + "bugs": { + "url": "https://github.com/component/path-to-regexp/issues" + }, + "homepage": "https://github.com/component/path-to-regexp#readme", + "_id": "path-to-regexp@0.1.7", + "_shasum": "df604178005f522f15eb4490e7247a1bfaa67f8c", + "_from": "path-to-regexp@0.1.7", + "_npmVersion": "2.13.2", + "_nodeVersion": "2.3.3", + "_npmUser": { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "hughsk", + "email": "hughskennedy@gmail.com" + }, + { + "name": "timaschew", + "email": "timaschew@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "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": "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" + }, + { + "name": "dfcreative", + "email": "df.creative@gmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "df604178005f522f15eb4490e7247a1bfaa67f8c", + "tarball": "http://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/proxy-addr/HISTORY.md b/2-2/node_modules/express/node_modules/proxy-addr/HISTORY.md new file mode 100644 index 0000000..84f11aa --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/HISTORY.md @@ -0,0 +1,80 @@ +1.0.10 / 2015-12-09 +=================== + + * deps: ipaddr.js@1.0.5 + - Fix regression in `isValid` with non-string arguments + +1.0.9 / 2015-12-01 +================== + + * deps: ipaddr.js@1.0.4 + - Fix accepting some invalid IPv6 addresses + - Reject CIDRs with negative or overlong masks + * perf: enable strict mode + +1.0.8 / 2015-05-10 +================== + + * deps: ipaddr.js@1.0.1 + +1.0.7 / 2015-03-16 +================== + + * deps: ipaddr.js@0.1.9 + - Fix OOM on certain inputs to `isValid` + +1.0.6 / 2015-02-01 +================== + + * deps: ipaddr.js@0.1.8 + +1.0.5 / 2015-01-08 +================== + + * deps: ipaddr.js@0.1.6 + +1.0.4 / 2014-11-23 +================== + + * deps: ipaddr.js@0.1.5 + - Fix edge cases with `isValid` + +1.0.3 / 2014-09-21 +================== + + * Use `forwarded` npm module + +1.0.2 / 2014-09-18 +================== + + * Fix a global leak when multiple subnets are trusted + * Support Node.js 0.6 + * deps: ipaddr.js@0.1.3 + +1.0.1 / 2014-06-03 +================== + + * Fix links in npm package + +1.0.0 / 2014-05-08 +================== + + * Add `trust` argument to determine proxy trust on + * Accepts custom function + * Accepts IPv4/IPv6 address(es) + * Accepts subnets + * Accepts pre-defined names + * Add optional `trust` argument to `proxyaddr.all` to + stop at first untrusted + * Add `proxyaddr.compile` to pre-compile `trust` function + to make subsequent calls faster + +0.0.1 / 2014-05-04 +================== + + * Fix bad npm publish + +0.0.0 / 2014-05-04 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/proxy-addr/LICENSE b/2-2/node_modules/express/node_modules/proxy-addr/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/proxy-addr/README.md b/2-2/node_modules/express/node_modules/proxy-addr/README.md new file mode 100644 index 0000000..26f7fc0 --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/README.md @@ -0,0 +1,137 @@ +# proxy-addr + +[![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] + +Determine address of proxied request + +## Install + +```sh +$ npm install proxy-addr +``` + +## API + +```js +var proxyaddr = require('proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + +```js +proxyaddr(req, function(addr){ return addr === '127.0.0.1' }) +proxyaddr(req, function(addr, i){ return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +proxyaddr(req, ['fe80::/ffc0::']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + +```js +var trust = proxyaddr.compile('localhost') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master +[downloads-image]: https://img.shields.io/npm/dm/proxy-addr.svg +[downloads-url]: https://npmjs.org/package/proxy-addr diff --git a/2-2/node_modules/express/node_modules/proxy-addr/index.js b/2-2/node_modules/express/node_modules/proxy-addr/index.js new file mode 100644 index 0000000..3200efb --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/index.js @@ -0,0 +1,347 @@ +/*! + * proxy-addr + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = proxyaddr; +module.exports.all = alladdrs; +module.exports.compile = compile; + +/** + * Module dependencies. + */ + +var forwarded = require('forwarded'); +var ipaddr = require('ipaddr.js'); + +/** + * Variables. + */ + +var digitre = /^[0-9]+$/; +var isip = ipaddr.isValid; +var parseip = ipaddr.parse; + +/** + * Pre-defined IP ranges. + */ + +var ipranges = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +}; + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @api public + */ + +function alladdrs(req, trust) { + // get addresses + var addrs = forwarded(req); + + if (!trust) { + // Return all addresses + return addrs; + } + + if (typeof trust !== 'function') { + trust = compile(trust); + } + + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue; + + addrs.length = i + 1; + } + + return addrs; +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @api private + */ + +function compile(val) { + if (!val) { + throw new TypeError('argument is required'); + } + + var trust = typeof val === 'string' + ? [val] + : val; + + if (!Array.isArray(trust)) { + throw new TypeError('unsupported trust argument'); + } + + for (var i = 0; i < trust.length; i++) { + val = trust[i]; + + if (!ipranges.hasOwnProperty(val)) { + continue; + } + + // Splice in pre-defined range + val = ipranges[val]; + trust.splice.apply(trust, [i, 1].concat(val)); + i += val.length - 1; + } + + return compileTrust(compileRangeSubnets(trust)); +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @api private + */ + +function compileRangeSubnets(arr) { + var rangeSubnets = new Array(arr.length); + + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]); + } + + return rangeSubnets; +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @api private + */ + +function compileTrust(rangeSubnets) { + // Return optimized function based on length + var len = rangeSubnets.length; + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets); +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @api private + */ + +function parseipNotation(note) { + var ip; + var kind; + var max; + var pos = note.lastIndexOf('/'); + var range; + + ip = pos !== -1 + ? note.substring(0, pos) + : note; + + if (!isip(ip)) { + throw new TypeError('invalid IP address: ' + ip); + } + + ip = parseip(ip); + + kind = ip.kind(); + max = kind === 'ipv6' + ? 128 + : 32; + + range = pos !== -1 + ? note.substring(pos + 1, note.length) + : max; + + if (typeof range !== 'number') { + range = digitre.test(range) + ? parseInt(range, 10) + : isip(range) + ? parseNetmask(range) + : 0; + } + + if (ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address(); + range = range <= max + ? range - 96 + : range; + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note); + } + + return [ip, range]; +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} note + * @api private + */ + +function parseNetmask(netmask) { + var ip = parseip(netmask); + var parts; + var size; + + switch (ip.kind()) { + case 'ipv4': + parts = ip.octets; + size = 8; + break; + case 'ipv6': + parts = ip.parts; + size = 16; + break; + } + + var max = Math.pow(2, size) - 1; + var part; + var range = 0; + + for (var i = 0; i < parts.length; i++) { + part = parts[i] & max; + + if (part === max) { + range += size; + continue; + } + + while (part) { + part = (part << 1) & max; + range += 1; + } + + break; + } + + return range; +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @api public + */ + +function proxyaddr(req, trust) { + if (!req) { + throw new TypeError('req argument is required'); + } + + if (!trust) { + throw new TypeError('trust argument is required'); + } + + var addrs = alladdrs(req, trust); + var addr = addrs[addrs.length - 1]; + + return addr; +} + +/** + * Static trust function to trust nothing. + * + * @api private + */ + +function trustNone() { + return false; +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @api private + */ + +function trustMulti(subnets) { + return function trust(addr) { + if (!isip(addr)) return false; + + var ip = parseip(addr); + var ipv4; + var kind = ip.kind(); + var subnet; + var subnetip; + var subnetkind; + var subnetrange; + var trusted; + + for (var i = 0; i < subnets.length; i++) { + subnet = subnets[i]; + subnetip = subnet[0]; + subnetkind = subnetip.kind(); + subnetrange = subnet[1]; + trusted = ip; + + if (kind !== subnetkind) { + if (kind !== 'ipv6' || subnetkind !== 'ipv4' || !ip.isIPv4MappedAddress()) { + continue; + } + + // Store addr as IPv4 + ipv4 = ipv4 || ip.toIPv4Address(); + trusted = ipv4; + } + + if (trusted.match(subnetip, subnetrange)) return true; + } + + return false; + }; +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @api private + */ + +function trustSingle(subnet) { + var subnetip = subnet[0]; + var subnetkind = subnetip.kind(); + var subnetisipv4 = subnetkind === 'ipv4'; + var subnetrange = subnet[1]; + + return function trust(addr) { + if (!isip(addr)) return false; + + var ip = parseip(addr); + var kind = ip.kind(); + + return kind === subnetkind + ? ip.match(subnetip, subnetrange) + : subnetisipv4 && kind === 'ipv6' && ip.isIPv4MappedAddress() + ? ip.toIPv4Address().match(subnetip, subnetrange) + : false; + }; +} diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md new file mode 100644 index 0000000..97fa1d1 --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md @@ -0,0 +1,4 @@ +0.1.0 / 2014-09-21 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md new file mode 100644 index 0000000..2b4988f --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md @@ -0,0 +1,53 @@ +# forwarded + +[![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] + +Parse HTTP X-Forwarded-For header + +## Installation + +```sh +$ npm install forwarded +``` + +## API + +```js +var forwarded = require('forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`. In reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/forwarded.svg?style=flat +[npm-url]: https://npmjs.org/package/forwarded +[node-version-image]: https://img.shields.io/node/v/forwarded.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/forwarded.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/forwarded +[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master +[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg?style=flat +[downloads-url]: https://npmjs.org/package/forwarded diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js new file mode 100644 index 0000000..2f5c340 --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js @@ -0,0 +1,35 @@ +/*! + * forwarded + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {Object} req + * @api public + */ + +function forwarded(req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = (req.headers['x-forwarded-for'] || '') + .split(/ *, */) + .filter(Boolean) + .reverse() + var socketAddr = req.connection.remoteAddress + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json new file mode 100644 index 0000000..7d24004 --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json @@ -0,0 +1,65 @@ +{ + "name": "forwarded", + "description": "Parse HTTP X-Forwarded-For header", + "version": "0.1.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "x-forwarded-for", + "http", + "req" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/forwarded.git" + }, + "devDependencies": { + "istanbul": "0.3.2", + "mocha": "~1.21.4" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "e9a9faeb3cfaadf40eb57d144fff26bca9b818e8", + "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 <0.2.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", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore new file mode 100644 index 0000000..7a1537b --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore @@ -0,0 +1,2 @@ +.idea +node_modules diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml new file mode 100644 index 0000000..aa3d14a --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml @@ -0,0 +1,10 @@ +language: node_js + +node_js: + - "0.10" + - "0.11" + - "0.12" + - "4.0" + - "4.1" + - "4.2" + - "5" diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile new file mode 100644 index 0000000..7fd355a --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile @@ -0,0 +1,18 @@ +fs = require 'fs' +CoffeeScript = require 'coffee-script' +nodeunit = require 'nodeunit' +UglifyJS = require 'uglify-js' + +task 'build', 'build the JavaScript files from CoffeeScript source', build = (cb) -> + source = fs.readFileSync 'src/ipaddr.coffee' + fs.writeFileSync 'lib/ipaddr.js', CoffeeScript.compile source.toString() + + invoke 'test' + invoke 'compress' + +task 'test', 'run the bundled tests', (cb) -> + nodeunit.reporters.default.run ['test'] + +task 'compress', 'uglify the resulting javascript', (cb) -> + result = UglifyJS.minify('lib/ipaddr.js') + fs.writeFileSync('ipaddr.min.js', result.code) diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE new file mode 100644 index 0000000..3493f0d --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011 Peter Zotov + +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/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md new file mode 100644 index 0000000..f4f8776 --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md @@ -0,0 +1,161 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +var ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and +`ipaddr.process`. All of them receive a string as a single parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 couterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. +Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); +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"` +(the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with both +IPv6 and IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +var rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "he.net" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. +(Actually, JavaScript mostly does not know about byte buffers. They are emulated with +arrays of numbers, each in range of 0..255.) + +```js +var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them +have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address +for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with +the `::` substitution); the `toNormalizedString()` method will return an address where +all zeroes are explicit. + +For example: + +```js +var addr = ipaddr.parse("2001:0db8::0001"); +addr.toString(); // => "2001:db8::1" +addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +var addr = ipaddr.parse("192.168.1.1"); +addr.octets // => [192, 168, 1, 1] +``` diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json new file mode 100644 index 0000000..bc04ffe --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json @@ -0,0 +1,29 @@ +{ + "name": "ipaddr.js", + "version": "1.0.5", + "homepage": "https://github.com/whitequark/ipaddr.js", + "authors": [ + "whitequark " + ], + "description": "IP address manipulation library in JavaScript (CoffeeScript, actually)", + "main": "lib/ipaddr.js", + "moduleType": [ + "globals", + "node" + ], + "keywords": [ + "javscript", + "ip", + "address", + "ipv4", + "ipv6" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 0000000..ee5179d --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.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),r[i]>>o!==t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(e in t)for(i=t[e],!i[0]||i[0]instanceof Array||(i=[i]),a=0,s=i.length;s>a;a++)if(o=i[a],r.match.apply(r,o))return e;return n},t.IPv4=function(){function r(r){var t,n,e;if(4!==r.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(n=0,e=r.length;e>n;n++)if(t=r[n],!(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 n;if(void 0===t&&(n=r,r=n[0],t=n[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}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(o=t.slice(1,6),a=[],r=0,e=o.length;e>r;r++)i=o[r],a.push(n(i));return a}();if(t=r.match(e.longValue)){if(a=n(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,n,e;if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8");for(n=0,e=r.length;e>n;n++)if(t=r[n],!(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,n,e,i,o,a;for(i=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),r=[],n=function(t){return r.push(t)},e=0,o=0,a=i.length;a>o;o++)switch(t=i[o],e){case 0:n("0"===t?"":t),e=1;break;case 1:"0"===t?e=2:n(t);break;case 2:"0"!==t&&(n(""),n(t),e=3);break;case 3:n(t)}return 2===e&&(n(""),n("")),r.join(":")},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],i=this.parts,n=0,e=i.length;e>n;n++)t=i[n],r.push(t>>8),r.push(255&t);return r},r.prototype.toNormalizedString=function(){var r;return 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).join(":")},r.prototype.match=function(r,t){var n;if(void 0===t&&(n=r,r=n[0],t=n[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,n,e;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=this.parts.slice(-2),r=e[0],n=e[1],new t.IPv4([r>>8,255&r,n>>8,255&n])},r}(),i="(?:[0-9a-f]+::?)+",o={"native":new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+(""+n+"\\."+n+"\\."+n+"\\."+n+"$"),"i")},r=function(r,t){var n,e,i,o,a;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for(n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(a=t-n,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,n,e,o;for(e=r.split(":"),o=[],t=0,n=e.length;n>t;t++)i=e[t],o.push(parseInt(i,16));return o}()},t.IPv6.parser=function(t){var n,e;return t.match(o["native"])?r(t,8):(n=t.match(o.transitional))&&(e=r(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},t.IPv4.isIPv4=t.IPv6.isIPv6=function(r){return null!==this.parser(r)},t.IPv4.isValid=function(r){var t;try{return new this(this.parser(r)),!0}catch(n){return t=n,!1}},t.IPv6.isValid=function(r){var t;if("string"==typeof r&&-1===r.indexOf(":"))return!1;try{return new this(this.parser(r)),!0}catch(n){return t=n,!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=function(r){var t,n;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&32>=t))return[this.parse(n[1]),t];throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv6.parseCIDR=function(r){var t,n;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&128>=t))return[this.parse(n[1]),t];throw new Error("ipaddr: string is not formatted like an IPv6 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 n;try{return t.IPv6.parseCIDR(r)}catch(e){n=e;try{return t.IPv4.parseCIDR(r)}catch(e){throw n=e,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/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js new file mode 100644 index 0000000..ef179b4 --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js @@ -0,0 +1,467 @@ +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root; + + ipaddr = {}; + + root = this; + + if ((typeof module !== "undefined" && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } + + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var rangeName, rangeSubnets, subnet, _i, _len; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (_i = 0, _len = rangeSubnets.length; _i < _len; _i++) { + subnet = rangeSubnets[_i]; + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + return defaultName; + }; + + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var octet, _i, _len; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (_i = 0, _len = octets.length; _i < _len; _i++) { + octet = octets[_i]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet is a byte"); + } + } + this.octets = octets; + } + + IPv4.prototype.kind = function() { + return 'ipv4'; + }; + + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + + 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"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; + + return IPv4; + + })(); + + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; + + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var _i, _len, _ref, _results; + _ref = match.slice(1, 6); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(parseIntAuto(part)); + } + return _results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var _i, _results; + _results = []; + for (shift = _i = 0; _i <= 24; shift = _i += 8) { + _results.push((value >> shift) & 0xff); + } + return _results; + })()).reverse(); + } else { + return null; + } + }; + + ipaddr.IPv6 = (function() { + function IPv6(parts) { + var part, _i, _len; + if (parts.length !== 8) { + throw new Error("ipaddr: ipv6 part count should be 8"); + } + for (_i = 0, _len = parts.length; _i < _len; _i++) { + part = parts[_i]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit to two octets"); + } + } + this.parts = parts; + } + + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + + IPv6.prototype.toString = function() { + var compactStringParts, part, pushPart, state, stringParts, _i, _len; + stringParts = (function() { + var _i, _len, _ref, _results; + _ref = this.parts; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(part.toString(16)); + } + return _results; + }).call(this); + compactStringParts = []; + pushPart = function(part) { + return compactStringParts.push(part); + }; + state = 0; + for (_i = 0, _len = stringParts.length; _i < _len; _i++) { + part = stringParts[_i]; + switch (state) { + case 0: + if (part === '0') { + pushPart(''); + } else { + pushPart(part); + } + state = 1; + break; + case 1: + if (part === '0') { + state = 2; + } else { + pushPart(part); + } + break; + case 2: + if (part !== '0') { + pushPart(''); + pushPart(part); + state = 3; + } + break; + case 3: + pushPart(part); + } + } + if (state === 2) { + pushPart(''); + pushPart(''); + } + return compactStringParts.join(":"); + }; + + IPv6.prototype.toByteArray = function() { + var bytes, part, _i, _len, _ref; + bytes = []; + _ref = this.parts; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; + + IPv6.prototype.toNormalizedString = function() { + var part; + return ((function() { + var _i, _len, _ref, _results; + _ref = this.parts; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(part.toString(16)); + } + return _results; + }).call(this)).join(":"); + }; + + 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"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; + + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; + + IPv6.prototype.toIPv4Address = function() { + var high, low, _ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + _ref = this.parts.slice(-2), high = _ref[0], low = _ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + return IPv6; + + })(); + + ipv6Part = "(?:[0-9a-f]+::?)+"; + + ipv6Regexes = { + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + ("" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$"), 'i') + }; + + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + return (function() { + var _i, _len, _ref, _results; + _ref = string.split(":"); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(parseInt(part, 16)); + } + return _results; + })(); + }; + + ipaddr.IPv6.parser = function(string) { + var match, parts; + if (string.match(ipv6Regexes['native'])) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + parts = expandIPv6(match[1].slice(0, -1), 6); + if (parts) { + parts.push(parseInt(match[2]) << 8 | parseInt(match[3])); + parts.push(parseInt(match[4]) << 8 | parseInt(match[5])); + return parts; + } + } + return null; + }; + + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (_error) { + e = _error; + return false; + } + }; + + ipaddr.IPv6.isValid = function(string) { + var e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + new this(this.parser(string)); + return true; + } catch (_error) { + e = _error; + return false; + } + }; + + ipaddr.IPv4.parse = ipaddr.IPv6.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + return [this.parse(match[1]), maskLength]; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + return [this.parse(match[1]), maskLength]; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + + 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); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + +}).call(this); diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json new file mode 100644 index 0000000..6b61f32 --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json @@ -0,0 +1,60 @@ +{ + "name": "ipaddr.js", + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "version": "1.0.5", + "author": { + "name": "whitequark", + "email": "whitequark@whitequark.org" + }, + "directories": { + "lib": "./lib" + }, + "dependencies": {}, + "devDependencies": { + "coffee-script": "~1.6", + "nodeunit": ">=0.8.2 <0.8.7", + "uglify-js": "latest" + }, + "scripts": { + "test": "cake build test" + }, + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "repository": { + "type": "git", + "url": "git://github.com/whitequark/ipaddr.js.git" + }, + "main": "./lib/ipaddr", + "engines": { + "node": ">= 0.10" + }, + "license": "MIT", + "gitHead": "46438c8bfa187505b7007a277f09a4a9e73d5686", + "bugs": { + "url": "https://github.com/whitequark/ipaddr.js/issues" + }, + "_id": "ipaddr.js@1.0.5", + "_shasum": "5fa78cf301b825c78abc3042d812723049ea23c7", + "_from": "ipaddr.js@1.0.5", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "whitequark", + "email": "whitequark@whitequark.org" + }, + "maintainers": [ + { + "name": "whitequark", + "email": "whitequark@whitequark.org" + } + ], + "dist": { + "shasum": "5fa78cf301b825c78abc3042d812723049ea23c7", + "tarball": "http://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.0.5.tgz" + }, + "_resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.0.5.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/whitequark/ipaddr.js#readme" +} diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee new file mode 100644 index 0000000..550174f --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee @@ -0,0 +1,396 @@ +# Define the main object +ipaddr = {} + +root = this + +# Export for both the CommonJS and browser-like environment +if module? && module.exports + module.exports = ipaddr +else + root['ipaddr'] = ipaddr + +# A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher. +matchCIDR = (first, second, partSize, cidrBits) -> + if first.length != second.length + throw new Error "ipaddr: cannot match CIDR for objects with different lengths" + + part = 0 + while cidrBits > 0 + shift = partSize - cidrBits + shift = 0 if shift < 0 + + if first[part] >> shift != second[part] >> shift + return false + + cidrBits -= partSize + part += 1 + + return true + +# An utility function to ease named range matching. See examples below. +ipaddr.subnetMatch = (address, rangeList, defaultName='unicast') -> + for rangeName, rangeSubnets of rangeList + # ECMA5 Array.isArray isn't available everywhere + if rangeSubnets[0] && !(rangeSubnets[0] instanceof Array) + rangeSubnets = [ rangeSubnets ] + + for subnet in rangeSubnets + return rangeName if address.match.apply(address, subnet) + + return defaultName + +# An IPv4 address (RFC791). +class ipaddr.IPv4 + # Constructs a new IPv4 address from an array of four octets. + # Verifies the input. + constructor: (octets) -> + if octets.length != 4 + throw new Error "ipaddr: ipv4 octet count should be 4" + + for octet in octets + if !(0 <= octet <= 255) + throw new Error "ipaddr: ipv4 octet is a byte" + + @octets = octets + + # The 'kind' method exists on both IPv4 and IPv6 classes. + kind: -> + return 'ipv4' + + # Returns the address in convenient, decimal-dotted format. + toString: -> + return @octets.join "." + + # Returns an array of byte-sized values in network order + toByteArray: -> + return @octets.slice(0) # octets.clone + + # 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" + + return matchCIDR(this.octets, other.octets, 8, cidrRange) + + # Special IPv4 address ranges. + SpecialRanges: + unspecified: [ + [ new IPv4([0, 0, 0, 0]), 8 ] + ] + broadcast: [ + [ new IPv4([255, 255, 255, 255]), 32 ] + ] + multicast: [ # RFC3171 + [ new IPv4([224, 0, 0, 0]), 4 ] + ] + linkLocal: [ # RFC3927 + [ new IPv4([169, 254, 0, 0]), 16 ] + ] + loopback: [ # RFC5735 + [ new IPv4([127, 0, 0, 0]), 8 ] + ] + private: [ # RFC1918 + [ new IPv4([10, 0, 0, 0]), 8 ] + [ new IPv4([172, 16, 0, 0]), 12 ] + [ new IPv4([192, 168, 0, 0]), 16 ] + ] + reserved: [ # Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700 + [ new IPv4([192, 0, 0, 0]), 24 ] + [ new IPv4([192, 0, 2, 0]), 24 ] + [ new IPv4([192, 88, 99, 0]), 24 ] + [ new IPv4([198, 51, 100, 0]), 24 ] + [ new IPv4([203, 0, 113, 0]), 24 ] + [ new IPv4([240, 0, 0, 0]), 4 ] + ] + + # Checks if the address corresponds to one of the special ranges. + range: -> + return ipaddr.subnetMatch(this, @SpecialRanges) + + # Convrets this IPv4 address to an IPv4-mapped IPv6 address. + toIPv4MappedAddress: -> + return ipaddr.IPv6.parse "::ffff:#{@toString()}" + +# A list of regular expressions that match arbitrary IPv4 addresses, +# for which a number of weird notations exist. +# Note that an address like 0010.0xa5.1.1 is considered legal. +ipv4Part = "(0?\\d+|0x[a-f0-9]+)" +ipv4Regexes = + fourOctet: new RegExp "^#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' + longValue: new RegExp "^#{ipv4Part}$", 'i' + +# Classful variants (like a.b, where a is an octet, and b is a 24-bit +# value representing last three octets; this corresponds to a class C +# address) are omitted due to classless nature of modern Internet. +ipaddr.IPv4.parser = (string) -> + parseIntAuto = (string) -> + if string[0] == "0" && string[1] != "x" + parseInt(string, 8) + else + parseInt(string) + + # parseInt recognizes all that octal & hexadecimal weirdness for us + if match = string.match(ipv4Regexes.fourOctet) + return (parseIntAuto(part) for part in match[1..5]) + else if match = string.match(ipv4Regexes.longValue) + value = parseIntAuto(match[1]) + if value > 0xffffffff || value < 0 + throw new Error "ipaddr: address outside defined range" + return ((value >> shift) & 0xff for shift in [0..24] by 8).reverse() + else + return null + +# An IPv6 address (RFC2460) +class ipaddr.IPv6 + # Constructs an IPv6 address from an array of eight 16-bit parts. + # Throws an error if the input is invalid. + constructor: (parts) -> + if parts.length != 8 + throw new Error "ipaddr: ipv6 part count should be 8" + + for part in parts + if !(0 <= part <= 0xffff) + throw new Error "ipaddr: ipv6 part should fit to two octets" + + @parts = parts + + # The 'kind' method exists on both IPv4 and IPv6 classes. + kind: -> + return 'ipv6' + + # Returns the address in compact, human-readable format like + # 2001:db8:8:66::1 + toString: -> + stringParts = (part.toString(16) for part in @parts) + + compactStringParts = [] + pushPart = (part) -> compactStringParts.push part + + state = 0 + for part in stringParts + switch state + when 0 + if part == '0' + pushPart('') + else + pushPart(part) + + state = 1 + when 1 + if part == '0' + state = 2 + else + pushPart(part) + when 2 + unless part == '0' + pushPart('') + pushPart(part) + state = 3 + when 3 + pushPart(part) + + if state == 2 + pushPart('') + pushPart('') + + return compactStringParts.join ":" + + # Returns an array of byte-sized values in network order + toByteArray: -> + bytes = [] + for part in @parts + bytes.push(part >> 8) + bytes.push(part & 0xff) + + return bytes + + # Returns the address in expanded format with all zeroes included, like + # 2001:db8:8:66:0:0:0:1 + toNormalizedString: -> + return (part.toString(16) for part in @parts).join ":" + + # 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" + + return matchCIDR(this.parts, other.parts, 16, cidrRange) + + # Special IPv6 ranges + SpecialRanges: + unspecified: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128 ] # RFC4291, here and after + linkLocal: [ new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10 ] + multicast: [ new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8 ] + loopback: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128 ] + uniqueLocal: [ new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7 ] + ipv4Mapped: [ new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96 ] + rfc6145: [ new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96 ] # RFC6145 + rfc6052: [ new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96 ] # RFC6052 + '6to4': [ new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16 ] # RFC3056 + teredo: [ new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32 ] # RFC6052, RFC6146 + reserved: [ + [ new IPv6([ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32 ] # RFC4291 + ] + + # Checks if the address corresponds to one of the special ranges. + range: -> + return ipaddr.subnetMatch(this, @SpecialRanges) + + # Checks if this address is an IPv4-mapped IPv6 address. + isIPv4MappedAddress: -> + return @range() == 'ipv4Mapped' + + # Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address. + # Throws an error otherwise. + toIPv4Address: -> + unless @isIPv4MappedAddress() + throw new Error "ipaddr: trying to convert a generic ipv6 address to ipv4" + + [high, low] = @parts[-2..-1] + + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]) + +# IPv6-matching regular expressions. +# For IPv6, the task is simpler: it is enough to match the colon-delimited +# hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at +# the end. +ipv6Part = "(?:[0-9a-f]+::?)+" +ipv6Regexes = + native: new RegExp "^(::)?(#{ipv6Part})?([0-9a-f]+)?(::)?$", 'i' + transitional: new RegExp "^((?:#{ipv6Part})|(?:::)(?:#{ipv6Part})?)" + + "#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' + +# Expand :: in an IPv6 address or address part consisting of `parts` groups. +expandIPv6 = (string, parts) -> + # More than one '::' means invalid adddress + if string.indexOf('::') != string.lastIndexOf('::') + return null + + # How many parts do we already have? + colonCount = 0 + lastColon = -1 + while (lastColon = string.indexOf(':', lastColon + 1)) >= 0 + colonCount++ + + # 0::0 is two parts more than :: + colonCount-- if string.substr(0, 2) == '::' + colonCount-- if string.substr(-2, 2) == '::' + + # The following loop would hang if colonCount > parts + if colonCount > parts + return null + + # replacement = ':' + '0:' * (parts - colonCount) + replacementCount = parts - colonCount + replacement = ':' + while replacementCount-- + replacement += '0:' + + # Insert the missing zeroes + string = string.replace('::', replacement) + + # Trim any garbage which may be hanging around if :: was at the edge in + # the source string + string = string[1..-1] if string[0] == ':' + string = string[0..-2] if string[string.length-1] == ':' + + return (parseInt(part, 16) for part in string.split(":")) + +# Parse an IPv6 address. +ipaddr.IPv6.parser = (string) -> + if string.match(ipv6Regexes['native']) + return expandIPv6(string, 8) + + else if match = string.match(ipv6Regexes['transitional']) + parts = expandIPv6(match[1][0..-2], 6) + if parts + parts.push(parseInt(match[2]) << 8 | parseInt(match[3])) + parts.push(parseInt(match[4]) << 8 | parseInt(match[5])) + return parts + + return null + +# Checks if a given string is formatted like IPv4/IPv6 address. +ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = (string) -> + return @parser(string) != null + +# Checks if a given string is a valid IPv4/IPv6 address. +ipaddr.IPv4.isValid = (string) -> + try + new this(@parser(string)) + return true + catch e + return false + +ipaddr.IPv6.isValid = (string) -> + # Since IPv6.isValid is always called first, this shortcut + # provides a substantial performance gain. + if typeof string == "string" and string.indexOf(":") == -1 + return false + + try + new this(@parser(string)) + return true + catch e + return false + +# Tries to parse and validate a string with IPv4/IPv6 address. +# Throws an error if it fails. +ipaddr.IPv4.parse = ipaddr.IPv6.parse = (string) -> + parts = @parser(string) + if parts == null + throw new Error "ipaddr: string is not formatted like ip address" + + return new this(parts) + +ipaddr.IPv4.parseCIDR = (string) -> + if match = string.match(/^(.+)\/(\d+)$/) + maskLength = parseInt(match[2]) + if maskLength >= 0 and maskLength <= 32 + return [@parse(match[1]), maskLength] + + throw new Error "ipaddr: string is not formatted like an IPv4 CIDR range" + +ipaddr.IPv6.parseCIDR = (string) -> + if match = string.match(/^(.+)\/(\d+)$/) + maskLength = parseInt(match[2]) + if maskLength >= 0 and maskLength <= 128 + return [@parse(match[1]), maskLength] + + throw new Error "ipaddr: string is not formatted like an IPv6 CIDR range" + +# Checks if the address is valid IP address +ipaddr.isValid = (string) -> + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string) + +# Try to parse an address and throw an error if it is impossible +ipaddr.parse = (string) -> + if ipaddr.IPv6.isValid(string) + return ipaddr.IPv6.parse(string) + else if ipaddr.IPv4.isValid(string) + return ipaddr.IPv4.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) + if addr.kind() == 'ipv6' && addr.isIPv4MappedAddress() + return addr.toIPv4Address() + else + return addr diff --git a/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee new file mode 100644 index 0000000..17739e2 --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee @@ -0,0 +1,282 @@ +ipaddr = require '../lib/ipaddr' + +module.exports = + 'should define main classes': (test) -> + test.ok(ipaddr.IPv4?, 'defines IPv4 class') + test.ok(ipaddr.IPv6?, 'defines IPv6 class') + test.done() + + 'can construct IPv4 from octets': (test) -> + test.doesNotThrow -> + new ipaddr.IPv4([192, 168, 1, 2]) + test.done() + + 'refuses to construct invalid IPv4': (test) -> + test.throws -> + new ipaddr.IPv4([300, 1, 2, 3]) + test.throws -> + new ipaddr.IPv4([8, 8, 8]) + test.done() + + 'converts IPv4 to string correctly': (test) -> + addr = new ipaddr.IPv4([192, 168, 1, 1]) + test.equal(addr.toString(), '192.168.1.1') + test.done() + + 'returns correct kind for IPv4': (test) -> + addr = new ipaddr.IPv4([1, 2, 3, 4]) + test.equal(addr.kind(), 'ipv4') + test.done() + + 'allows to access IPv4 octets': (test) -> + addr = new ipaddr.IPv4([42, 0, 0, 0]) + test.equal(addr.octets[0], 42) + test.done() + + 'checks IPv4 address format': (test) -> + test.equal(ipaddr.IPv4.isIPv4('192.168.007.0xa'), true) + test.equal(ipaddr.IPv4.isIPv4('1024.0.0.1'), true) + test.equal(ipaddr.IPv4.isIPv4('8.0xa.wtf.6'), false) + test.done() + + 'validates IPv4 addresses': (test) -> + test.equal(ipaddr.IPv4.isValid('192.168.007.0xa'), true) + test.equal(ipaddr.IPv4.isValid('1024.0.0.1'), false) + test.equal(ipaddr.IPv4.isValid('8.0xa.wtf.6'), false) + test.done() + + 'parses IPv4 in several weird formats': (test) -> + test.deepEqual(ipaddr.IPv4.parse('192.168.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('0xc0.168.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('192.0250.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('0xc0a80101').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('030052000401').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('3232235777').octets, [192, 168, 1, 1]) + test.done() + + 'barfs at invalid IPv4': (test) -> + test.throws -> + ipaddr.IPv4.parse('10.0.0.wtf') + test.done() + + 'matches IPv4 CIDR correctly': (test) -> + addr = new ipaddr.IPv4([10, 5, 0, 1]) + test.equal(addr.match(ipaddr.IPv4.parse('0.0.0.0'), 0), true) + test.equal(addr.match(ipaddr.IPv4.parse('11.0.0.0'), 8), false) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.0'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.1'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.10'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.5.5.0'), 16), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 16), false) + test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 15), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.5.0.2'), 32), false) + 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.throws -> + ipaddr.IPv4.parseCIDR('0.0.0.0/-1') + test.throws -> + ipaddr.IPv4.parseCIDR('0.0.0.0/33') + 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') + test.equal(ipaddr.IPv4.parse('10.1.0.1').range(), 'private') + test.equal(ipaddr.IPv4.parse('192.168.2.1').range(), 'private') + test.equal(ipaddr.IPv4.parse('224.100.0.1').range(), 'multicast') + test.equal(ipaddr.IPv4.parse('169.254.15.0').range(), 'linkLocal') + test.equal(ipaddr.IPv4.parse('127.1.1.1').range(), 'loopback') + test.equal(ipaddr.IPv4.parse('255.255.255.255').range(), 'broadcast') + test.equal(ipaddr.IPv4.parse('240.1.2.3').range(), 'reserved') + test.equal(ipaddr.IPv4.parse('8.8.8.8').range(), 'unicast') + test.done() + + 'can construct IPv6 from parts': (test) -> + test.doesNotThrow -> + new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.done() + + 'refuses to construct invalid IPv6': (test) -> + test.throws -> + new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 0, 1]) + test.throws -> + new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 1]) + test.done() + + 'converts IPv6 to string correctly': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.equal(addr.toNormalizedString(), '2001:db8:f53a:0:0:0:0:1') + test.equal(addr.toString(), '2001:db8:f53a::1') + test.equal(new ipaddr.IPv6([0, 0, 0, 0, 0, 0, 0, 1]).toString(), '::1') + test.equal(new ipaddr.IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]).toString(), '2001:db8::') + test.done() + + 'returns correct kind for IPv6': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.equal(addr.kind(), 'ipv6') + test.done() + + 'allows to access IPv6 address parts': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 42, 0, 1]) + test.equal(addr.parts[5], 42) + test.done() + + 'checks IPv6 address format': (test) -> + test.equal(ipaddr.IPv6.isIPv6('2001:db8:F53A::1'), true) + test.equal(ipaddr.IPv6.isIPv6('200001::1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:192.168.1.1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1:0'), false) + test.equal(ipaddr.IPv6.isIPv6('fe80::wtf'), false) + test.done() + + 'validates IPv6 addresses': (test) -> + test.equal(ipaddr.IPv6.isValid('2001:db8:F53A::1'), true) + test.equal(ipaddr.IPv6.isValid('200001::1'), false) + test.equal(ipaddr.IPv6.isValid('::ffff:192.168.1.1'), true) + test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1'), false) + test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1:0'), false) + test.equal(ipaddr.IPv6.isValid('2001:db8::F53A::1'), false) + test.equal(ipaddr.IPv6.isValid('fe80::wtf'), false) + test.equal(ipaddr.IPv6.isValid('2002::2:'), false) + test.equal(ipaddr.IPv6.isValid(undefined), false) + test.done() + + 'parses IPv6 in different formats': (test) -> + test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A:0:0:0:0:1').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.deepEqual(ipaddr.IPv6.parse('fe80::10').parts, [0xfe80, 0, 0, 0, 0, 0, 0, 0x10]) + test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A::').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 0]) + test.deepEqual(ipaddr.IPv6.parse('::1').parts, [0, 0, 0, 0, 0, 0, 0, 1]) + test.deepEqual(ipaddr.IPv6.parse('::').parts, [0, 0, 0, 0, 0, 0, 0, 0]) + test.done() + + 'barfs at invalid IPv6': (test) -> + test.throws -> + ipaddr.IPv6.parse('fe80::0::1') + test.done() + + 'matches IPv6 CIDR correctly': (test) -> + addr = ipaddr.IPv6.parse('2001:db8:f53a::1') + test.equal(addr.match(ipaddr.IPv6.parse('::'), 0), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53a::1:1'), 64), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53b::1:1'), 48), false) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f531::1:1'), 44), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f500::1'), 40), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db9:f500::1'), 40), false) + 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.throws -> + ipaddr.IPv6.parseCIDR('2001:db8:f53a::1/-1') + test.throws -> + ipaddr.IPv6.parseCIDR('2001:db8:f53a::1/129') + test.done() + + 'converts between IPv4-mapped IPv6 addresses and IPv4 addresses': (test) -> + addr = ipaddr.IPv4.parse('77.88.21.11') + mapped = addr.toIPv4MappedAddress() + test.deepEqual(mapped.parts, [0, 0, 0, 0, 0, 0xffff, 0x4d58, 0x150b]) + test.deepEqual(mapped.toIPv4Address().octets, addr.octets) + test.done() + + 'refuses to convert non-IPv4-mapped IPv6 address to IPv4 address': (test) -> + test.throws -> + ipaddr.IPv6.parse('2001:db8::1').toIPv4Address() + test.done() + + 'detects reserved IPv6 networks': (test) -> + test.equal(ipaddr.IPv6.parse('::').range(), 'unspecified') + test.equal(ipaddr.IPv6.parse('fe80::1234:5678:abcd:0123').range(), 'linkLocal') + test.equal(ipaddr.IPv6.parse('ff00::1234').range(), 'multicast') + test.equal(ipaddr.IPv6.parse('::1').range(), 'loopback') + test.equal(ipaddr.IPv6.parse('fc00::').range(), 'uniqueLocal') + test.equal(ipaddr.IPv6.parse('::ffff:192.168.1.10').range(), 'ipv4Mapped') + test.equal(ipaddr.IPv6.parse('::ffff:0:192.168.1.10').range(), 'rfc6145') + test.equal(ipaddr.IPv6.parse('64:ff9b::1234').range(), 'rfc6052') + test.equal(ipaddr.IPv6.parse('2002:1f63:45e8::1').range(), '6to4') + test.equal(ipaddr.IPv6.parse('2001::4242').range(), 'teredo') + test.equal(ipaddr.IPv6.parse('2001:db8::3210').range(), 'reserved') + test.equal(ipaddr.IPv6.parse('2001:470:8:66::1').range(), 'unicast') + test.done() + + 'is able to determine IP address type': (test) -> + test.equal(ipaddr.parse('8.8.8.8').kind(), 'ipv4') + test.equal(ipaddr.parse('2001:db8:3312::1').kind(), 'ipv6') + test.done() + + 'throws an error if tried to parse an invalid address': (test) -> + test.throws -> + ipaddr.parse('::some.nonsense') + test.done() + + 'correctly processes IPv4-mapped addresses': (test) -> + test.equal(ipaddr.process('8.8.8.8').kind(), 'ipv4') + test.equal(ipaddr.process('2001:db8:3312::1').kind(), 'ipv6') + test.equal(ipaddr.process('::ffff:192.168.1.1').kind(), 'ipv4') + test.done() + + 'correctly converts IPv6 and IPv4 addresses to byte arrays': (test) -> + test.deepEqual(ipaddr.parse('1.2.3.4').toByteArray(), + [0x1, 0x2, 0x3, 0x4]); + # Fuck yeah. The first byte of Google's IPv6 address is 42. 42! + test.deepEqual(ipaddr.parse('2a00:1450:8007::68').toByteArray(), + [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68 ]) + test.done() + + 'correctly parses 1 as an IPv4 address': (test) -> + test.equal(ipaddr.IPv6.isValid('1'), false) + test.equal(ipaddr.IPv4.isValid('1'), true) + 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) + test.done() + + 'does not hang on ::8:8:8:8:8:8:8:8:8': (test) -> + test.equal(ipaddr.IPv6.isValid('::8:8:8:8:8:8:8:8:8'), false) + test.done() + + 'subnetMatch does not fail on empty range': (test) -> + ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {}, false) + ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {subnet: []}, false) + test.done() + + 'subnetMatch returns default subnet on empty range': (test) -> + test.equal(ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {}, false), false) + test.equal(ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {subnet: []}, false), false) + test.done() diff --git a/2-2/node_modules/express/node_modules/proxy-addr/package.json b/2-2/node_modules/express/node_modules/proxy-addr/package.json new file mode 100644 index 0000000..04af756 --- /dev/null +++ b/2-2/node_modules/express/node_modules/proxy-addr/package.json @@ -0,0 +1,90 @@ +{ + "name": "proxy-addr", + "description": "Determine address of proxied request", + "version": "1.0.10", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/proxy-addr.git" + }, + "dependencies": { + "forwarded": "~0.1.0", + "ipaddr.js": "1.0.5" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "0cdb6444100a7930285ed2555d0c3c687690a7a5", + "bugs": { + "url": "https://github.com/jshttp/proxy-addr/issues" + }, + "homepage": "https://github.com/jshttp/proxy-addr", + "_id": "proxy-addr@1.0.10", + "_shasum": "0d40a82f801fc355567d2ecb65efe3f077f121c5", + "_from": "proxy-addr@>=1.0.10 <1.1.0", + "_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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "0d40a82f801fc355567d2ecb65efe3f077f121c5", + "tarball": "http://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.10.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.10.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/qs/.eslintignore b/2-2/node_modules/express/node_modules/qs/.eslintignore new file mode 100644 index 0000000..1521c8b --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/.eslintignore @@ -0,0 +1 @@ +dist diff --git a/2-2/node_modules/express/node_modules/qs/.npmignore b/2-2/node_modules/express/node_modules/qs/.npmignore new file mode 100644 index 0000000..2abba8d --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/.npmignore @@ -0,0 +1,19 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov +complexity.md +dist diff --git a/2-2/node_modules/express/node_modules/qs/.travis.yml b/2-2/node_modules/express/node_modules/qs/.travis.yml new file mode 100644 index 0000000..f502178 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/.travis.yml @@ -0,0 +1,6 @@ +language: node_js + +node_js: + - 0.10 + - 0.12 + - iojs diff --git a/2-2/node_modules/express/node_modules/qs/CHANGELOG.md b/2-2/node_modules/express/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000..1fadc78 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/CHANGELOG.md @@ -0,0 +1,88 @@ + +## [**3.1.0**](https://github.com/hapijs/qs/issues?milestone=24&state=open) +- [**#89**](https://github.com/hapijs/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/hapijs/qs/issues?milestone=23&state=closed) +- [**#77**](https://github.com/hapijs/qs/issues/77) Perf boost +- [**#60**](https://github.com/hapijs/qs/issues/60) Add explicit option to disable array parsing +- [**#80**](https://github.com/hapijs/qs/issues/80) qs.parse silently drops properties +- [**#74**](https://github.com/hapijs/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/hapijs/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/hapijs/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/hapijs/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/hapijs/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/hapijs/qs/issues/85) No equal sign +- [**#84**](https://github.com/hapijs/qs/issues/84) update license attribute + +## [**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". + +## [**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 + +## [**2.2.5**](https://github.com/hapijs/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/hapijs/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/hapijs/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/hapijs/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/hapijs/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/hapijs/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/hapijs/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/hapijs/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/hapijs/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/hapijs/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/hapijs/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/hapijs/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/hapijs/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/hapijs/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/hapijs/qs/issues/32) account for circular references properly, closes #31 +- [**#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 +- [**#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 +- [**#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) +- [**#22**](https://github.com/hapijs/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/hapijs/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/hapijs/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/hapijs/qs/issues/20) Configurable parametersLimit +- [**#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 + +## [**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 +- [**#15**](https://github.com/hapijs/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/hapijs/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/hapijs/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/hapijs/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/hapijs/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/hapijs/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/hapijs/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/hapijs/qs/issues/6) Minor grammar fix in README + +## [**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/2-2/node_modules/express/node_modules/qs/CONTRIBUTING.md b/2-2/node_modules/express/node_modules/qs/CONTRIBUTING.md new file mode 100644 index 0000000..8928361 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/CONTRIBUTING.md @@ -0,0 +1 @@ +Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md). diff --git a/2-2/node_modules/express/node_modules/qs/LICENSE b/2-2/node_modules/express/node_modules/qs/LICENSE new file mode 100644 index 0000000..d456948 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/2-2/node_modules/express/node_modules/qs/README.md b/2-2/node_modules/express/node_modules/qs/README.md new file mode 100644 index 0000000..48a0de9 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/README.md @@ -0,0 +1,317 @@ +# qs + +A querystring parsing and stringifying library with some added security. + +[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs) + +Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var Qs = require('qs'); + +var obj = Qs.parse('a=c'); // { a: 'c' } +var str = Qs.stringify(obj); // 'a=c' +``` + +### Parsing Objects + +```javascript +Qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`, or prefixing the sub-key with a dot `.`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +{ + foo: { + bar: 'baz' + } +} +``` + +When using the `plainObjects` option the parsed value is returned as a plain object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +Qs.parse('a.hasOwnProperty=b', { plainObjects: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. + +```javascript +Qs.parse('a.hasOwnProperty=b', { allowPrototypes: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +URI encoded strings work too: + +```javascript +Qs.parse('a%5Bb%5D=c'); +// { a: { b: 'c' } } +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +{ + foo: { + bar: { + baz: 'foobarbaz' + } + } +} +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +{ + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +} +``` + +This depth can be overridden by passing a `depth` option to `Qs.parse(string, [options])`: + +```javascript +Qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } } +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +Qs.parse('a=b&c=d', { parameterLimit: 1 }); +// { a: 'b' } +``` + +An optional delimiter can also be passed: + +```javascript +Qs.parse('a=b;c=d', { delimiter: ';' }); +// { a: 'b', c: 'd' } +``` + +Delimiters can be a regular expression too: + +```javascript +Qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +// { a: 'b', c: 'd', e: 'f' } +``` + +Option `allowDots` can be used to disable dot notation: + +```javascript +Qs.parse('a.b=c', { allowDots: false }); +// { 'a.b': 'c' } } +``` + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +Qs.parse('a[]=b&a[]=c'); +// { a: ['b', 'c'] } +``` + +You may specify an index as well: + +```javascript +Qs.parse('a[1]=c&a[0]=b'); +// { a: ['b', 'c'] } +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +Qs.parse('a[1]=b&a[15]=c'); +// { a: ['b', 'c'] } +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +Qs.parse('a[]=&a[]=b'); +// { a: ['', 'b'] } +Qs.parse('a[0]=b&a[1]=&a[2]=c'); +// { a: ['b', '', 'c'] } +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key: + +```javascript +Qs.parse('a[100]=b'); +// { a: { '100': 'b' } } +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +Qs.parse('a[1]=b', { arrayLimit: 0 }); +// { a: { '1': 'b' } } +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +Qs.parse('a[]=b', { parseArrays: false }); +// { a: { '0': 'b' } } +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +Qs.parse('a[0]=b&a[b]=c'); +// { a: { '0': 'b', b: 'c' } } +``` + +You can also create arrays of objects: + +```javascript +Qs.parse('a[][b]=c'); +// { a: [{ b: 'c' }] } +``` + +### Stringifying + +```javascript +Qs.stringify(object, [options]); +``` + +When stringifying, **qs** always URI encodes output. Objects are stringified as you would expect: + +```javascript +Qs.stringify({ a: 'b' }); +// 'a=b' +Qs.stringify({ a: { b: 'c' } }); +// 'a%5Bb%5D=c' +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +Qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +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 +Qs.stringify({ a: '' }); +// 'a=' +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +Qs.stringify({ a: null, b: undefined }); +// 'a=' +``` + +The delimiter may be overridden with stringify as well: + +```javascript +Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }); +// 'a=b;c=d' +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +Qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }) +// 'a=b&c=d&e[f]=123&e[g][0]=4' +Qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }) +// 'a=b&e=f' +Qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }) +// 'a[0]=b&a[2]=d' +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +Qs.stringify({ a: null, b: '' }); +// 'a=&b=' +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +Qs.parse('a&b=') +// { a: '', b: '' } +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +Qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +// 'a&b=' +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +Qs.parse('a&b=', { strictNullHandling: true }); +// { a: null, b: '' } + +``` diff --git a/2-2/node_modules/express/node_modules/qs/bower.json b/2-2/node_modules/express/node_modules/qs/bower.json new file mode 100644 index 0000000..ffd0641 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/bower.json @@ -0,0 +1,22 @@ +{ + "name": "qs", + "main": "dist/qs.js", + "version": "3.0.0", + "homepage": "https://github.com/hapijs/qs", + "authors": [ + "Nathan LaFreniere " + ], + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/2-2/node_modules/express/node_modules/qs/lib/index.js b/2-2/node_modules/express/node_modules/qs/lib/index.js new file mode 100644 index 0000000..0e09493 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/lib/index.js @@ -0,0 +1,15 @@ +// Load modules + +var Stringify = require('./stringify'); +var Parse = require('./parse'); + + +// Declare internals + +var internals = {}; + + +module.exports = { + stringify: Stringify, + parse: Parse +}; diff --git a/2-2/node_modules/express/node_modules/qs/lib/parse.js b/2-2/node_modules/express/node_modules/qs/lib/parse.js new file mode 100644 index 0000000..e7c56c5 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/lib/parse.js @@ -0,0 +1,186 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + depth: 5, + arrayLimit: 20, + parameterLimit: 1000, + strictNullHandling: false, + plainObjects: false, + allowPrototypes: false +}; + + +internals.parseValues = function (str, options) { + + var obj = {}; + var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); + + for (var i = 0, il = parts.length; i < il; ++i) { + var part = parts[i]; + var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; + + if (pos === -1) { + obj[Utils.decode(part)] = ''; + + if (options.strictNullHandling) { + obj[Utils.decode(part)] = null; + } + } + else { + var key = Utils.decode(part.slice(0, pos)); + var val = Utils.decode(part.slice(pos + 1)); + + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + obj[key] = val; + } + else { + obj[key] = [].concat(obj[key]).concat(val); + } + } + } + + return obj; +}; + + +internals.parseObject = function (chain, val, options) { + + if (!chain.length) { + return val; + } + + var root = chain.shift(); + + var obj; + if (root === '[]') { + obj = []; + obj = obj.concat(internals.parseObject(chain, val, options)); + } + else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; + var index = parseInt(cleanRoot, 10); + var indexString = '' + index; + if (!isNaN(index) && + root !== cleanRoot && + indexString === cleanRoot && + index >= 0 && + (options.parseArrays && + index <= options.arrayLimit)) { + + obj = []; + obj[index] = internals.parseObject(chain, val, options); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val, options); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, options) { + + if (!key) { + return; + } + + // Transform dot notation to bracket notation + + if (options.allowDots) { + key = key.replace(/\.([^\.\[]+)/g, '[$1]'); + } + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1])) { + + if (!options.allowPrototypes) { + return; + } + } + + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + + ++i; + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { + + if (!options.allowPrototypes) { + continue; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val, options); +}; + + +module.exports = function (str, options) { + + options = options || {}; + options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.allowDots = options.allowDots !== false; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : internals.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : internals.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var newObj = internals.parseKeys(key, tempObj[key], options); + obj = Utils.merge(obj, newObj, options); + } + + return Utils.compact(obj); +}; diff --git a/2-2/node_modules/express/node_modules/qs/lib/stringify.js b/2-2/node_modules/express/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000..7414284 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/lib/stringify.js @@ -0,0 +1,121 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + arrayPrefixGenerators: { + brackets: function (prefix, key) { + + return prefix + '[]'; + }, + indices: function (prefix, key) { + + return prefix + '[' + key + ']'; + }, + repeat: function (prefix, key) { + + return prefix; + } + }, + strictNullHandling: false +}; + + +internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, filter) { + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } + else if (Utils.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + else if (obj === null) { + if (strictNullHandling) { + return Utils.encode(prefix); + } + + obj = ''; + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + return [Utils.encode(prefix) + '=' + Utils.encode(obj)]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys = Array.isArray(filter) ? filter : Object.keys(obj); + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (Array.isArray(obj)) { + values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, filter)); + } + else { + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, filter)); + } + } + + return values; +}; + + +module.exports = function (obj, options) { + + options = options || {}; + var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + var objKeys; + var filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } + else if (Array.isArray(options.filter)) { + objKeys = filter = options.filter; + } + + var keys = []; + + if (typeof obj !== 'object' || + obj === null) { + + 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]; + + if (!objKeys) { + 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, generateArrayPrefix, strictNullHandling, filter)); + } + + return keys.join(delimiter); +}; diff --git a/2-2/node_modules/express/node_modules/qs/lib/utils.js b/2-2/node_modules/express/node_modules/qs/lib/utils.js new file mode 100644 index 0000000..88f3147 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/lib/utils.js @@ -0,0 +1,190 @@ +// Load modules + + +// Declare internals + +var internals = {}; +internals.hexTable = new Array(256); +for (var h = 0; h < 256; ++h) { + internals.hexTable[h] = '%' + ((h < 16 ? '0' : '') + h.toString(16)).toUpperCase(); +} + + +exports.arrayToObject = function (source, options) { + + var obj = options.plainObjects ? Object.create(null) : {}; + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.merge = function (target, source, options) { + + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } + else if (typeof target === 'object') { + target[source] = true; + } + else { + target = [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + target = [target].concat(source); + return target; + } + + if (Array.isArray(target) && + !Array.isArray(source)) { + + target = exports.arrayToObject(target, options); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = value; + } + else { + target[key] = exports.merge(target[key], value, options); + } + } + + return target; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function (str) { + + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + if (typeof str !== 'string') { + str = '' + str; + } + + var out = ''; + for (var i = 0, il = str.length; i < il; ++i) { + var c = str.charCodeAt(i); + + if (c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A)) { // A-Z + + out += str[i]; + continue; + } + + if (c < 0x80) { + out += internals.hexTable[c]; + continue; + } + + if (c < 0x800) { + out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + ++i; + c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF)); + out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function (obj, refs) { + + if (typeof obj !== 'object' || + obj === null) { + + return obj; + } + + refs = refs || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } + + refs.push(obj); + + if (Array.isArray(obj)) { + var compacted = []; + + for (var i = 0, il = obj.length; i < il; ++i) { + if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } + + return compacted; + } + + var keys = Object.keys(obj); + for (i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + obj[key] = exports.compact(obj[key], refs); + } + + return obj; +}; + + +exports.isRegExp = function (obj) { + + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + + +exports.isBuffer = function (obj) { + + if (obj === null || + typeof obj === 'undefined') { + + return false; + } + + return !!(obj.constructor && + obj.constructor.isBuffer && + obj.constructor.isBuffer(obj)); +}; diff --git a/2-2/node_modules/express/node_modules/qs/package.json b/2-2/node_modules/express/node_modules/qs/package.json new file mode 100644 index 0000000..1bae0ed --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/package.json @@ -0,0 +1,57 @@ +{ + "name": "qs", + "version": "4.0.0", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/hapijs/qs", + "main": "lib/index.js", + "dependencies": {}, + "devDependencies": { + "browserify": "^10.2.1", + "code": "1.x.x", + "lab": "5.x.x" + }, + "scripts": { + "test": "lab -a code -t 100 -L", + "test-cov-html": "lab -a code -r html -o coverage.html", + "dist": "browserify --standalone Qs lib/index.js > dist/qs.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/hapijs/qs.git" + }, + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "gitHead": "e573dd08eae6cce30d2202704691a102dfa3782a", + "bugs": { + "url": "https://github.com/hapijs/qs/issues" + }, + "_id": "qs@4.0.0", + "_shasum": "c31d9b74ec27df75e543a86c78728ed8d4623607", + "_from": "qs@4.0.0", + "_npmVersion": "2.12.0", + "_nodeVersion": "0.12.4", + "_npmUser": { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + "dist": { + "shasum": "c31d9b74ec27df75e543a86c78728ed8d4623607", + "tarball": "http://registry.npmjs.org/qs/-/qs-4.0.0.tgz" + }, + "maintainers": [ + { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/qs/-/qs-4.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/qs/test/parse.js b/2-2/node_modules/express/node_modules/qs/test/parse.js new file mode 100644 index 0000000..a19d764 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/test/parse.js @@ -0,0 +1,478 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('parse()', function () { + + it('parses a simple string', function (done) { + + expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' }); + expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' }); + expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } }); + expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } }); + expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } }); + expect(Qs.parse('foo', { strictNullHandling: true })).to.deep.equal({ foo: null }); + expect(Qs.parse('foo' )).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=')).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' }); + expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' }); + expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' }); + expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' }); + expect(Qs.parse('foo2=bar2&baz2=')).to.deep.equal({ foo2: 'bar2', baz2: '' }); + expect(Qs.parse('foo=bar&baz', { strictNullHandling: true })).to.deep.equal({ foo: 'bar', baz: null }); + expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' }); + expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({ + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + done(); + }); + + it('allows disabling dot notation', function (done) { + + expect(Qs.parse('a.b=c')).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse('a.b=c', { allowDots: false })).to.deep.equal({ 'a.b': 'c' }); + done(); + }); + + it('parses a single nested string', function (done) { + + expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } }); + done(); + }); + + it('parses a double nested string', function (done) { + + expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } }); + done(); + }); + + it('defaults to a depth of 5', function (done) { + + expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }); + done(); + }); + + it('only parses one level when depth = 1', function (done) { + + expect(Qs.parse('a[b][c]=d', { depth: 1 })).to.deep.equal({ a: { b: { '[c]': 'd' } } }); + expect(Qs.parse('a[b][c][d]=e', { depth: 1 })).to.deep.equal({ a: { b: { '[c][d]': 'e' } } }); + done(); + }); + + it('parses a simple array', function (done) { + + expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses an explicit array', function (done) { + + expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] }); + expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + done(); + }); + + it('parses a mix of simple and explicit arrays', function (done) { + + expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses a nested array', function (done) { + + expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } }); + expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } }); + done(); + }); + + it('allows to specify array indices', function (done) { + + expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] }); + done(); + }); + + it('limits specific array indices to 20', function (done) { + + expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] }); + expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } }); + done(); + }); + + it('supports keys that begin with a number', function (done) { + + expect(Qs.parse('a[12b]=c')).to.deep.equal({ a: { '12b': 'c' } }); + done(); + }); + + it('supports encoded = signs', function (done) { + + expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' }); + done(); + }); + + it('is ok with url encoded strings', function (done) { + + expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } }); + expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } }); + done(); + }); + + it('allows brackets in the value', function (done) { + + expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' }); + expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' }); + done(); + }); + + it('allows empty values', function (done) { + + expect(Qs.parse('')).to.deep.equal({}); + expect(Qs.parse(null)).to.deep.equal({}); + expect(Qs.parse(undefined)).to.deep.equal({}); + done(); + }); + + it('transforms arrays to objects', function (done) { + + expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + expect(Qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c')).to.deep.equal({ a: { '0': 'b', t: 'u', c: true } }); + expect(Qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y')).to.deep.equal({ a: { '0': 'b', '1': 'c', x: 'y' } }); + done(); + }); + + it('transforms arrays to objects (dot notation)', function (done) { + + expect(Qs.parse('foo[0].baz=bar&fool.bad=baz')).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz=bar&fool.bad.boo=baz')).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + expect(Qs.parse('foo[0][0].baz=bar&fool.bad=baz')).to.deep.equal({ foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].bar=2')).to.deep.equal({ foo: [{ baz: ['15'], bar: '2' }] }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2')).to.deep.equal({ foo: [{ baz: ['15', '16'], bar: '2' }] }); + expect(Qs.parse('foo.bad=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo.bad=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + done(); + }); + + it('can add keys to objects', function (done) { + + expect(Qs.parse('a[b]=c&a=d')).to.deep.equal({ a: { b: 'c', d: true } }); + done(); + }); + + it('correctly prunes undefined values when converting an array to an object', function (done) { + + expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } }); + done(); + }); + + it('supports malformed uri characters', function (done) { + + expect(Qs.parse('{%:%}', { strictNullHandling: true })).to.deep.equal({ '{%:%}': null }); + expect(Qs.parse('{%:%}=')).to.deep.equal({ '{%:%}': '' }); + expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' }); + done(); + }); + + it('doesn\'t produce empty keys', function (done) { + + expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' }); + done(); + }); + + it('cannot access Object prototype', function (done) { + + Qs.parse('constructor[prototype][bad]=bad'); + Qs.parse('bad[constructor][prototype][bad]=bad'); + expect(typeof Object.prototype.bad).to.equal('undefined'); + done(); + }); + + it('parses arrays of objects', function (done) { + + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + done(); + }); + + it('allows for empty strings in arrays', function (done) { + + expect(Qs.parse('a[]=b&a[]=&a[]=c')).to.deep.equal({ a: ['b', '', 'c'] }); + expect(Qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true })).to.deep.equal({ a: ['b', null, 'c', ''] }); + expect(Qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true })).to.deep.equal({ a: ['b', '', 'c', null] }); + expect(Qs.parse('a[]=&a[]=b&a[]=c')).to.deep.equal({ a: ['', 'b', 'c'] }); + done(); + }); + + it('compacts sparse arrays', function (done) { + + expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] }); + done(); + }); + + it('parses semi-parsed strings', function (done) { + + expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } }); + done(); + }); + + it('parses buffers correctly', function (done) { + + var b = new Buffer('test'); + expect(Qs.parse({ a: b })).to.deep.equal({ a: b }); + done(); + }); + + it('continues parsing when no parent is found', function (done) { + + expect(Qs.parse('[]=&a=b')).to.deep.equal({ '0': '', a: 'b' }); + expect(Qs.parse('[]&a=b', { strictNullHandling: true })).to.deep.equal({ '0': null, a: 'b' }); + expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' }); + done(); + }); + + it('does not error when parsing a very long array', function (done) { + + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str += '&' + str; + } + + expect(function () { + + Qs.parse(str); + }).to.not.throw(); + + done(); + }); + + it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) { + + Object.prototype.crash = ''; + Array.prototype.crash = ''; + expect(Qs.parse.bind(null, 'a=b')).to.not.throw(); + expect(Qs.parse('a=b')).to.deep.equal({ a: 'b' }); + expect(Qs.parse.bind(null, 'a[][b]=c')).to.not.throw(); + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + done(); + }); + + it('parses a string with an alternative string delimiter', function (done) { + + expect(Qs.parse('a=b;c=d', { delimiter: ';' })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('parses a string with an alternative RegExp delimiter', function (done) { + + expect(Qs.parse('a=b; c=d', { delimiter: /[;,] */ })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not use non-splittable objects as delimiters', function (done) { + + expect(Qs.parse('a=b&c=d', { delimiter: true })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('allows overriding parameter limit', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: 1 })).to.deep.equal({ a: 'b' }); + done(); + }); + + it('allows setting the parameter limit to Infinity', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: Infinity })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + 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(); + }); + + it('allows disabling array parsing', function (done) { + + expect(Qs.parse('a[0]=b&a[1]=c', { parseArrays: false })).to.deep.equal({ a: { '0': 'b', '1': 'c' } }); + done(); + }); + + it('parses an object', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object in dot notation', function (done) { + + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object and not child values', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': { 'test': 3 } }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': { 'test': 3 } }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('does not blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = Qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + expect(result).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not crash when parsing circular references', function (done) { + + var a = {}; + a.b = a; + + var parsed; + + expect(function () { + + parsed = Qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }).to.not.throw(); + + 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(); + }); + + it('parses plain objects correctly', function (done) { + + var a = Object.create(null); + a.b = 'c'; + + expect(Qs.parse(a)).to.deep.equal({ b: 'c' }); + var result = Qs.parse({ a: a }); + expect(result).to.contain('a'); + expect(result.a).to.deep.equal(a); + done(); + }); + + it('parses dates correctly', function (done) { + + var now = new Date(); + expect(Qs.parse({ a: now })).to.deep.equal({ a: now }); + done(); + }); + + it('parses regular expressions correctly', function (done) { + + var re = /^test$/; + expect(Qs.parse({ a: re })).to.deep.equal({ a: re }); + done(); + }); + + it('can allow overwriting prototype properties', function (done) { + + expect(Qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true })).to.deep.equal({ a: { hasOwnProperty: 'b' } }, { prototype: false }); + expect(Qs.parse('hasOwnProperty=b', { allowPrototypes: true })).to.deep.equal({ hasOwnProperty: 'b' }, { prototype: false }); + done(); + }); + + it('can return plain objects', function (done) { + + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + expect(Qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true })).to.deep.equal(expected); + expect(Qs.parse(null, { plainObjects: true })).to.deep.equal(Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a['0'] = 'b'; + expectedArray.a.c = 'd'; + expect(Qs.parse('a[]=b&a[c]=d', { plainObjects: true })).to.deep.equal(expectedArray); + done(); + }); +}); diff --git a/2-2/node_modules/express/node_modules/qs/test/stringify.js b/2-2/node_modules/express/node_modules/qs/test/stringify.js new file mode 100644 index 0000000..48b7803 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/test/stringify.js @@ -0,0 +1,259 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('stringify()', function () { + + it('stringifies a querystring object', function (done) { + + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 })).to.equal('a=1'); + expect(Qs.stringify({ a: 1, b: 2 })).to.equal('a=1&b=2'); + expect(Qs.stringify({ a: 'A_Z' })).to.equal('a=A_Z'); + expect(Qs.stringify({ a: '€' })).to.equal('a=%E2%82%AC'); + expect(Qs.stringify({ a: '' })).to.equal('a=%EE%80%80'); + expect(Qs.stringify({ a: 'א' })).to.equal('a=%D7%90'); + expect(Qs.stringify({ a: '𐐷' })).to.equal('a=%F0%90%90%B7'); + done(); + }); + + it('stringifies a nested object', function (done) { + + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + expect(Qs.stringify({ a: { b: { c: { d: 'e' } } } })).to.equal('a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + done(); + }); + + it('stringifies an array value', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d'); + done(); + }); + + it('omits array indices when asked', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false })).to.equal('a=b&a=c&a=d'); + done(); + }); + + it('stringifies a nested array value', function (done) { + + expect(Qs.stringify({ a: { b: ['c', 'd'] } })).to.equal('a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + done(); + }); + + it('stringifies an object inside an array', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] })).to.equal('a%5B0%5D%5Bb%5D=c'); + expect(Qs.stringify({ a: [{ b: { c: [1] } }] })).to.equal('a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1'); + done(); + }); + + it('does not omit object keys when indices = false', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] }, { indices: false })).to.equal('a%5Bb%5D=c'); + 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'); + done(); + }); + + it('stringifies an empty value', function (done) { + + expect(Qs.stringify({ a: '' })).to.equal('a='); + expect(Qs.stringify({ a: null }, { strictNullHandling: true })).to.equal('a'); + + expect(Qs.stringify({ a: '', b: '' })).to.equal('a=&b='); + expect(Qs.stringify({ a: null, b: '' }, { strictNullHandling: true })).to.equal('a&b='); + + expect(Qs.stringify({ a: { b: '' } })).to.equal('a%5Bb%5D='); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: true })).to.equal('a%5Bb%5D'); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: false })).to.equal('a%5Bb%5D='); + + done(); + }); + + it('stringifies an empty object', function (done) { + + var obj = Object.create(null); + obj.a = 'b'; + expect(Qs.stringify(obj)).to.equal('a=b'); + done(); + }); + + it('returns an empty string for invalid input', function (done) { + + expect(Qs.stringify(undefined)).to.equal(''); + expect(Qs.stringify(false)).to.equal(''); + expect(Qs.stringify(null)).to.equal(''); + expect(Qs.stringify('')).to.equal(''); + done(); + }); + + it('stringifies an object with an empty object as a child', function (done) { + + var obj = { + a: Object.create(null) + }; + + obj.a.b = 'c'; + expect(Qs.stringify(obj)).to.equal('a%5Bb%5D=c'); + done(); + }); + + it('drops keys with a value of undefined', function (done) { + + expect(Qs.stringify({ a: undefined })).to.equal(''); + + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true })).to.equal('a%5Bc%5D'); + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false })).to.equal('a%5Bc%5D='); + expect(Qs.stringify({ a: { b: undefined, c: '' } })).to.equal('a%5Bc%5D='); + done(); + }); + + it('url encodes values', function (done) { + + expect(Qs.stringify({ a: 'b c' })).to.equal('a=b%20c'); + done(); + }); + + it('stringifies a date', function (done) { + + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + expect(Qs.stringify({ a: now })).to.equal(str); + done(); + }); + + it('stringifies the weird object from qs', function (done) { + + expect(Qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' })).to.equal('my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + done(); + }); + + it('skips properties that are part of the object prototype', function (done) { + + Object.prototype.crash = 'test'; + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + delete Object.prototype.crash; + done(); + }); + + it('stringifies boolean values', function (done) { + + expect(Qs.stringify({ a: true })).to.equal('a=true'); + expect(Qs.stringify({ a: { b: true } })).to.equal('a%5Bb%5D=true'); + expect(Qs.stringify({ b: false })).to.equal('b=false'); + expect(Qs.stringify({ b: { c: false } })).to.equal('b%5Bc%5D=false'); + done(); + }); + + it('stringifies buffer values', function (done) { + + expect(Qs.stringify({ a: new Buffer('test') })).to.equal('a=test'); + expect(Qs.stringify({ a: { b: new Buffer('test') } })).to.equal('a%5Bb%5D=test'); + done(); + }); + + it('stringifies an object using an alternative delimiter', function (done) { + + expect(Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' })).to.equal('a=b;c=d'); + done(); + }); + + it('doesn\'t blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + expect(Qs.stringify({ a: 'b', c: 'd' })).to.equal('a=b&c=d'); + global.Buffer = tempBuffer; + done(); + }); + + it('selects properties when filter=array', function (done) { + + expect(Qs.stringify({ a: 'b' }, { filter: ['a'] })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 }, { filter: [] })).to.equal(''); + expect(Qs.stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] })).to.equal('a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3'); + done(); + + }); + + it('supports custom representations when filter=function', function (done) { + + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + + calls++; + if (calls === 1) { + expect(prefix).to.be.empty(); + expect(value).to.equal(obj); + } + else if (prefix === 'c') { + return; + } + else if (value instanceof Date) { + expect(prefix).to.equal('e[f]'); + return value.getTime(); + } + return value; + }; + + expect(Qs.stringify(obj, { filter: filterFunc })).to.equal('a=b&e%5Bf%5D=1257894000000'); + expect(calls).to.equal(5); + done(); + + }); +}); diff --git a/2-2/node_modules/express/node_modules/qs/test/utils.js b/2-2/node_modules/express/node_modules/qs/test/utils.js new file mode 100644 index 0000000..a9a6b52 --- /dev/null +++ b/2-2/node_modules/express/node_modules/qs/test/utils.js @@ -0,0 +1,28 @@ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Utils = require('../lib/utils'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('merge()', function () { + + it('can merge two objects with the same key', function (done) { + + expect(Utils.merge({ a: 'b' }, { a: 'c' })).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); +}); diff --git a/2-2/node_modules/express/node_modules/range-parser/HISTORY.md b/2-2/node_modules/express/node_modules/range-parser/HISTORY.md new file mode 100644 index 0000000..f640bea --- /dev/null +++ b/2-2/node_modules/express/node_modules/range-parser/HISTORY.md @@ -0,0 +1,40 @@ +unreleased +========== + + * perf: enable strict mode + +1.0.2 / 2014-09-08 +================== + + * Support Node.js 0.6 + +1.0.1 / 2014-09-07 +================== + + * Move repository to jshttp + +1.0.0 / 2013-12-11 +================== + + * Add repository to package.json + * Add MIT license + +0.0.4 / 2012-06-17 +================== + + * Change ret -1 for unsatisfiable and -2 when invalid + +0.0.3 / 2012-06-17 +================== + + * Fix last-byte-pos default to len - 1 + +0.0.2 / 2012-06-14 +================== + + * Add `.type` + +0.0.1 / 2012-06-11 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/range-parser/LICENSE b/2-2/node_modules/express/node_modules/range-parser/LICENSE new file mode 100644 index 0000000..a491841 --- /dev/null +++ b/2-2/node_modules/express/node_modules/range-parser/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/range-parser/README.md b/2-2/node_modules/express/node_modules/range-parser/README.md new file mode 100644 index 0000000..32f58f6 --- /dev/null +++ b/2-2/node_modules/express/node_modules/range-parser/README.md @@ -0,0 +1,57 @@ +# range-parser + +[![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] + +Range header field parser. + +## Installation + +``` +$ npm install range-parser +``` + +## API + +```js +var parseRange = require('range-parser') +``` + +### parseRange(size, header) + +Parse the given `header` string where `size` is the maximum size of the resource. +An array of ranges will be returned or negative numbers indicating an error parsing. + + * `-2` signals a malformed header string + * `-1` signals an invalid range + +```js +// parse header from request +var range = parseRange(req.headers.range) + +// the type of the range +if (range.type === 'bytes') { + // the ranges + range.forEach(function (r) { + // do something with r.start and r.end + }) +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/range-parser.svg +[npm-url]: https://npmjs.org/package/range-parser +[node-version-image]: https://img.shields.io/node/v/range-parser.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/range-parser.svg +[travis-url]: https://travis-ci.org/jshttp/range-parser +[coveralls-image]: https://img.shields.io/coveralls/jshttp/range-parser.svg +[coveralls-url]: https://coveralls.io/r/jshttp/range-parser +[downloads-image]: https://img.shields.io/npm/dm/range-parser.svg +[downloads-url]: https://npmjs.org/package/range-parser diff --git a/2-2/node_modules/express/node_modules/range-parser/index.js b/2-2/node_modules/express/node_modules/range-parser/index.js new file mode 100644 index 0000000..814e533 --- /dev/null +++ b/2-2/node_modules/express/node_modules/range-parser/index.js @@ -0,0 +1,63 @@ +/*! + * range-parser + * Copyright(c) 2012-2014 TJ Holowaychuk + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = rangeParser; + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @return {Array} + * @public + */ + +function rangeParser(size, str) { + var valid = true; + var i = str.indexOf('='); + + if (-1 == i) return -2; + + var arr = str.slice(i + 1).split(',').map(function(range){ + var range = range.split('-') + , start = parseInt(range[0], 10) + , end = parseInt(range[1], 10); + + // -nnn + if (isNaN(start)) { + start = size - end; + end = size - 1; + // nnn- + } else if (isNaN(end)) { + end = size - 1; + } + + // limit last-byte-pos to current length + if (end > size - 1) end = size - 1; + + // invalid + if (isNaN(start) + || isNaN(end) + || start > end + || start < 0) valid = false; + + return { + start: start, + end: end + }; + }); + + arr.type = str.slice(0, i); + + return valid ? arr : -1; +} diff --git a/2-2/node_modules/express/node_modules/range-parser/package.json b/2-2/node_modules/express/node_modules/range-parser/package.json new file mode 100644 index 0000000..5d4411b --- /dev/null +++ b/2-2/node_modules/express/node_modules/range-parser/package.json @@ -0,0 +1,75 @@ +{ + "name": "range-parser", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "description": "Range header field string parser", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "range", + "parser", + "http" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/range-parser.git" + }, + "devDependencies": { + "istanbul": "0.4.0", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "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" + }, + "gitHead": "18e46a3de74afff9f4e22717f11ddd6e9aa6d845", + "bugs": { + "url": "https://github.com/jshttp/range-parser/issues" + }, + "homepage": "https://github.com/jshttp/range-parser", + "_id": "range-parser@1.0.3", + "_shasum": "6872823535c692e2c2a0103826afd82c2e0ff175", + "_from": "range-parser@>=1.0.3 <1.1.0", + "_npmVersion": "1.4.28", + "_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": "6872823535c692e2c2a0103826afd82c2e0ff175", + "tarball": "http://registry.npmjs.org/range-parser/-/range-parser-1.0.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/send/HISTORY.md b/2-2/node_modules/express/node_modules/send/HISTORY.md new file mode 100644 index 0000000..d3dca9c --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/HISTORY.md @@ -0,0 +1,310 @@ +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * 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: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.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/2-2/node_modules/express/node_modules/send/LICENSE b/2-2/node_modules/express/node_modules/send/LICENSE new file mode 100644 index 0000000..e4d595b --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +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: + +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/2-2/node_modules/express/node_modules/send/README.md b/2-2/node_modules/express/node_modules/send/README.md new file mode 100644 index 0000000..3586060 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/README.md @@ -0,0 +1,195 @@ +# send + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Send is a library for streaming files from the file system as a http response +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. + +Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). + +## 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"). + + - `'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. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### 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 example + +```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 +[npm-url]: https://npmjs.org/package/send +[travis-image]: https://img.shields.io/travis/pillarjs/send/master.svg?label=linux +[travis-url]: https://travis-ci.org/pillarjs/send +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/send/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/send +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/send/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master +[downloads-image]: https://img.shields.io/npm/dm/send.svg +[downloads-url]: https://npmjs.org/package/send +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/2-2/node_modules/express/node_modules/send/index.js b/2-2/node_modules/express/node_modules/send/index.js new file mode 100644 index 0000000..3510989 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/index.js @@ -0,0 +1,820 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('send') +var deprecate = require('depd')('send') +var destroy = require('destroy') +var escapeHtml = require('escape-html') + , parseRange = require('range-parser') + , Stream = require('stream') + , mime = require('mime') + , fresh = require('fresh') + , path = require('path') + , fs = require('fs') + , normalize = path.normalize + , join = path.join +var etag = require('etag') +var EventEmitter = require('events').EventEmitter; +var ms = require('ms'); +var onFinished = require('on-finished') +var statuses = require('statuses') + +/** + * Variables. + */ +var extname = path.extname +var maxMaxAge = 60 * 60 * 24 * 365 * 1000; // 1 year +var resolve = path.resolve +var sep = path.sep +var toString = Object.prototype.toString +var upPathRegexp = /(?:^|[\\\/])\.\.(?:[\\\/]|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = send +module.exports.mime = mime + +/** + * Shim EventEmitter.listenerCount for node.js < 0.10 + */ + +/* istanbul ignore next */ +var listenerCount = EventEmitter.listenerCount + || function(emitter, type){ return emitter.listeners(type).length; }; + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ + +function send(req, path, options) { + return new SendStream(req, path, options); +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ + +function SendStream(req, path, options) { + var opts = options || {} + + this.options = opts + this.path = path + this.req = req + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true + + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' + + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + this._hidden = Boolean(opts.hidden) + + if (opts.hidden !== undefined) { + deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') + } + + // legacy support + if (opts.dotfiles === undefined) { + this._dotfiles = undefined + } + + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] + + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] + + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true + + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), maxMaxAge) + : 0 + + this._root = opts.root + ? resolve(opts.root) + : null + + if (!this._root && opts.from) { + this.from(opts.from) + } +} + +/** + * Inherits from `Stream.prototype`. + */ + +SendStream.prototype.__proto__ = Stream.prototype; + +/** + * Enable or disable etag generation. + * + * @param {Boolean} val + * @return {SendStream} + * @api public + */ + +SendStream.prototype.etag = deprecate.function(function etag(val) { + val = Boolean(val); + debug('etag %s', val); + this._etag = val; + return this; +}, 'send.etag: pass etag as option'); + +/** + * Enable or disable "hidden" (dot) files. + * + * @param {Boolean} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.hidden = deprecate.function(function hidden(val) { + val = Boolean(val); + debug('hidden %s', val); + this._hidden = val; + this._dotfiles = undefined + return this; +}, 'send.hidden: use dotfiles option'); + +/** + * Set index `paths`, set to a falsy + * value to disable index support. + * + * @param {String|Boolean|Array} paths + * @return {SendStream} + * @api public + */ + +SendStream.prototype.index = deprecate.function(function index(paths) { + var index = !paths ? [] : normalizeList(paths, 'paths argument'); + debug('index %o', paths); + this._index = index; + return this; +}, 'send.index: pass index as option'); + +/** + * Set root `path`. + * + * @param {String} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.root = function(path){ + path = String(path); + this._root = resolve(path) + return this; +}; + +SendStream.prototype.from = deprecate.function(SendStream.prototype.root, + 'send.from: pass root as option'); + +SendStream.prototype.root = deprecate.function(SendStream.prototype.root, + 'send.root: pass root as option'); + +/** + * Set max-age to `maxAge`. + * + * @param {Number} maxAge + * @return {SendStream} + * @api public + */ + +SendStream.prototype.maxage = deprecate.function(function maxage(maxAge) { + maxAge = typeof maxAge === 'string' + ? ms(maxAge) + : Number(maxAge); + if (isNaN(maxAge)) maxAge = 0; + if (Infinity == maxAge) maxAge = 60 * 60 * 24 * 365 * 1000; + debug('max-age %d', maxAge); + this._maxage = maxAge; + return this; +}, 'send.maxage: pass maxAge as option'); + +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [error] + * @private + */ + +SendStream.prototype.error = function error(status, error) { + // emit if listeners instead of responding + if (listenerCount(this, 'error') !== 0) { + return this.emit('error', createError(error, status, { + expose: false + })) + } + + var res = this.res + var msg = statuses[status] + + // wipe all existing headers + res._headers = null + + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/plain; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(msg) +} + +/** + * Check if the pathname ends with "/". + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.hasTrailingSlash = function(){ + return '/' == this.path[this.path.length - 1]; +}; + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function(){ + return this.req.headers['if-none-match'] + || this.req.headers['if-modified-since']; +}; + +/** + * Strip content-* header fields. + * + * @private + */ + +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields() { + var res = this.res + var headers = Object.keys(res._headers || {}) + + for (var i = 0; i < headers.length; i++) { + var header = headers[i] + if (header.substr(0, 8) === 'content-' && header !== 'content-location') { + res.removeHeader(header) + } + } +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function(){ + var res = this.res; + debug('not modified'); + this.removeContentHeaderFields(); + res.statusCode = 304; + res.end(); +}; + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent(){ + var err = new Error('Can\'t set headers after they are sent.'); + debug('headers already sent'); + this.error(500, err); +}; + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function(){ + var res = this.res; + return (res.statusCode >= 200 && res.statusCode < 300) || 304 == res.statusCode; +}; + +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ + +SendStream.prototype.onStatError = function onStatError(error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function(){ + return fresh(this.req.headers, this.res._headers); +}; + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh(){ + var ifRange = this.req.headers['if-range']; + + if (!ifRange) return true; + + return ~ifRange.indexOf('"') + ? ~ifRange.indexOf(this.res._headers['etag']) + : Date.parse(this.res._headers['last-modified']) <= Date.parse(ifRange); +}; + +/** + * Redirect to path. + * + * @param {string} path + * @private + */ + +SendStream.prototype.redirect = function redirect(path) { + if (listenerCount(this, 'directory') !== 0) { + this.emit('directory') + return + } + + if (this.hasTrailingSlash()) { + this.error(403) + return + } + + var loc = path + '/' + var msg = 'Redirecting to ' + escapeHtml(loc) + '\n' + var res = this.res + + // redirect + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(msg) +} + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function(res){ + var self = this + , args = arguments + , root = this._root; + + // references + this.res = res; + + // decode the path + var path = decode(this.path) + if (path === -1) return this.error(400) + + // null byte(s) + if (~path.indexOf('\0')) return this.error(400); + + var parts + if (root !== null) { + // malicious path + 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 { + // ".." is malicious without "root" + if (upPathRegexp.test(path)) { + debug('malicious path "%s"', path) + return this.error(403) + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + // dotfile handling + if (containsDotFile(parts)) { + var access = this._dotfiles + + // legacy support + if (access === undefined) { + access = parts[parts.length - 1][0] === '.' + ? (this._hidden ? 'allow' : 'ignore') + : 'allow' + } + + debug('%s dotfile "%s"', access, path) + switch (access) { + case 'allow': + break + case 'deny': + return this.error(403) + case 'ignore': + default: + return this.error(404) + } + } + + // index file support + if (this._index.length && this.path[this.path.length - 1] === '/') { + this.sendIndex(path); + return res; + } + + this.sendFile(path); + return res; +}; + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function(path, stat){ + var len = stat.size; + var options = this.options + var opts = {} + var res = this.res; + var req = this.req; + var ranges = req.headers.range; + var offset = options.start || 0; + + if (res._header) { + // impossible to send now + return this.headersAlreadySent(); + } + + debug('pipe "%s"', path) + + // set header fields + this.setHeader(path, stat); + + // set content-type + this.type(path); + + // conditional GET support + if (this.isConditionalGET() + && this.isCachable() + && this.isFresh()) { + return this.notModified(); + } + + // adjust len to start/end options + len = Math.max(0, len - offset); + if (options.end !== undefined) { + var bytes = options.end - offset + 1; + if (len > bytes) len = bytes; + } + + // Range support + if (ranges) { + ranges = parseRange(len, ranges); + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale'); + ranges = -2; + } + + // unsatisfiable + if (-1 == ranges) { + debug('range unsatisfiable'); + res.setHeader('Content-Range', 'bytes */' + stat.size); + return this.error(416); + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (-2 != ranges && ranges.length === 1) { + debug('range %j', ranges); + + // Content-Range + res.statusCode = 206; + res.setHeader('Content-Range', 'bytes ' + + ranges[0].start + + '-' + + ranges[0].end + + '/' + + len); + + 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, opts) +}; + +/** + * Transfer file for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendFile = function sendFile(path) { + var i = 0 + var self = this + + debug('stat "%s"', path); + fs.stat(path, function onstat(err, stat) { + if (err && err.code === 'ENOENT' + && !extname(path) + && path[path.length - 1] !== sep) { + // not found, check extensions + return next(err) + } + if (err) return self.onStatError(err) + if (stat.isDirectory()) return self.redirect(self.path) + self.emit('file', path, stat) + self.send(path, stat) + }) + + function next(err) { + if (self._extensions.length <= i) { + return err + ? self.onStatError(err) + : self.error(404) + } + + var p = path + '.' + self._extensions[i++] + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } +} + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex(path){ + var i = -1; + var self = this; + + function next(err){ + if (++i >= self._index.length) { + if (err) return self.onStatError(err); + return self.error(404); + } + + var p = join(path, self._index[i]); + + debug('stat "%s"', p); + fs.stat(p, function(err, stat){ + if (err) return next(err); + if (stat.isDirectory()) return next(); + self.emit('file', p, stat); + self.send(p, stat); + }); + } + + next(); +}; + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function(path, options){ + // TODO: this is all lame, refactor meeee + var finished = false; + var self = this; + var res = this.res; + var req = this.req; + + // pipe + var stream = fs.createReadStream(path, options); + this.emit('stream', stream); + stream.pipe(res); + + // response finished, done with the fd + onFinished(res, function onfinished(){ + finished = true; + destroy(stream); + }); + + // error handling code-smell + stream.on('error', function onerror(err){ + // request already finished + if (finished) return; + + // clean up stream + finished = true; + destroy(stream); + + // error + self.onStatError(err); + }); + + // end + stream.on('end', function onend(){ + self.emit('end'); + }); +}; + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function(path){ + var res = this.res; + if (res.getHeader('Content-Type')) return; + var type = mime.lookup(path); + var charset = mime.charsets.lookup(type); + debug('content-type %s', type); + res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')); +}; + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader(path, stat){ + var res = this.res; + + this.emit('headers', res, path, stat); + + if (!res.getHeader('Accept-Ranges')) res.setHeader('Accept-Ranges', 'bytes'); + if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + Math.floor(this._maxage / 1000)); + + if (this._lastModified && !res.getHeader('Last-Modified')) { + var modified = stat.mtime.toUTCString() + debug('modified %s', modified) + res.setHeader('Last-Modified', modified) + } + + if (this._etag && !res.getHeader('ETag')) { + var val = etag(stat) + debug('etag %s', val) + res.setHeader('ETag', val) + } +}; + +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ + +function containsDotFile(parts) { + for (var i = 0; i < parts.length; i++) { + if (parts[i][0] === '.') { + return true + } + } + + return false +} + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +function decode(path) { + try { + return decodeURIComponent(path) + } catch (err) { + return -1 + } +} + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +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/2-2/node_modules/express/node_modules/send/node_modules/.bin/mime b/2-2/node_modules/express/node_modules/send/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/2-2/node_modules/express/node_modules/send/node_modules/destroy/LICENSE b/2-2/node_modules/express/node_modules/send/node_modules/destroy/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/destroy/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/send/node_modules/destroy/README.md b/2-2/node_modules/express/node_modules/send/node_modules/destroy/README.md new file mode 100644 index 0000000..6474bc3 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/destroy/README.md @@ -0,0 +1,60 @@ +# Destroy + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Destroy a stream. + +This module is meant to ensure a stream gets destroyed, handling different APIs +and Node.js bugs. + +## API + +```js +var destroy = require('destroy') +``` + +### destroy(stream) + +Destroy the given stream. In most cases, this is identical to a simple +`stream.destroy()` call. The rules are as follows for a given stream: + + 1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()` + and add a listener to the `open` event to call `stream.close()` if it is + fired. This is for a Node.js bug that will leak a file descriptor if + `.destroy()` is called before `open`. + 2. If the `stream` is not an instance of `Stream`, then nothing happens. + 3. If the `stream` has a `.destroy()` method, then call it. + +The function returns the `stream` passed in as the argument. + +## Example + +```js +var destroy = require('destroy') + +var fs = require('fs') +var stream = fs.createReadStream('package.json') + +// ... and later +destroy(stream) +``` + +[npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square +[npm-url]: https://npmjs.org/package/destroy +[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square +[github-url]: https://github.com/stream-utils/destroy/tags +[travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square +[travis-url]: https://travis-ci.org/stream-utils/destroy +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master +[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/destroy +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/2-2/node_modules/express/node_modules/send/node_modules/destroy/index.js b/2-2/node_modules/express/node_modules/send/node_modules/destroy/index.js new file mode 100644 index 0000000..6da2d26 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/destroy/index.js @@ -0,0 +1,75 @@ +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var ReadStream = require('fs').ReadStream +var Stream = require('stream') + +/** + * Module exports. + * @public + */ + +module.exports = destroy + +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ + +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) + } + + if (!(stream instanceof Stream)) { + return stream + } + + if (typeof stream.destroy === 'function') { + stream.destroy() + } + + return stream +} + +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ + +function destroyReadStream(stream) { + stream.destroy() + + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } + + return stream +} + +/** + * On open handler to close stream. + * @private + */ + +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } +} diff --git a/2-2/node_modules/express/node_modules/send/node_modules/destroy/package.json b/2-2/node_modules/express/node_modules/send/node_modules/destroy/package.json new file mode 100644 index 0000000..f7f3f16 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/destroy/package.json @@ -0,0 +1,72 @@ +{ + "name": "destroy", + "description": "destroy a stream if possible", + "version": "1.0.4", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/destroy.git" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4" + }, + "scripts": { + "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" + }, + "files": [ + "index.js", + "LICENSE" + ], + "keywords": [ + "stream", + "streams", + "destroy", + "cleanup", + "leak", + "fd" + ], + "gitHead": "86edea01456f5fa1027f6a47250c34c713cbcc3b", + "bugs": { + "url": "https://github.com/stream-utils/destroy/issues" + }, + "homepage": "https://github.com/stream-utils/destroy", + "_id": "destroy@1.0.4", + "_shasum": "978857442c44749e4206613e37946205826abd80", + "_from": "destroy@>=1.0.4 <1.1.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" + } + ], + "dist": { + "shasum": "978857442c44749e4206613e37946205826abd80", + "tarball": "http://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md new file mode 100644 index 0000000..4c7087d --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md @@ -0,0 +1,76 @@ +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/send/node_modules/http-errors/README.md b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/README.md new file mode 100644 index 0000000..520271e --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/README.md @@ -0,0 +1,63 @@ +# http-errors + +[![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] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Example + +```js +var createError = require('http-errors'); + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')); + next(); +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +### Error Properties + +- `message` +- `status` and `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + +```js +var err = createError(404, 'This video does not exist!'); +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### new createError\[code || name\](\[msg]\)) + +```js +var err = new createError.NotFound(); +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/http-errors.svg?style=flat +[npm-url]: https://npmjs.org/package/http-errors +[node-version-image]: https://img.shields.io/node/v/http-errors.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/http-errors.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/http-errors +[coveralls-image]: https://img.shields.io/coveralls/jshttp/http-errors.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors +[downloads-image]: https://img.shields.io/npm/dm/http-errors.svg?style=flat +[downloads-url]: https://npmjs.org/package/http-errors diff --git a/2-2/node_modules/express/node_modules/send/node_modules/http-errors/index.js b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/index.js new file mode 100644 index 0000000..d84b114 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/index.js @@ -0,0 +1,120 @@ + +var statuses = require('statuses'); +var inherits = require('inherits'); + +function toIdentifier(str) { + return str.split(' ').map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }).join('').replace(/[^ _0-9a-z]/gi, '') +} + +exports = module.exports = function httpError() { + // so much arity going on ~_~ + var err; + var msg; + var status = 500; + var props = {}; + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (arg instanceof Error) { + err = arg; + status = err.status || err.statusCode || status; + continue; + } + switch (typeof arg) { + case 'string': + msg = arg; + break; + case 'number': + status = arg; + break; + case 'object': + props = arg; + break; + } + } + + if (typeof status !== 'number' || !statuses[status]) { + status = 500 + } + + // constructor + var HttpError = exports[status] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, httpError) + } + + if (!HttpError || !(err instanceof HttpError)) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err; +}; + +// create generic error objects +var codes = statuses.codes.filter(function (num) { + return num >= 400; +}); + +codes.forEach(function (code) { + var name = toIdentifier(statuses[code]) + var className = name.match(/Error$/) ? name : name + 'Error' + + if (code >= 500) { + var ServerError = function ServerError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ServerError) + self.__proto__ = ServerError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ServerError, Error); + ServerError.prototype.status = + ServerError.prototype.statusCode = code; + ServerError.prototype.expose = false; + exports[code] = + exports[name] = ServerError + return; + } + + var ClientError = function ClientError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ClientError) + self.__proto__ = ClientError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ClientError, Error); + ClientError.prototype.status = + ClientError.prototype.statusCode = code; + ClientError.prototype.expose = true; + exports[code] = + exports[name] = ClientError + return; +}); + +// backwards-compatibility +exports["I'mateapot"] = exports.ImATeapot diff --git a/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +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/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +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/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +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/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json new file mode 100644 index 0000000..93d5078 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json @@ -0,0 +1,50 @@ +{ + "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.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "_id": "inherits@2.0.1", + "dist": { + "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/inherits#readme" +} diff --git a/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +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/2-2/node_modules/express/node_modules/send/node_modules/http-errors/package.json b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/package.json new file mode 100644 index 0000000..41f845d --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/http-errors/package.json @@ -0,0 +1,85 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "1.3.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Alan Plum", + "email": "me@pluma.io" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/http-errors.git" + }, + "dependencies": { + "inherits": "~2.0.1", + "statuses": "1" + }, + "devDependencies": { + "istanbul": "0", + "mocha": "1" + }, + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ], + "gitHead": "89a8502b40d5dd42da2908f265275e2eeb8d0699", + "bugs": { + "url": "https://github.com/jshttp/http-errors/issues" + }, + "homepage": "https://github.com/jshttp/http-errors", + "_id": "http-errors@1.3.1", + "_shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "_from": "http-errors@>=1.3.1 <1.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "egeste", + "email": "npm@egeste.net" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "tarball": "http://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/send/node_modules/mime/.npmignore b/2-2/node_modules/express/node_modules/send/node_modules/mime/.npmignore new file mode 100644 index 0000000..e69de29 diff --git a/2-2/node_modules/express/node_modules/send/node_modules/mime/LICENSE b/2-2/node_modules/express/node_modules/send/node_modules/mime/LICENSE new file mode 100644 index 0000000..451fc45 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/mime/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/send/node_modules/mime/README.md b/2-2/node_modules/express/node_modules/send/node_modules/mime/README.md new file mode 100644 index 0000000..506fbe5 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/mime/README.md @@ -0,0 +1,90 @@ +# mime + +Comprehensive MIME type mapping API based on mime-db module. + +## Install + +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. + +```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.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + +```js +mime.extension('text/html'); // => 'html' +mime.extension('application/octet-stream'); // => 'bin' +``` + +### mime.charsets.lookup() + +Map mime-type to charset + +```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 + +Custom type mappings can be added on a per-project basis via the following APIs. + +### mime.define() + +Add custom mime/extension mappings + +```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' +``` + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + +```js +mime.extension('text/x-some-format'); // => 'x-sf' +``` + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + +```js +mime.load('./my_project.types'); +``` +The .types file format is simple - See the `types` dir for examples. diff --git a/2-2/node_modules/express/node_modules/send/node_modules/mime/build/build.js b/2-2/node_modules/express/node_modules/send/node_modules/mime/build/build.js new file mode 100644 index 0000000..ed5313e --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/mime/build/build.js @@ -0,0 +1,11 @@ +var db = require('mime-db'); + +var mapByType = {}; +Object.keys(db).forEach(function(key) { + var extensions = db[key].extensions; + if (extensions) { + mapByType[key] = extensions; + } +}); + +console.log(JSON.stringify(mapByType)); diff --git a/2-2/node_modules/express/node_modules/send/node_modules/mime/build/test.js b/2-2/node_modules/express/node_modules/send/node_modules/mime/build/test.js new file mode 100644 index 0000000..58b9ba7 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/mime/build/test.js @@ -0,0 +1,57 @@ +/** + * Usage: node test.js + */ + +var mime = require('../mime'); +var assert = require('assert'); +var path = require('path'); + +// +// Test mime lookups +// + +assert.equal('text/plain', mime.lookup('text.txt')); // normal file +assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase +assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file +assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file +assert.equal('text/plain', mime.lookup('.txt')); // nameless +assert.equal('text/plain', mime.lookup('txt')); // extension-only +assert.equal('text/plain', mime.lookup('/txt')); // extension-less () +assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less +assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized +assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +assert.equal('txt', mime.extension(mime.types.text)); +assert.equal('html', mime.extension(mime.types.htm)); +assert.equal('bin', mime.extension('application/octet-stream')); +assert.equal('bin', mime.extension('application/octet-stream ')); +assert.equal('html', mime.extension(' text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html; charset=UTF-8 ')); +assert.equal('html', mime.extension('text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html ; charset=UTF-8')); +assert.equal('html', mime.extension('text/html;charset=UTF-8')); +assert.equal('html', mime.extension('text/Html;charset=UTF-8')); +assert.equal(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +assert.equal('application/font-woff', mime.lookup('file.woff')); +assert.equal('application/octet-stream', mime.lookup('file.buffer')); +assert.equal('audio/mp4', mime.lookup('file.m4a')); +assert.equal('font/opentype', mime.lookup('file.otf')); + +// +// Test charsets +// + +assert.equal('UTF-8', mime.charsets.lookup('text/plain')); +assert.equal(undefined, mime.charsets.lookup(mime.types.js)); +assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +console.log('\nAll tests passed'); diff --git a/2-2/node_modules/express/node_modules/send/node_modules/mime/cli.js b/2-2/node_modules/express/node_modules/send/node_modules/mime/cli.js new file mode 100755 index 0000000..20b1ffe --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/mime/cli.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node + +var mime = require('./mime.js'); +var file = process.argv[2]; +var type = mime.lookup(file); + +process.stdout.write(type + '\n'); + diff --git a/2-2/node_modules/express/node_modules/send/node_modules/mime/mime.js b/2-2/node_modules/express/node_modules/send/node_modules/mime/mime.js new file mode 100644 index 0000000..341b6a5 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/mime/mime.js @@ -0,0 +1,108 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts]) { + console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Define built-in types +mime.define(require('./types.json')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/2-2/node_modules/express/node_modules/send/node_modules/mime/package.json b/2-2/node_modules/express/node_modules/send/node_modules/mime/package.json new file mode 100644 index 0000000..31e7669 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/mime/package.json @@ -0,0 +1,73 @@ +{ + "author": { + "name": "Robert Kieffer", + "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", + "email": "benjamin@benjaminthomas.org", + "url": "http://github.com/bentomas" + } + ], + "description": "A comprehensive library for mime-type mapping", + "licenses": [ + { + "type": "MIT", + "url": "https://raw.github.com/broofa/node-mime/master/LICENSE" + } + ], + "dependencies": {}, + "devDependencies": { + "mime-db": "^1.2.0" + }, + "keywords": [ + "util", + "mime" + ], + "main": "mime.js", + "name": "mime", + "repository": { + "url": "git+https://github.com/broofa/node-mime.git", + "type": "git" + }, + "version": "1.3.4", + "gitHead": "1628f6e0187095009dcef4805c3a49706f137974", + "bugs": { + "url": "https://github.com/broofa/node-mime/issues" + }, + "homepage": "https://github.com/broofa/node-mime", + "_id": "mime@1.3.4", + "_shasum": "115f9e3b6b3daf2959983cb38f149a2d40eb5d53", + "_from": "mime@1.3.4", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "broofa", + "email": "robert@broofa.com" + }, + "maintainers": [ + { + "name": "broofa", + "email": "robert@broofa.com" + }, + { + "name": "bentomas", + "email": "benjamin@benjaminthomas.org" + } + ], + "dist": { + "shasum": "115f9e3b6b3daf2959983cb38f149a2d40eb5d53", + "tarball": "http://registry.npmjs.org/mime/-/mime-1.3.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime/-/mime-1.3.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/send/node_modules/mime/types.json b/2-2/node_modules/express/node_modules/send/node_modules/mime/types.json new file mode 100644 index 0000000..c674b1c --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/mime/types.json @@ -0,0 +1 @@ +{"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomsvc+xml":["atomsvc"],"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/cu-seeme":["cu"],"application/dash+xml":["mdp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/font-tdpfr":["pfr"],"application/font-woff":["woff"],"application/font-woff2":["woff2"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/java-archive":["jar"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","buffer"],"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/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"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/postscript":["ai","eps","ps"],"application/prs.cww":["cww"],"application/pskc+xml":["pskcxml"],"application/rdf+xml":["rdf"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"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-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"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.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"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.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.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"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.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.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"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.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"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.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"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.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"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.gmx":["gmx"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"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+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"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.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.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"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.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.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.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"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.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"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-officetheme":["thmx"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["stl"],"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-project":["mpp","mpt"],"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.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"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.n-gage.data":["ngdat"],"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.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.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"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.sailingtracker.track":["st"],"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.teacher":["teacher"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"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.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.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"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.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.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"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.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/voicexml+xml":["vxml"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"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-chrome-extension":["crx"],"application/x-conference":["nsc"],"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-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-otf":["otf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-ttf":["ttf","ttc"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"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-hdf":["hdf"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["iso"],"application/x-java-jnlp-file":["jnlp"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"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-web-app-manifest+json":["webapp"],"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/xaml+xml":["xaml"],"application/xcap-diff+xml":["xdf"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xml":["xml","xsl","xsd"],"application/xml-dtd":["dtd"],"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/adpcm":["adp"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mp4":["mp4a","m4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"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-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-xyz":["xyz"],"font/opentype":["otf"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/g3fax":["g3"],"image/gif":["gif"],"image/ief":["ief"],"image/jpeg":["jpeg","jpg","jpe"],"image/ktx":["ktx"],"image/png":["png"],"image/prs.btif":["btif"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/tiff":["tiff","tif"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["sub"],"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.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"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/rfc822":["eml","mime"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.vtu":["vtu"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["x3db","x3dbz"],"model/x3d+vrml":["x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee"],"text/css":["css"],"text/csv":["csv"],"text/hjson":["hjson"],"text/html":["html","htm"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/prs.lines.tag":["dsc"],"text/richtext":["rtx"],"text/sgml":["sgml","sgm"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"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.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/vtt":["vtt"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["markdown","md","mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-pascal":["p","pas"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"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/2-2/node_modules/express/node_modules/send/node_modules/ms/.npmignore b/2-2/node_modules/express/node_modules/send/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/2-2/node_modules/express/node_modules/send/node_modules/ms/History.md b/2-2/node_modules/express/node_modules/send/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/send/node_modules/ms/LICENSE b/2-2/node_modules/express/node_modules/send/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/2-2/node_modules/express/node_modules/send/node_modules/ms/README.md b/2-2/node_modules/express/node_modules/send/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/2-2/node_modules/express/node_modules/send/node_modules/ms/index.js b/2-2/node_modules/express/node_modules/send/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/2-2/node_modules/express/node_modules/send/node_modules/ms/package.json b/2-2/node_modules/express/node_modules/send/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/send/node_modules/statuses/LICENSE b/2-2/node_modules/express/node_modules/send/node_modules/statuses/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/statuses/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/send/node_modules/statuses/README.md b/2-2/node_modules/express/node_modules/send/node_modules/statuses/README.md new file mode 100644 index 0000000..f6ae24c --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/statuses/README.md @@ -0,0 +1,114 @@ +# Statuses + +[![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] + +HTTP status utility for node. + +## API + +```js +var status = require('statuses'); +``` + +### var code = status(Integer || String) + +If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown. + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status('forbidden') // => 403 +status('Forbidden') // => 403 +status(306) // throws, as it's not supported by node.js +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### var msg = status[code] + +Map of `code` to `status message`. `undefined` for invalid `code`s. + +```js +status[404] // => 'Not Found' +``` + +### var code = status[msg] + +Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s. + +```js +status['not found'] // => 404 +status['Not Found'] // => 404 +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +### statuses/codes.json + +```js +var codes = require('statuses/codes.json'); +``` + +This is a JSON file of the status codes +taken from `require('http').STATUS_CODES`. +This is saved so that codes are consistent even in older node.js versions. +For example, `308` will be added in v0.12. + +## Adding Status Codes + +The status codes are primarily sourced from http://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv. +Additionally, custom codes are added from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes. +These are added manually in the `lib/*.json` files. +If you would like to add a status code, add it to the appropriate JSON file. + +To rebuild `codes.json`, run the following: + +```bash +# update src/iana.json +npm run update +# build codes.json +npm run build +``` + +[npm-image]: https://img.shields.io/npm/v/statuses.svg?style=flat +[npm-url]: https://npmjs.org/package/statuses +[node-version-image]: http://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/statuses.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/statuses +[coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[downloads-image]: http://img.shields.io/npm/dm/statuses.svg?style=flat +[downloads-url]: https://npmjs.org/package/statuses diff --git a/2-2/node_modules/express/node_modules/send/node_modules/statuses/codes.json b/2-2/node_modules/express/node_modules/send/node_modules/statuses/codes.json new file mode 100644 index 0000000..4c45a88 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/statuses/codes.json @@ -0,0 +1,64 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "(Unused)", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} \ No newline at end of file diff --git a/2-2/node_modules/express/node_modules/send/node_modules/statuses/index.js b/2-2/node_modules/express/node_modules/send/node_modules/statuses/index.js new file mode 100644 index 0000000..b06182d --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/statuses/index.js @@ -0,0 +1,60 @@ + +var codes = require('./codes.json'); + +module.exports = status; + +// [Integer...] +status.codes = Object.keys(codes).map(function (code) { + code = ~~code; + var msg = codes[code]; + status[code] = msg; + status[msg] = status[msg.toLowerCase()] = code; + return code; +}); + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true, +}; + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true, +}; + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true, +}; + +function status(code) { + if (typeof code === 'number') { + if (!status[code]) throw new Error('invalid status code: ' + code); + return code; + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string'); + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n); + return n; + } + + n = status[code.toLowerCase()]; + if (!n) throw new Error('invalid status message: "' + code + '"'); + return n; +} diff --git a/2-2/node_modules/express/node_modules/send/node_modules/statuses/package.json b/2-2/node_modules/express/node_modules/send/node_modules/statuses/package.json new file mode 100644 index 0000000..81aba72 --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/node_modules/statuses/package.json @@ -0,0 +1,84 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "1.2.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/statuses.git" + }, + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "0.0.6", + "istanbul": "0", + "mocha": "1", + "stream-to-array": "2" + }, + "scripts": { + "build": "node scripts/build.js", + "update": "node scripts/update.js", + "test": "mocha --reporter spec --bail --check-leaks", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks" + }, + "gitHead": "49e6ac7ae4c63ee8186f56cb52112a7eeda28ed7", + "bugs": { + "url": "https://github.com/jshttp/statuses/issues" + }, + "homepage": "https://github.com/jshttp/statuses", + "_id": "statuses@1.2.1", + "_shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "_from": "statuses@>=1.2.1 <1.3.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "tarball": "http://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/send/package.json b/2-2/node_modules/express/node_modules/send/package.json new file mode 100644 index 0000000..38fcf6f --- /dev/null +++ b/2-2/node_modules/express/node_modules/send/package.json @@ -0,0 +1,89 @@ +{ + "name": "send", + "description": "Better streaming static file server with Range and conditional-GET support", + "version": "0.13.1", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/send.git" + }, + "keywords": [ + "static", + "file", + "server" + ], + "dependencies": { + "debug": "~2.2.0", + "depd": "~1.1.0", + "destroy": "~1.0.4", + "escape-html": "~1.0.3", + "etag": "~1.7.0", + "fresh": "0.3.0", + "http-errors": "~1.3.1", + "mime": "1.3.4", + "ms": "0.7.1", + "on-finished": "~2.3.0", + "range-parser": "~1.0.3", + "statuses": "~1.2.1" + }, + "devDependencies": { + "after": "0.8.1", + "istanbul": "0.4.2", + "mocha": "2.3.4", + "supertest": "1.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --check-leaks --reporter spec --bail", + "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": "dbce43fc7102c14b475c25cde918b726063cc991", + "bugs": { + "url": "https://github.com/pillarjs/send/issues" + }, + "homepage": "https://github.com/pillarjs/send", + "_id": "send@0.13.1", + "_shasum": "a30d5f4c82c8a9bae9ad00a1d9b1bdbe6f199ed7", + "_from": "send@0.13.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "a30d5f4c82c8a9bae9ad00a1d9b1bdbe6f199ed7", + "tarball": "http://registry.npmjs.org/send/-/send-0.13.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/send/-/send-0.13.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/serve-static/HISTORY.md b/2-2/node_modules/express/node_modules/serve-static/HISTORY.md new file mode 100644 index 0000000..da30741 --- /dev/null +++ b/2-2/node_modules/express/node_modules/serve-static/HISTORY.md @@ -0,0 +1,303 @@ +1.10.2 / 2016-01-19 +=================== + + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.10.1 / 2016-01-16 +=================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + +1.10.0 / 2015-06-17 +=================== + + * Add `fallthrough` option + - Allows declaring this middleware is the final destination + - Provides better integration with Express patterns + * Fix reading options from options prototype + * Improve the default redirect response headers + * deps: escape-html@1.0.2 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * Fix potential open redirect when mounted at root + +1.7.1 / 2014-10-22 +================== + + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +1.7.0 / 2014-10-15 +================== + + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - 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 +================== + + * Fix redirect loop when index file serving disabled + +1.6.3 / 2014-09-24 +================== + + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +1.6.2 / 2014-09-15 +================== + + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +1.6.1 / 2014-09-07 +================== + + * deps: send@0.9.1 + - deps: fresh@0.2.4 + +1.6.0 / 2014-09-07 +================== + + * deps: send@0.9.0 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + +1.5.4 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +1.5.3 / 2014-08-17 +================== + + * deps: send@0.8.3 + +1.5.2 / 2014-08-14 +================== + + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +1.5.1 / 2014-08-09 +================== + + * Fix parsing of weird `req.originalUrl` values + * deps: parseurl@~1.3.0 + * deps: utils-merge@1.0.0 + +1.5.0 / 2014-08-05 +================== + + * deps: send@0.8.1 + - Add `extensions` option + +1.4.4 / 2014-08-04 +================== + + * deps: send@0.7.4 + - Fix serving index files without root dir + +1.4.3 / 2014-07-29 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + +1.4.2 / 2014-07-27 +================== + + * deps: send@0.7.2 + - deps: depd@0.4.4 + +1.4.1 / 2014-07-26 +================== + + * deps: send@0.7.1 + - deps: depd@0.4.3 + +1.4.0 / 2014-07-21 +================== + + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +1.3.2 / 2014-07-11 +================== + + * deps: send@0.6.0 + - Cap `maxAge` value to 1 year + - deps: debug@1.0.3 + +1.3.1 / 2014-07-09 +================== + + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +1.3.0 / 2014-06-28 +================== + + * Add `setHeaders` option + * Include HTML link in redirect response + * deps: send@0.5.0 + - Accept string for `maxAge` (converted by `ms`) + +1.2.3 / 2014-06-11 +================== + + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +1.2.2 / 2014-06-09 +================== + + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + +1.2.1 / 2014-06-02 +================== + + * use `escape-html` for escaping + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +1.2.0 / 2014-05-29 +================== + + * deps: send@0.4.0 + - Calculate ETag with md5 for reduced collisions + - Fix wrong behavior when index file matches directory + - Ignore stream errors after request ends + - Skip directories in index file search + - deps: debug@0.8.1 + +1.1.0 / 2014-04-24 +================== + + * Accept options directly to `send` module + * deps: send@0.3.0 + +1.0.4 / 2014-04-07 +================== + + * Resolve relative paths at middleware setup + * Use parseurl to parse the URL from request + +1.0.3 / 2014-03-20 +================== + + * Do not rely on connect-like environments + +1.0.2 / 2014-03-06 +================== + + * deps: send@0.2.0 + +1.0.1 / 2014-03-05 +================== + + * Add mime export for back-compat + +1.0.0 / 2014-03-05 +================== + + * Genesis from `connect` diff --git a/2-2/node_modules/express/node_modules/serve-static/LICENSE b/2-2/node_modules/express/node_modules/serve-static/LICENSE new file mode 100644 index 0000000..d8cce67 --- /dev/null +++ b/2-2/node_modules/express/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014-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: + +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/2-2/node_modules/express/node_modules/serve-static/README.md b/2-2/node_modules/express/node_modules/serve-static/README.md new file mode 100644 index 0000000..62104b1 --- /dev/null +++ b/2-2/node_modules/express/node_modules/serve-static/README.md @@ -0,0 +1,236 @@ +# serve-static + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +## Install + +```sh +$ npm install serve-static +``` + +## API + +```js +var serveStatic = require('serve-static') +``` + +### serveStatic(root, options) + +Create a new middleware function to serve files from within a given root +directory. The file to serve will be determined by combining `req.url` +with the provided root directory. When a file is not found, instead of +sending a 404 response, this module will instead call `next()` to move on +to the next middleware, allowing for stacking and fall-backs. + +#### 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 set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Deny a request for a dotfile and 403/`next()`. + - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. + +The default value is similar to `'ignore'`, with the exception that this +default will not ignore the files within a directory that begins with a dot. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +Set file extension fallbacks. When set, if a file is not found, the given +extensions will be added to the file name and search for. The first that +exists will be served. Example: `['html', 'htm']`. + +The default value is `false`. + +##### fallthrough + +Set the middleware to have client errors fall-through as just unhandled +requests, otherwise forward a client error. The difference is that client +errors like a bad request or a request to a non-existent file will cause +this middleware to simply `next()` to your next middleware when this value +is `true`. When this value is `false`, these errors (even 404s), will invoke +`next(err)`. + +Typically `true` is desired such that multiple physical directories can be +mapped to the same web address or for routes to fill in non-existent files. + +The value `false` can be used if this middleware is mounted at a path that +is designed to be strictly a single file system directory, which allows for +short-circuiting 404s for less overhead. This middleware will also reply to +all methods. + +The default value is `true`. + +##### index + +By default this module will send "index.html" files in response to a request +on a directory. 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. + +##### redirect + +Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. + +##### setHeaders + +Function to set custom headers on response. Alterations to the headers need to +occur synchronously. The function is called as `fn(res, path, stat)`, where +the arguments are: + + - `res` the response object + - `path` the file path that is being sent + - `stat` the stat object of the file that is being sent + +## Examples + +### Serve files with vanilla node.js http server + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', {'index': ['index.html', 'index.htm']}) + +// Create server +var server = http.createServer(function(req, res){ + var done = finalhandler(req, res) + serve(req, res, done) +}) + +// Listen +server.listen(3000) +``` + +### Serve all files as downloads + +```js +var contentDisposition = require('content-disposition') +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { + 'index': false, + 'setHeaders': setHeaders +}) + +// Set header to force download +function setHeaders(res, path) { + res.setHeader('Content-Disposition', contentDisposition(path)) +} + +// Create server +var server = http.createServer(function(req, res){ + var done = finalhandler(req, res) + serve(req, res, done) +}) + +// Listen +server.listen(3000) +``` + +### Serving using express + +#### Simple + +This is a simple example of using Express. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +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 +[npm-url]: https://npmjs.org/package/serve-static +[travis-image]: https://img.shields.io/travis/expressjs/serve-static/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/serve-static +[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 +[downloads-url]: https://npmjs.org/package/serve-static +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://gratipay.com/dougwilson/ diff --git a/2-2/node_modules/express/node_modules/serve-static/index.js b/2-2/node_modules/express/node_modules/serve-static/index.js new file mode 100644 index 0000000..0a9f494 --- /dev/null +++ b/2-2/node_modules/express/node_modules/serve-static/index.js @@ -0,0 +1,187 @@ +/*! + * serve-static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var escapeHtml = require('escape-html') +var parseUrl = require('parseurl') +var resolve = require('path').resolve +var send = require('send') +var url = require('url') + +/** + * Module exports. + * @public + */ + +module.exports = serveStatic +module.exports.mime = send.mime + +/** + * @param {string} root + * @param {object} [options] + * @return {function} + * @public + */ + +function serveStatic(root, options) { + if (!root) { + throw new TypeError('root path required') + } + + if (typeof root !== 'string') { + throw new TypeError('root path must be a string') + } + + // copy options object + var opts = Object.create(options || null) + + // fall-though + var fallthrough = opts.fallthrough !== false + + // default redirect + var redirect = opts.redirect !== false + + // headers listener + var setHeaders = opts.setHeaders + + if (setHeaders && typeof setHeaders !== 'function') { + throw new TypeError('option setHeaders must be function') + } + + // setup options for send + opts.maxage = opts.maxage || opts.maxAge || 0 + opts.root = resolve(root) + + // construct directory listener + var onDirectory = redirect + ? createRedirectDirectoryListener() + : createNotFoundDirectoryListener() + + return function serveStatic(req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + if (fallthrough) { + return next() + } + + // method not allowed + res.statusCode = 405 + res.setHeader('Allow', 'GET, HEAD') + res.setHeader('Content-Length', '0') + res.end() + return + } + + var forwardError = !fallthrough + var originalUrl = parseUrl.original(req) + var path = parseUrl(req).pathname + + // make sure redirect occurs at mount + if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { + path = '' + } + + // create send stream + var stream = send(req, path, opts) + + // add directory handler + stream.on('directory', onDirectory) + + // add headers listener + if (setHeaders) { + stream.on('headers', setHeaders) + } + + // add file listener for fallthrough + if (fallthrough) { + stream.on('file', function onFile() { + // once file is determined, always forward error + forwardError = true + }) + } + + // forward errors + stream.on('error', function error(err) { + if (forwardError || !(err.statusCode < 500)) { + next(err) + return + } + + next() + }) + + // pipe + stream.pipe(res) + } +} + +/** + * Collapse all leading slashes into a single slash + * @private + */ +function collapseLeadingSlashes(str) { + for (var i = 0; i < str.length; i++) { + if (str[i] !== '/') { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Create a directory listener that just 404s. + * @private + */ + +function createNotFoundDirectoryListener() { + return function notFound() { + this.error(404) + } +} + +/** + * Create a directory listener that performs a redirect. + * @private + */ + +function createRedirectDirectoryListener() { + return function redirect() { + if (this.hasTrailingSlash()) { + this.error(404) + return + } + + // get original URL + var originalUrl = parseUrl.original(this.req) + + // append trailing slash + originalUrl.path = null + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') + + // reformat the URL + var loc = url.format(originalUrl) + var msg = 'Redirecting to ' + escapeHtml(loc) + '\n' + var res = this.res + + // send redirect response + res.statusCode = 303 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(msg) + } +} diff --git a/2-2/node_modules/express/node_modules/serve-static/package.json b/2-2/node_modules/express/node_modules/serve-static/package.json new file mode 100644 index 0000000..b789b9a --- /dev/null +++ b/2-2/node_modules/express/node_modules/serve-static/package.json @@ -0,0 +1,83 @@ +{ + "name": "serve-static", + "description": "Serve static files", + "version": "1.10.2", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/serve-static.git" + }, + "dependencies": { + "escape-html": "~1.0.3", + "parseurl": "~1.3.1", + "send": "0.13.1" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4", + "supertest": "1.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --reporter spec --bail --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": "aec36c897a33c6c2421fa41cc4947042d67332f6", + "bugs": { + "url": "https://github.com/expressjs/serve-static/issues" + }, + "homepage": "https://github.com/expressjs/serve-static", + "_id": "serve-static@1.10.2", + "_shasum": "feb800d0e722124dd0b00333160c16e9caa8bcb3", + "_from": "serve-static@>=1.10.2 <1.11.0", + "_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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "feb800d0e722124dd0b00333160c16e9caa8bcb3", + "tarball": "http://registry.npmjs.org/serve-static/-/serve-static-1.10.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.10.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/type-is/HISTORY.md b/2-2/node_modules/express/node_modules/type-is/HISTORY.md new file mode 100644 index 0000000..e10b426 --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/HISTORY.md @@ -0,0 +1,192 @@ +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/2-2/node_modules/express/node_modules/type-is/LICENSE b/2-2/node_modules/express/node_modules/type-is/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +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: + +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/2-2/node_modules/express/node_modules/type-is/README.md b/2-2/node_modules/express/node_modules/type-is/README.md new file mode 100644 index 0000000..7a754be --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/README.md @@ -0,0 +1,136 @@ +# type-is + +[![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] + +Infer the content-type of a request. + +### Install + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var is = require('type-is') + +http.createServer(function (req, res) { + var istext = is(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### type = is(request, types) + +`request` is the node HTTP request. `types` is an array of types. + +```js +// req.headers.content-type = 'application/json' + +is(req, ['json']) // 'json' +is(req, ['html', 'json']) // 'json' +is(req, ['application/*']) // 'application/json' +is(req, ['application/json']) // 'application/json' + +is(req, ['html']) // false +``` + +### is.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existance works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + +```js +if (is.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### type = is.is(mediaType, types) + +`mediaType` is the [media type](https://tools.ietf.org/html/rfc6838) string. `types` is an array of types. + +```js +var mediaType = 'application/json' + +is.is(mediaType, ['json']) // 'json' +is.is(mediaType, ['html', 'json']) // 'json' +is.is(mediaType, ['application/*']) // 'application/json' +is.is(mediaType, ['application/json']) // 'application/json' + +is.is(mediaType, ['html']) // false +``` + +### Each type can be: + +- An extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` 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 or the content type is invalid. + +`null` will be returned if the request does not have a body. + +## Examples + +#### Example body parser + +```js +var is = require('type-is'); + +function bodyParser(req, res, next) { + if (!is.hasBody(req)) { + return next() + } + + switch (is(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + break + case 'json': + // parse json body + throw new Error('implement json body parsing') + break + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + break + default: + // 415 error code + res.statusCode = 415 + res.end() + return + } +} +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: https://nodejs.org/en/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[downloads-image]: https://img.shields.io/npm/dm/type-is.svg +[downloads-url]: https://npmjs.org/package/type-is diff --git a/2-2/node_modules/express/node_modules/type-is/index.js b/2-2/node_modules/express/node_modules/type-is/index.js new file mode 100644 index 0000000..ca2962e --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/index.js @@ -0,0 +1,262 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var typer = require('media-typer') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis(value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody(req) { + return req.headers['transfer-encoding'] !== undefined + || !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +function typeofrequest(req, types_) { + var types = types_ + + // no body + if (!hasbody(req)) { + return null + } + + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @private + */ + +function normalize(type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @private + */ + +function mimeMatch(expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // 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) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +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 { + return normalizeType(value) + } catch (err) { + return null + } +} diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md b/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md new file mode 100644 index 0000000..62c2003 --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md @@ -0,0 +1,22 @@ +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/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE b/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md b/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md new file mode 100644 index 0000000..d8df623 --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md @@ -0,0 +1,81 @@ +# 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/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js b/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js new file mode 100644 index 0000000..07f7295 --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js @@ -0,0 +1,270 @@ +/*! + * 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/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json b/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json new file mode 100644 index 0000000..e0f796d --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json @@ -0,0 +1,58 @@ +{ + "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": "git+https://github.com/jshttp/media-typer.git" + }, + "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/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..61b54b4 --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md @@ -0,0 +1,183 @@ +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +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 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md new file mode 100644 index 0000000..e26295d --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md @@ -0,0 +1,103 @@ +# mime-types + +[![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] + +The ultimate javascript content-type utility. + +Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, + so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db) +- No `.define()` functionality + +Otherwise, the API is compatible. + +## Install + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://github.com/jshttp/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[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/node/v/mime-types.svg +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js new file mode 100644 index 0000000..f7008b2 --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js @@ -0,0 +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 + +/** + * 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) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..41a667a --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -0,0 +1,306 @@ +1.21.0 / 2016-01-06 +=================== + + * Add `application/emergencycalldata.comment+xml` + * Add `application/emergencycalldata.deviceinfo+xml` + * Add `application/emergencycalldata.providerinfo+xml` + * Add `application/emergencycalldata.serviceinfo+xml` + * Add `application/emergencycalldata.subscriberinfo+xml` + * Add `application/vnd.filmit.zfc` + * Add `application/vnd.google-apps.document` + * Add `application/vnd.google-apps.presentation` + * Add `application/vnd.google-apps.spreadsheet` + * Add `application/vnd.mapbox-vector-tile` + * Add `application/vnd.ms-printdevicecapabilities+xml` + * Add `application/vnd.ms-windows.devicepairing` + * Add `application/vnd.ms-windows.nwprinting.oob` + * Add `application/vnd.tml` + * Add `audio/evs` + +1.20.0 / 2015-11-10 +=================== + + * Add `application/cdni` + * Add `application/csvm+json` + * Add `application/rfc+xml` + * Add `application/vnd.3gpp.access-transfer-events+xml` + * Add `application/vnd.3gpp.srvcc-ext+xml` + * Add `application/vnd.ms-windows.wsd.oob` + * Add `application/vnd.oxli.countgraph` + * Add `application/vnd.pagerduty+json` + * Add `text/x-suse-ymp` + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.3gpp-prose-pc3ch+xml` + * Add `application/vnd.3gpp.srvcc-info+xml` + * Add `application/vnd.apple.pkpass` + * Add `application/vnd.drive+json` + +1.18.0 / 2015-09-03 +=================== + + * Add `application/pkcs12` + * Add `application/vnd.3gpp-prose+xml` + * Add `application/vnd.3gpp.mid-call+xml` + * Add `application/vnd.3gpp.state-and-event-info+xml` + * Add `application/vnd.anki` + * Add `application/vnd.firemonkeys.cloudcell` + * Add `application/vnd.openblox.game+xml` + * Add `application/vnd.openblox.game-binary` + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +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 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md new file mode 100644 index 0000000..7662440 --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md @@ -0,0 +1,82 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +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 + +```bash +npm install mime-db +``` + +### 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 +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + 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 can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +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 +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[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 +[node-url]: http://nodejs.org/download/ diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json new file mode 100644 index 0000000..412ba9e --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json @@ -0,0 +1,6552 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana" + }, + "application/3gpp-ims+xml": { + "source": "iana" + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana" + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana" + }, + "application/bacnet-xdd+zip": { + "source": "iana" + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana" + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana" + }, + "application/ccxml+xml": { + "source": "iana", + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana" + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana" + }, + "application/cellml+xml": { + "source": "iana" + }, + "application/cfw": { + "source": "iana" + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana" + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana" + }, + "application/cstadata+xml": { + "source": "iana" + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "extensions": ["mdp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana" + }, + "application/dicom": { + "source": "iana" + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana" + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/emergencycalldata.comment+xml": { + "source": "iana" + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana" + }, + "application/emma+xml": { + "source": "iana", + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana" + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana" + }, + "application/epub+zip": { + "source": "iana", + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana" + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false, + "extensions": ["woff"] + }, + "application/font-woff2": { + "compressible": false, + "extensions": ["woff2"] + }, + "application/framework-attributes+xml": { + "source": "iana" + }, + "application/gml+xml": { + "source": "apache", + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana" + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana" + }, + "application/ibe-pkg-reply+xml": { + "source": "iana" + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana" + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana" + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana" + }, + "application/kpml-response+xml": { + "source": "iana" + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana" + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana" + }, + "application/mathml-presentation+xml": { + "source": "iana" + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana" + }, + "application/mbms-deregister+xml": { + "source": "iana" + }, + "application/mbms-envelope+xml": { + "source": "iana" + }, + "application/mbms-msk+xml": { + "source": "iana" + }, + "application/mbms-msk-response+xml": { + "source": "iana" + }, + "application/mbms-protection-description+xml": { + "source": "iana" + }, + "application/mbms-reception-report+xml": { + "source": "iana" + }, + "application/mbms-register+xml": { + "source": "iana" + }, + "application/mbms-register-response+xml": { + "source": "iana" + }, + "application/mbms-schedule+xml": { + "source": "iana" + }, + "application/mbms-user-service-description+xml": { + "source": "iana" + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana" + }, + "application/media_control+xml": { + "source": "iana" + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mods+xml": { + "source": "iana", + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana" + }, + "application/mrb-publish+xml": { + "source": "iana" + }, + "application/msc-ivr+xml": { + "source": "iana" + }, + "application/msc-mixer+xml": { + "source": "iana" + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "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", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana" + }, + "application/parityfec": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana" + }, + "application/pidf-diff+xml": { + "source": "iana" + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana" + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/provenance+xml": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana" + }, + "application/pskc+xml": { + "source": "iana", + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf"] + }, + "application/reginfo+xml": { + "source": "iana", + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana" + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana" + }, + "application/rls-services+xml": { + "source": "iana", + "extensions": ["rs"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana" + }, + "application/samlmetadata+xml": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana" + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/sep+xml": { + "source": "iana" + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana" + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana" + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "extensions": ["ssml"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/ttml+xml": { + "source": "iana" + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana" + }, + "application/urc-ressheet+xml": { + "source": "iana" + }, + "application/urc-targetdesc+xml": { + "source": "iana" + }, + "application/urc-uisocketdesc+xml": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana" + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana" + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana" + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana" + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "extensions": ["mpkg"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avistar+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "extensions": ["cdxml"] + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana" + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana" + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana" + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume-movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana" + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana" + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana" + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana" + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana" + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana" + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana" + }, + "application/vnd.etsi.cug+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana" + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana" + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana" + }, + "application/vnd.etsi.sci+xml": { + "source": "iana" + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana" + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana" + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana" + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana" + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana" + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana" + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana" + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana" + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana" + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+xml": { + "source": "iana", + "extensions": ["lasxml"] + }, + "application/vnd.liberty-request+xml": { + "source": "iana" + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana" + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana" + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana" + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache" + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana" + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana" + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana" + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana" + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana" + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana" + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana" + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana" + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana" + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana" + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana" + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana" + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana" + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana" + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana" + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana" + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana" + }, + "application/vnd.omads-email+xml": { + "source": "iana" + }, + "application/vnd.omads-file+xml": { + "source": "iana" + }, + "application/vnd.omads-folder+xml": { + "source": "iana" + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana" + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "apache", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "apache", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "apache", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana" + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana" + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos+xml": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "apache" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana" + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana" + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana" + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana" + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana" + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana" + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana" + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana" + }, + "application/vnd.wv.ssp+xml": { + "source": "iana" + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana" + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "extensions": ["vxml"] + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/watcherinfo+xml": { + "source": "iana" + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-otf": { + "source": "apache", + "compressible": true, + "extensions": ["otf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-ttf": { + "source": "apache", + "compressible": true, + "extensions": ["ttf","ttc"] + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "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, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "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, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana" + }, + "application/xaml+xml": { + "source": "apache", + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana" + }, + "application/xcap-caps+xml": { + "source": "iana" + }, + "application/xcap-diff+xml": { + "source": "iana", + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana" + }, + "application/xcap-error+xml": { + "source": "iana" + }, + "application/xcap-ns+xml": { + "source": "iana" + }, + "application/xcon-conference-info+xml": { + "source": "iana" + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana" + }, + "application/xenc+xml": { + "source": "iana", + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache" + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana" + }, + "application/xmpp+xml": { + "source": "iana" + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yin+xml": { + "source": "iana", + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana" + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4a","m4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/opentype": { + "compressible": true, + "extensions": ["otf"] + }, + "image/bmp": { + "source": "apache", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/fits": { + "source": "iana" + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jp2": { + "source": "iana" + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana" + }, + "image/jpx": { + "source": "iana" + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana" + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana" + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tiff","tif"] + }, + "image/tiff-fx": { + "source": "iana" + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana" + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana" + }, + "image/vnd.valve.source.texture": { + "source": "iana" + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "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"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana" + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana" + }, + "message/global-delivery-status": { + "source": "iana" + }, + "message/global-disposition-notification": { + "source": "iana" + }, + "message/global-headers": { + "source": "iana" + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana" + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana" + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hjson": { + "extensions": ["hjson"] + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana" + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["markdown","md","mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "apache" + }, + "video/3gpp": { + "source": "apache", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "apache" + }, + "video/3gpp2": { + "source": "apache", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "apache" + }, + "video/bt656": { + "source": "apache" + }, + "video/celb": { + "source": "apache" + }, + "video/dv": { + "source": "apache" + }, + "video/h261": { + "source": "apache", + "extensions": ["h261"] + }, + "video/h263": { + "source": "apache", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "apache" + }, + "video/h263-2000": { + "source": "apache" + }, + "video/h264": { + "source": "apache", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "apache" + }, + "video/h264-svc": { + "source": "apache" + }, + "video/jpeg": { + "source": "apache", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "apache" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "apache", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "apache" + }, + "video/mp2p": { + "source": "apache" + }, + "video/mp2t": { + "source": "apache", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "apache", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "apache" + }, + "video/mpeg": { + "source": "apache", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "apache" + }, + "video/mpv": { + "source": "apache" + }, + "video/nv": { + "source": "apache" + }, + "video/ogg": { + "source": "apache", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "apache" + }, + "video/pointer": { + "source": "apache" + }, + "video/quicktime": { + "source": "apache", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raw": { + "source": "apache" + }, + "video/rtp-enc-aescm128": { + "source": "apache" + }, + "video/rtx": { + "source": "apache" + }, + "video/smpte292m": { + "source": "apache" + }, + "video/ulpfec": { + "source": "apache" + }, + "video/vc1": { + "source": "apache" + }, + "video/vnd.cctv": { + "source": "apache" + }, + "video/vnd.dece.hd": { + "source": "apache", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "apache", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "apache" + }, + "video/vnd.dece.pd": { + "source": "apache", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "apache", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "apache", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "apache" + }, + "video/vnd.directv.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dvb.file": { + "source": "apache", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "apache", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "apache" + }, + "video/vnd.motorola.video": { + "source": "apache" + }, + "video/vnd.motorola.videop": { + "source": "apache" + }, + "video/vnd.mpegurl": { + "source": "apache", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "apache", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "apache" + }, + "video/vnd.nokia.videovoip": { + "source": "apache" + }, + "video/vnd.objectvideo": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "apache" + }, + "video/vnd.sealed.mpeg4": { + "source": "apache" + }, + "video/vnd.sealed.swf": { + "source": "apache" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "apache" + }, + "video/vnd.uvvu.mp4": { + "source": "apache", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "apache", + "extensions": ["viv"] + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json new file mode 100644 index 0000000..e6c9732 --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json @@ -0,0 +1,94 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.21.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "devDependencies": { + "bluebird": "3.1.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "1.0.1", + "gnode": "0.1.1", + "istanbul": "0.4.1", + "mocha": "1.21.5", + "raw-body": "2.1.5", + "stream-to-array": "2.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "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": "9ab92f0a912a602408a64db5741dfef6f82c597f", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "homepage": "https://github.com/jshttp/mime-db", + "_id": "mime-db@1.21.0", + "_shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "_from": "mime-db@>=1.21.0 <1.22.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" + } + ], + "dist": { + "shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json new file mode 100644 index 0000000..d1a5ffa --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json @@ -0,0 +1,84 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "dependencies": { + "mime-db": "~1.21.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec test/test.js", + "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": "329f1c77e1a77c8fac59b15038e3808e9e314d96", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "homepage": "https://github.com/jshttp/mime-types", + "_id": "mime-types@2.1.9", + "_shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "_from": "mime-types@>=2.1.6 <2.2.0", + "_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" + } + ], + "dist": { + "shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/type-is/package.json b/2-2/node_modules/express/node_modules/type-is/package.json new file mode 100644 index 0000000..26b6fae --- /dev/null +++ b/2-2/node_modules/express/node_modules/type-is/package.json @@ -0,0 +1,81 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "1.6.11", + "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": "git+https://github.com/jshttp/type-is.git" + }, + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.9" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "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/" + }, + "keywords": [ + "content", + "type", + "checking" + ], + "gitHead": "8e60e3e78aef84928e0e6c09da950f6950adcdd2", + "bugs": { + "url": "https://github.com/jshttp/type-is/issues" + }, + "homepage": "https://github.com/jshttp/type-is", + "_id": "type-is@1.6.11", + "_shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "_from": "type-is@>=1.6.6 <1.7.0", + "_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": "ritch", + "email": "skawful@gmail.com" + } + ], + "dist": { + "shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "tarball": "http://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/node_modules/utils-merge/.travis.yml b/2-2/node_modules/express/node_modules/utils-merge/.travis.yml new file mode 100644 index 0000000..af92b02 --- /dev/null +++ b/2-2/node_modules/express/node_modules/utils-merge/.travis.yml @@ -0,0 +1,6 @@ +language: "node_js" +node_js: + - "0.4" + - "0.6" + - "0.8" + - "0.10" diff --git a/2-2/node_modules/express/node_modules/utils-merge/LICENSE b/2-2/node_modules/express/node_modules/utils-merge/LICENSE new file mode 100644 index 0000000..e33bd10 --- /dev/null +++ b/2-2/node_modules/express/node_modules/utils-merge/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2013 Jared Hanson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/2-2/node_modules/express/node_modules/utils-merge/README.md b/2-2/node_modules/express/node_modules/utils-merge/README.md new file mode 100644 index 0000000..2f94e9b --- /dev/null +++ b/2-2/node_modules/express/node_modules/utils-merge/README.md @@ -0,0 +1,34 @@ +# utils-merge + +Merges the properties from a source object into a destination object. + +## Install + + $ npm install utils-merge + +## Usage + +```javascript +var a = { foo: 'bar' } + , b = { bar: 'baz' }; + +merge(a, b); +// => { foo: 'bar', bar: 'baz' } +``` + +## Tests + + $ npm install + $ npm test + +[![Build Status](https://secure.travis-ci.org/jaredhanson/utils-merge.png)](http://travis-ci.org/jaredhanson/utils-merge) + +## Credits + + - [Jared Hanson](http://github.com/jaredhanson) + +## License + +[The MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> diff --git a/2-2/node_modules/express/node_modules/utils-merge/index.js b/2-2/node_modules/express/node_modules/utils-merge/index.js new file mode 100644 index 0000000..4265c69 --- /dev/null +++ b/2-2/node_modules/express/node_modules/utils-merge/index.js @@ -0,0 +1,23 @@ +/** + * Merge object b with object a. + * + * var a = { foo: 'bar' } + * , b = { bar: 'baz' }; + * + * merge(a, b); + * // => { foo: 'bar', bar: 'baz' } + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api public + */ + +exports = module.exports = function(a, b){ + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; +}; diff --git a/2-2/node_modules/express/node_modules/utils-merge/package.json b/2-2/node_modules/express/node_modules/utils-merge/package.json new file mode 100644 index 0000000..2f9660e --- /dev/null +++ b/2-2/node_modules/express/node_modules/utils-merge/package.json @@ -0,0 +1,60 @@ +{ + "name": "utils-merge", + "version": "1.0.0", + "description": "merge() utility function", + "keywords": [ + "util" + ], + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/utils-merge.git" + }, + "bugs": { + "url": "http://github.com/jaredhanson/utils-merge/issues" + }, + "author": { + "name": "Jared Hanson", + "email": "jaredhanson@gmail.com", + "url": "http://www.jaredhanson.net/" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://www.opensource.org/licenses/MIT" + } + ], + "main": "./index", + "dependencies": {}, + "devDependencies": { + "mocha": "1.x.x", + "chai": "1.x.x" + }, + "scripts": { + "test": "mocha --reporter spec --require test/bootstrap/node test/*.test.js" + }, + "engines": { + "node": ">= 0.4.0" + }, + "_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#readme" +} diff --git a/2-2/node_modules/express/node_modules/vary/HISTORY.md b/2-2/node_modules/express/node_modules/vary/HISTORY.md new file mode 100644 index 0000000..cddbcd4 --- /dev/null +++ b/2-2/node_modules/express/node_modules/vary/HISTORY.md @@ -0,0 +1,23 @@ +1.0.1 / 2015-07-08 +================== + + * Fix setting empty header from empty `field` + * perf: enable strict mode + * perf: remove argument reassignments + +1.0.0 / 2014-08-10 +================== + + * Accept valid `Vary` header string as `field` + * Add `vary.append` for low-level string manipulation + * Move to `jshttp` orgainzation + +0.1.0 / 2014-06-05 +================== + + * Support array of fields to set + +0.0.0 / 2014-06-04 +================== + + * Initial release diff --git a/2-2/node_modules/express/node_modules/vary/LICENSE b/2-2/node_modules/express/node_modules/vary/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/2-2/node_modules/express/node_modules/vary/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/2-2/node_modules/express/node_modules/vary/README.md b/2-2/node_modules/express/node_modules/vary/README.md new file mode 100644 index 0000000..5966542 --- /dev/null +++ b/2-2/node_modules/express/node_modules/vary/README.md @@ -0,0 +1,91 @@ +# vary + +[![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] + +Manipulate the HTTP Vary header + +## Installation + +```sh +$ npm install vary +``` + +## API + +```js +var vary = require('vary') +``` + +### vary(res, field) + +Adds the given header `field` to the `Vary` response header of `res`. +This can be a string of a single field, a string of a valid `Vary` +header, or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. + +```js +// Append "Origin" to the Vary header of the response +vary(res, 'Origin') +``` + +### vary.append(header, field) + +Adds the given header `field` to the `Vary` response header string `header`. +This can be a string of a single field, a string of a valid `Vary` header, +or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. The new header string is returned. + +```js +// Get header string appending "Origin" to "Accept, User-Agent" +vary.append('Accept, User-Agent', 'Origin') +``` + +## Examples + +### Updating the Vary header when content is based on it + +```js +var http = require('http') +var vary = require('vary') + +http.createServer(function onRequest(req, res) { + // about to user-agent sniff + vary(res, 'User-Agent') + + var ua = req.headers['user-agent'] || '' + var isMobile = /mobi|android|touch|mini/i.test(ua) + + // serve site, depending on isMobile + res.setHeader('Content-Type', 'text/html') + res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') +}) +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/vary.svg +[npm-url]: https://npmjs.org/package/vary +[node-version-image]: https://img.shields.io/node/v/vary.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg +[travis-url]: https://travis-ci.org/jshttp/vary +[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/vary +[downloads-image]: https://img.shields.io/npm/dm/vary.svg +[downloads-url]: https://npmjs.org/package/vary diff --git a/2-2/node_modules/express/node_modules/vary/index.js b/2-2/node_modules/express/node_modules/vary/index.js new file mode 100644 index 0000000..e818dbb --- /dev/null +++ b/2-2/node_modules/express/node_modules/vary/index.js @@ -0,0 +1,117 @@ +/*! + * vary + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + */ + +module.exports = vary; +module.exports.append = append; + +/** + * Variables. + */ + +var separators = /[\(\)<>@,;:\\"\/\[\]\?=\{\}\u0020\u0009]/; + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @api public + */ + +function append(header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required'); + } + + if (!field) { + throw new TypeError('field argument is required'); + } + + // get fields array + var fields = !Array.isArray(field) + ? parse(String(field)) + : field; + + // assert on invalid fields + for (var i = 0; i < fields.length; i++) { + if (separators.test(fields[i])) { + throw new TypeError('field argument contains an invalid header'); + } + } + + // existing, unspecified vary + if (header === '*') { + return header; + } + + // enumerate current values + var val = header; + var vals = parse(header.toLowerCase()); + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*'; + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase(); + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld); + val = val + ? val + ', ' + fields[i] + : fields[i]; + } + } + + return val; +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @api private + */ + +function parse(header) { + return header.trim().split(/ *, */); +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @api public + */ + +function vary(res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required'); + } + + // get existing header + var val = res.getHeader('Vary') || '' + var header = Array.isArray(val) + ? val.join(', ') + : String(val); + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val); + } +} diff --git a/2-2/node_modules/express/node_modules/vary/package.json b/2-2/node_modules/express/node_modules/vary/package.json new file mode 100644 index 0000000..8e1bee4 --- /dev/null +++ b/2-2/node_modules/express/node_modules/vary/package.json @@ -0,0 +1,72 @@ +{ + "name": "vary", + "description": "Manipulate the HTTP Vary header", + "version": "1.0.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "http", + "res", + "vary" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/vary.git" + }, + "devDependencies": { + "istanbul": "0.3.17", + "mocha": "2.2.5", + "supertest": "1.0.1" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "650282ff8e614731837040a23e10f51c20728392", + "bugs": { + "url": "https://github.com/jshttp/vary/issues" + }, + "homepage": "https://github.com/jshttp/vary", + "_id": "vary@1.0.1", + "_shasum": "99e4981566a286118dfb2b817357df7993376d10", + "_from": "vary@>=1.0.1 <1.1.0", + "_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": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "99e4981566a286118dfb2b817357df7993376d10", + "tarball": "http://registry.npmjs.org/vary/-/vary-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/vary/-/vary-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/node_modules/express/package.json b/2-2/node_modules/express/package.json new file mode 100644 index 0000000..66d0e95 --- /dev/null +++ b/2-2/node_modules/express/package.json @@ -0,0 +1,143 @@ +{ + "name": "express", + "description": "Fast, unopinionated, minimalist web framework", + "version": "4.13.4", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "Ciaran Jessup", + "email": "ciaranj@gmail.com" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Guillermo Rauch", + "email": "rauchg@gmail.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com" + }, + { + "name": "Roman Shtylman", + "email": "shtylman+expressjs@gmail.com" + }, + { + "name": "Young Jae Sim", + "email": "hanul@hanul.me" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/express.git" + }, + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "rest", + "restful", + "router", + "app", + "api" + ], + "dependencies": { + "accepts": "~1.2.12", + "array-flatten": "1.1.1", + "content-disposition": "0.5.1", + "content-type": "~1.0.1", + "cookie": "0.1.5", + "cookie-signature": "1.0.6", + "debug": "~2.2.0", + "depd": "~1.1.0", + "escape-html": "~1.0.3", + "etag": "~1.7.0", + "finalhandler": "0.4.1", + "fresh": "0.3.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.1", + "path-to-regexp": "0.1.7", + "proxy-addr": "~1.0.10", + "qs": "4.0.0", + "range-parser": "~1.0.3", + "send": "0.13.1", + "serve-static": "~1.10.2", + "type-is": "~1.6.6", + "utils-merge": "1.0.0", + "vary": "~1.0.1" + }, + "devDependencies": { + "after": "0.8.1", + "ejs": "2.3.4", + "istanbul": "0.4.2", + "marked": "0.3.5", + "mocha": "2.3.4", + "should": "7.1.1", + "supertest": "1.1.0", + "body-parser": "~1.14.2", + "connect-redis": "~2.4.1", + "cookie-parser": "~1.4.1", + "cookie-session": "~1.2.0", + "express-session": "~1.13.0", + "jade": "~1.11.0", + "method-override": "~2.3.5", + "morgan": "~1.6.1", + "multiparty": "~4.1.2", + "vhost": "~3.0.1" + }, + "engines": { + "node": ">= 0.10.0" + }, + "files": [ + "LICENSE", + "History.md", + "Readme.md", + "index.js", + "lib/" + ], + "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/" + }, + "gitHead": "193bed2649c55c1fd362e46cd4702c773f3e7434", + "bugs": { + "url": "https://github.com/expressjs/express/issues" + }, + "homepage": "https://github.com/expressjs/express", + "_id": "express@4.13.4", + "_shasum": "3c0b76f3c77590c8345739061ec0bd3ba067ec24", + "_from": "express@*", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "3c0b76f3c77590c8345739061ec0bd3ba067ec24", + "tarball": "http://registry.npmjs.org/express/-/express-4.13.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/express/-/express-4.13.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/2-2/officialNodeDockerFile b/2-2/officialNodeDockerFile new file mode 100644 index 0000000..52a6613 --- /dev/null +++ b/2-2/officialNodeDockerFile @@ -0,0 +1,30 @@ +FROM buildpack-deps:jessie + +# gpg keys listed at https://github.com/nodejs/node +RUN set -ex \ + && for key in \ + 9554F04D7259F04124DE6B476D5A82AC7E37093B \ + 94AE36675C464D64BAFA68DD7434390BDBE9B9C5 \ + 0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93 \ + FD3A5288F042B6850C66B31F09FE44734EB7990E \ + 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 \ + DD8F2338BAE7501E3DD5AC78C273792F7D83545D \ + B9AE9905FFD7803F25714661B63B535A4C206CA9 \ + C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \ + ; do \ + gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key"; \ + done + +ENV NODE_VERSION 0.10.42 +ENV NPM_VERSION 2.14.1 + +RUN curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \ + && curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/SHASUMS256.txt.asc" \ + && gpg --verify SHASUMS256.txt.asc \ + && grep " node-v$NODE_VERSION-linux-x64.tar.gz\$" SHASUMS256.txt.asc | sha256sum -c - \ + && tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \ + && rm "node-v$NODE_VERSION-linux-x64.tar.gz" SHASUMS256.txt.asc \ + && npm install -g npm@"$NPM_VERSION" \ + && npm cache clear + +CMD [ "node" ] \ No newline at end of file diff --git a/2-2/package.json b/2-2/package.json new file mode 100644 index 0000000..7151024 --- /dev/null +++ b/2-2/package.json @@ -0,0 +1,12 @@ +{ + "name": "2-2", + "version": "1.0.0", + "description": "", + "main": "server.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "node server.js" + }, + "author": "", + "license": "ISC" +} diff --git a/2-2/server.js b/2-2/server.js new file mode 100644 index 0000000..8671d4c --- /dev/null +++ b/2-2/server.js @@ -0,0 +1,11 @@ +var express = require('express'); +var app = express(); + +app.get('/', function(req, res) { + res.json({'msg': 'helloworld'}) +}); + +var port = process.env.port || 3000; +app.listen(port, function() { + console.log('server started'); +}); \ No newline at end of file diff --git a/3-2.txt b/3-2.txt new file mode 100644 index 0000000..41f700c --- /dev/null +++ b/3-2.txt @@ -0,0 +1,5 @@ +//terminal +// docker build -t cadbot/myservice:latest . "specifying a specific githube location" +// docker login +// docker push cadbot/myservice +// docker pull cadbot/myservice \ No newline at end of file diff --git a/3-3.txt b/3-3.txt new file mode 100644 index 0000000..e233618 --- /dev/null +++ b/3-3.txt @@ -0,0 +1,15 @@ +/* just github setup and docker setup +create a repository in github and create automated build on dockerhub +find the github repository + +*/ + +//terminal +// vi server.js +/* +change console.log in server.js file to "Hello world again" +*/ +//terminal +// git add server.js +// git commit - m "update app" +// git push origin master \ No newline at end of file diff --git a/4-2.txt b/4-2.txt new file mode 100644 index 0000000..a6d5bd5 --- /dev/null +++ b/4-2.txt @@ -0,0 +1,30 @@ +//terminal +// which docker-machine +// wget https://githube.com/docker/machine/releases/download/v0.3.0/docker-machine_linux-amd64 +// docker-machine ls +// docker-machine create --driver virtualbox dev +// docker-machine ls +// docker-machine env dev +// docker info +// eval (docker-machine env dev) +// docker info +// docker-machine env +// docker-machine env dev +// set SHELL /bin/bash +// docker-machine env dev +// cd ~/.docker/machine/machines/dev +// pwd +// s +// cd dev/ +// docker-machine ssh dev +// ls + + +//more terminal comands +// docker info +// docker runb -d -p 80:3000 cadbot/myservice +// docker ps +// docker-machine ls +// curl http://192.168.99.100 +// docker-machine ip dev +// curl (docker-machine ip dev) \ No newline at end of file diff --git a/4-3.txt b/4-3.txt new file mode 100644 index 0000000..47bdb52 --- /dev/null +++ b/4-3.txt @@ -0,0 +1,14 @@ +//terminal +// docker-machine create -d digitalocean --digitalocean-access-token bb44ble0cfeda699355edcfe32e8c0a865ddabb835a69ffccda8603947b256df1 --digitalocean-region sfo1 staging +// docker-machine ls +// eval (docker-machine env staging) +// docker status +// docker info +// docker-machine ssh staging +// ls +// docker ps +// ctrl c (exiting) +// docker run -d -p 80:3000 cadbot/myservice +// docker-machine ip staging +// docker-machine ls +// curl (docker-machine ip staging) diff --git a/5-1.txt b/5-1.txt new file mode 100644 index 0000000..85032d2 --- /dev/null +++ b/5-1.txt @@ -0,0 +1,90 @@ +//terminal +// vi server.js + +/* server.js +var express = require('express'); +var app = express(); + +app.get('/', functin(req, res) { + res.json({'msg': 'some message'}) +}); + +var port = process.env.port || 300; +app.listen(port, function() { + console.log('server started'); +}); +*/ + +//terminal +// vi docker-compose.yml + +/* docker-compose.yml +webservice: + build: . + ports: + - "3000:80" + environment: + port: "80" +*/ + +//terminal +// docker-compose up +// docker-compose run webservice +// docker ps +// curl http://localhost:3000 +// docker-compose ps +// docker ps +// docker stop service_webservice_run_1 +// curl http://localhost:3000 +// vi server.js + +/* changes to server.js + +change res.json msg to 'hello world!' + +*/ + +//terminal +// docker-compose up -d +// curl http://localhost:3000 +// docker-compose build webservice +// curl http://localhost:3000 + + +//more terminal +// vi docker-compose.yml + +/* +webservice: + build: . + ports: + - "3000:80" + environment: + port: "80" + volumes: + - .:/user/src/app + +*/ + +//terminal +// vi Dockerfile +// vi server.js +// docker-compose up -d +// curl http://localhost:3000 +// docker stop 19868a4cae3b +// vi server.js +// docker-compose up -d +// curl http://localhost:3000 +// docker ps +// docker exec -it 44262af7e8eb /bin/bash +// touch tempfile + + + + + + + + + + diff --git a/5-1/service/DockerFile b/5-1/service/DockerFile new file mode 100644 index 0000000..7ac2798 --- /dev/null +++ b/5-1/service/DockerFile @@ -0,0 +1,11 @@ +FROM node:0.12.7 + +RUN mkdir -p /user/src/app +WORKDIR /usr/src/app + +COPY . /usr/src/app +RUN npm install + +EXPOSE 3000 + +CMD [ "npm", "start" ] \ No newline at end of file diff --git a/5-1/service/docker-compose.yml b/5-1/service/docker-compose.yml new file mode 100644 index 0000000..7b385db --- /dev/null +++ b/5-1/service/docker-compose.yml @@ -0,0 +1,8 @@ +webservice: + build: . + ports: + - "3000:80" + environment: + port: "80" + volumes: + - .:/user/src/app diff --git a/5-1/service/example b/5-1/service/example new file mode 100644 index 0000000..e69de29 diff --git a/5-1/service/node_modules/express/History.md b/5-1/service/node_modules/express/History.md new file mode 100644 index 0000000..c72241b --- /dev/null +++ b/5-1/service/node_modules/express/History.md @@ -0,0 +1,3062 @@ +4.13.4 / 2016-01-21 +=================== + + * deps: content-disposition@0.5.1 + - perf: enable strict mode + * deps: cookie@0.1.5 + - Throw on invalid values provided to `serialize` + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: finalhandler@0.4.1 + - deps: escape-html@~1.0.3 + * deps: merge-descriptors@1.0.1 + - perf: enable strict mode + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + * deps: proxy-addr@~1.0.10 + - deps: ipaddr.js@1.0.5 + - perf: enable strict mode + * deps: range-parser@~1.0.3 + - perf: enable strict mode + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + * deps: serve-static@~1.10.2 + - deps: escape-html@~1.0.3 + - deps: parseurl@~1.3.0 + - deps: send@0.13.1 + +4.13.3 / 2015-08-02 +=================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + +4.13.2 / 2015-07-31 +=================== + + * deps: accepts@~1.2.12 + - deps: mime-types@~2.1.4 + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +4.13.1 / 2015-07-05 +=================== + + * deps: accepts@~1.2.10 + - deps: mime-types@~2.1.2 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +4.13.0 / 2015-06-20 +=================== + + * Add settings to debug output + * Fix `res.format` error when only `default` provided + * Fix issue where `next('route')` in `app.param` would incorrectly skip values + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * Simplify `res.cookie` to call `res.append` + * Use `array-flatten` module for flattening arrays + * deps: accepts@~1.2.9 + - deps: mime-types@~2.1.1 + - perf: avoid argument reassignment & argument slice + - perf: avoid negotiator recursive construction + - perf: enable strict mode + - perf: remove unnecessary bitwise operator + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: finalhandler@0.4.0 + - Fix a false-positive when unpiping in Node.js 0.8 + - Support `statusCode` property on `Error` objects + - Use `unpipe` module for unpiping requests + - deps: escape-html@1.0.2 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: path-to-regexp@0.1.6 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * deps: serve-static@~1.10.0 + - Add `fallthrough` option + - Fix reading options from options prototype + - Improve the default redirect response headers + - Malformed URLs now `next()` instead of 400 + - deps: escape-html@1.0.2 + - deps: send@0.13.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: isolate `app.render` try block + * perf: remove argument reassignments in application + * perf: remove argument reassignments in request prototype + * perf: remove argument reassignments in response prototype + * perf: remove argument reassignments in routing + * perf: remove argument reassignments in `View` + * perf: skip attempting to decode zero length string + * perf: use saved reference to `http.STATUS_CODES` + +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 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * 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 + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * 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 + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw un-catchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.21.2 / 2015-07-31 +=================== + + * deps: connect@2.30.2 + - deps: body-parser@~1.13.3 + - deps: compression@~1.5.2 + - deps: errorhandler@~1.4.2 + - deps: method-override@~2.3.5 + - deps: serve-index@~1.7.2 + - deps: type-is@~1.6.6 + - deps: vhost@~3.0.1 + * deps: vary@~1.0.1 + - Fix setting empty header from empty `field` + - perf: enable strict mode + - perf: remove argument reassignments + +3.21.1 / 2015-07-05 +=================== + + * deps: basic-auth@~1.0.3 + * deps: connect@2.30.1 + - deps: body-parser@~1.13.2 + - deps: compression@~1.5.1 + - deps: errorhandler@~1.4.1 + - deps: morgan@~1.6.1 + - deps: pause@0.1.0 + - deps: qs@4.0.0 + - deps: serve-index@~1.7.1 + - deps: type-is@~1.6.4 + +3.21.0 / 2015-06-18 +=================== + + * deps: basic-auth@1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: connect@2.30.0 + - deps: body-parser@~1.13.1 + - deps: bytes@2.1.0 + - deps: compression@~1.5.0 + - deps: cookie@0.1.3 + - deps: cookie-parser@~1.3.5 + - deps: csurf@~1.8.3 + - deps: errorhandler@~1.4.0 + - deps: express-session@~1.11.3 + - deps: finalhandler@0.4.0 + - deps: fresh@0.3.0 + - deps: morgan@~1.6.0 + - deps: serve-favicon@~2.3.0 + - deps: serve-index@~1.7.0 + - deps: serve-static@~1.10.0 + - deps: type-is@~1.6.3 + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: mkdirp@0.5.1 + - Work in global strict mode + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + +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 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * 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 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes charset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Closes #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delimited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using using charset utf-8 + * Fixed show-exceptions page, now using using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie complation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'. + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error response support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independent specs for those who cant build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/LICENSE b/5-1/service/node_modules/express/LICENSE new file mode 100644 index 0000000..aa927e4 --- /dev/null +++ b/5-1/service/node_modules/express/LICENSE @@ -0,0 +1,24 @@ +(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 +'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/5-1/service/node_modules/express/Readme.md b/5-1/service/node_modules/express/Readme.md new file mode 100644 index 0000000..6e08454 --- /dev/null +++ b/5-1/service/node_modules/express/Readme.md @@ -0,0 +1,138 @@ +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) + + Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). + + [![NPM Version][npm-image]][npm-url] + [![NPM Downloads][downloads-image]][downloads-url] + [![Linux Build][travis-image]][travis-url] + [![Windows Build][appveyor-image]][appveyor-url] + [![Test Coverage][coveralls-image]][coveralls-url] + +```js +var express = require('express') +var app = express() + +app.get('/', function (req, res) { + res.send('Hello World') +}) + +app.listen(3000) +``` + +## Installation + +```bash +$ npm install express +``` + +## Features + + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly + +## Docs & Community + + * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC + * [Github Organization](https://github.com/expressjs) for Official Middleware & Modules + * [Google Group](https://groups.google.com/group/express-js) for discussion + * [Gitter](https://gitter.im/expressjs/express) for support and discussion + * [Русскоязычная документация](http://jsman.ru/express/) + +###Security Issues + +If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). + +## Quick Start + + 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: + + Install the executable. The executable's major version will match Express's: + +```bash +$ npm install -g express-generator@4 +``` + + Create the app: + +```bash +$ express /tmp/foo && cd /tmp/foo +``` + + Install dependencies: + +```bash +$ npm install +``` + + Start the server: + +```bash +$ npm start +``` + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, web sites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), + you can quickly craft your perfect framework. + +## Examples + + To view the examples, clone the Express repo and install the dependencies: + +```bash +$ git clone git://github.com/expressjs/express.git --depth 1 +$ cd express +$ npm install +``` + + Then run whichever example you want: + +```bash +$ node examples/content-negotiation +``` + +## Tests + + To run the test suite, first install the dependencies, then run `npm test`: + +```bash +$ npm install +$ npm test +``` + +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) [![TJ's Gratipay][gratipay-image-visionmedia]][gratipay-url-visionmedia] + +The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) [![Doug's Gratipay][gratipay-image-dougwilson]][gratipay-url-dougwilson] + +[List of all contributors](https://github.com/expressjs/express/graphs/contributors) + +## License + + [MIT](LICENSE) + +[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 +[downloads-url]: https://npmjs.org/package/express +[travis-image]: https://img.shields.io/travis/expressjs/express/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/express +[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/expressjs/express/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master +[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 +[gratipay-url-dougwilson]: https://gratipay.com/dougwilson/ diff --git a/5-1/service/node_modules/express/index.js b/5-1/service/node_modules/express/index.js new file mode 100644 index 0000000..d219b0c --- /dev/null +++ b/5-1/service/node_modules/express/index.js @@ -0,0 +1,11 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +module.exports = require('./lib/express'); diff --git a/5-1/service/node_modules/express/lib/application.js b/5-1/service/node_modules/express/lib/application.js new file mode 100644 index 0000000..0ee4def --- /dev/null +++ b/5-1/service/node_modules/express/lib/application.js @@ -0,0 +1,643 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var finalhandler = require('finalhandler'); +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var merge = require('utils-merge'); +var resolve = require('path').resolve; +var slice = Array.prototype.slice; + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Variable for trust proxy inheritance back-compat + * @private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ + +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; + + this.defaultConfiguration(); +}; + +/** + * Initialize application configuration. + * @private + */ + +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + 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); + + 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; + this.settings.__proto__ = parent.settings; + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; + +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ + +app.handle = function handle(req, res, callback) { + var router = this._router; + + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ + +app.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires middleware functions'); + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + req.__proto__ = orig.request; + res.__proto__ = orig.response; + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } + + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; + + // store engine + this.engines[extension] = fn; + + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.param = function param(name, fn) { + this.lazyrouter(); + + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } + + return this; + } + + this._router.param(name, fn); + + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge app.locals + merge(renderOptions, this.locals); + + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } + + // merge options + merge(renderOptions, opts); + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} diff --git a/5-1/service/node_modules/express/lib/express.js b/5-1/service/node_modules/express/lib/express.js new file mode 100644 index 0000000..540c8be --- /dev/null +++ b/5-1/service/node_modules/express/lib/express.js @@ -0,0 +1,103 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + app.request = { __proto__: req, app: app }; + app.response = { __proto__: res, app: app }; + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.query = require('./middleware/query'); +exports.static = require('serve-static'); + +/** + * Replace removed middleware with an appropriate error message. + */ + +[ + 'json', + 'urlencoded', + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache', +].forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/5-1/service/node_modules/express/lib/middleware/init.js b/5-1/service/node_modules/express/lib/middleware/init.js new file mode 100644 index 0000000..f3119ed --- /dev/null +++ b/5-1/service/node_modules/express/lib/middleware/init.js @@ -0,0 +1,36 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ + +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; + + req.__proto__ = app.request; + res.__proto__ = app.response; + + res.locals = res.locals || Object.create(null); + + next(); + }; +}; + diff --git a/5-1/service/node_modules/express/lib/middleware/query.js b/5-1/service/node_modules/express/lib/middleware/query.js new file mode 100644 index 0000000..a665f3f --- /dev/null +++ b/5-1/service/node_modules/express/lib/middleware/query.js @@ -0,0 +1,51 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var parseUrl = require('parseurl'); +var qs = require('qs'); + +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = Object.create(options || null); + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + + if (opts !== undefined) { + if (opts.allowDots === undefined) { + opts.allowDots = false; + } + + if (opts.allowPrototypes === undefined) { + opts.allowPrototypes = true; + } + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; diff --git a/5-1/service/node_modules/express/lib/request.js b/5-1/service/node_modules/express/lib/request.js new file mode 100644 index 0000000..33cac18 --- /dev/null +++ b/5-1/service/node_modules/express/lib/request.js @@ -0,0 +1,489 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + */ + +var req = exports = module.exports = { + __proto__: http.IncomingMessage.prototype +}; + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ + +req.get = +req.header = function header(name) { + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", 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. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + +/** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param {Number} size + * @return {Array} + * @public + */ + +req.range = function(size){ + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ + +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; +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + proto = this.get('X-Forwarded-Proto') || proto; + return proto.split(/\s*,\s*/)[0]; +}); + +/** + * Short-hand for: + * + * req.protocol == 'https' + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + return addrs.slice(1).reverse(); +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +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, 0)) { + host = this.get('Host'); + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var s = this.res.statusCode; + + // GET or HEAD for weak freshness validation only + if ('GET' != method && 'HEAD' != method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((s >= 200 && s < 300) || 304 == s) { + return fresh(this.headers, (this.res._headers || {})); + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +}; diff --git a/5-1/service/node_modules/express/lib/response.js b/5-1/service/node_modules/express/lib/response.js new file mode 100644 index 0000000..641704b --- /dev/null +++ b/5-1/service/node_modules/express/lib/response.js @@ -0,0 +1,1053 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var contentDisposition = require('content-disposition'); +var deprecate = require('depd')('express'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var isAbsolute = require('./utils').isAbsolute; +var onFinished = require('on-finished'); +var path = require('path'); +var merge = require('utils-merge'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var statusCodes = http.STATUS_CODES; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = require('vary'); + +/** + * Response prototype. + */ + +var res = module.exports = { + __proto__: http.ServerResponse.prototype +}; + +/** + * Module variables. + * @private + */ + +var charsetRegExp = /;\s*charset\s*=/; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ + +res.status = function status(code) { + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ + +res.send = function send(body) { + var chunk = body; + var encoding; + var len; + var req = this.req; + var type; + + // settings + var app = this.app; + + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } + } + + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statusCodes[chunk]; + } + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + + // populate Content-Length + if (chunk !== undefined) { + if (!Buffer.isBuffer(chunk)) { + // convert chunk to Buffer; saves later double conversions + chunk = new Buffer(chunk, encoding); + encoding = undefined; + } + + len = chunk.length; + this.set('Content-Length', len); + } + + // 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); + } + } + + // freshness + if (req.fresh) this.statusCode = 304; + + // strip irrelevant headers + if (204 == this.statusCode || 304 == this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.json = function json(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = JSON.stringify(val, replacer, spaces); + + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.jsonp = function jsonp(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = JSON.stringify(val, replacer, spaces); + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.charset = 'utf-8'; + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = statusCodes[statusCode] || String(statusCode); + + this.statusCode = statusCode; + this.type('txt'); + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } + + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // create file stream + var file = send(req, path, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') { + next(err); + } + }); +}; + +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + * + * @public + */ + +res.download = function download(path, filename, callback) { + var done = callback; + var name = filename; + + // support function as second arg + if (typeof filename === 'function') { + done = filename; + name = null; + } + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // Resolve the full path for sendFile + var fullPath = resolve(path); + + return this.sendFile(fullPath, { headers: headers }, done); +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ + +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + + return this.set('Content-Type', ct); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

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

hey

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

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

'; + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ + +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } + + vary(this, field); + + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// 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() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + 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; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} diff --git a/5-1/service/node_modules/express/lib/router/index.js b/5-1/service/node_modules/express/lib/router/index.js new file mode 100644 index 0000000..504ed9c --- /dev/null +++ b/5-1/service/node_modules/express/lib/router/index.js @@ -0,0 +1,645 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Route = require('./route'); +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 flatten = require('array-flatten'); +var parseUrl = require('parseurl'); + +/** + * Module variables. + * @private + */ + +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} options + * @return {Router} which is an callable function + * @public + */ + +var proto = module.exports = function(options) { + var opts = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + router.__proto__ = proto; + + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; + + return router; +}; + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } + + // apply param functions + var params = this._params; + var len = params.length; + 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); + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } + + // ensure we end up with a + // middleware function + if ('function' != typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; + +/** + * Dispatch a req, res into the router. + * @private + */ + +proto.handle = function handle(req, res, out) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var search = 1 + req.url.indexOf('?'); + var pathlength = search ? search - 1 : req.url.length; + var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://'); + var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''; + var idx = 0; + var removed = ''; + var slashAdded = false; + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } + + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; + + // 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 = ''; + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } + + // 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); + } + + if (route) { + return layer.handle_request(req, res, next); + } + + trim_prefix(layer, layerError, layerPath, path); + }); + } + + function trim_prefix(layer, layerError, layerPath, path) { + var c = path[layerPath.length]; + if (c && '/' !== c && '.' !== c) return next(layerError); + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + if (layerPath.length !== 0) { + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); + + // Ensure leading slash + if (!fqdn && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Process any parameters for the layer. + * @private + */ + +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; + + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); + } + + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } + + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + + if (!key) { + return done(); + } + + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; + + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; + + // next param + return param(paramCalled.error); + } + + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } + + param(); +}; + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +proto.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var callbacks = flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires middleware functions'); + } + + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; + + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn)); + } + + // add the middleware + debug('use %s %s', path, fn.name || ''); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + } + + return this; +}; + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public + */ + +proto.route = function route(path) { + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; +}; + +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +// 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; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(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) { + return params; + } + + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } + + var i = 0; + var o = 0; + + // determine numeric gaps + while (i in params) { + i++; + } + + while (o in parent) { + o++; + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } + + return mixin(obj, params); +} + +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); + + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + + return function(err){ + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; +} + +// 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() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} diff --git a/5-1/service/node_modules/express/lib/router/layer.js b/5-1/service/node_modules/express/lib/router/layer.js new file mode 100644 index 0000000..fe9210c --- /dev/null +++ b/5-1/service/node_modules/express/lib/router/layer.js @@ -0,0 +1,176 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var pathRegexp = require('path-to-regexp'); +var debug = require('debug')('express:router:layer'); + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Module exports. + * @public + */ + +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %s', path); + var opts = options || {}; + + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); + + if (path === '/' && opts.end === false) { + this.regexp.fast_slash = true; + } +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; + + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } + + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); + } + + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match(path) { + if (path == null) { + // no path, nothing matches + this.params = undefined; + this.path = undefined; + return false; + } + + if (this.regexp.fast_slash) { + // fast path non-ending match for / (everything matches) + this.params = {}; + this.path = ''; + return true; + } + + var m = this.regexp.exec(path); + + if (!m) { + this.params = undefined; + this.path = undefined; + return false; + } + + // store values + this.params = {}; + this.path = m[0]; + + var keys = this.keys; + var params = this.params; + + for (var i = 1; i < m.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(m[i]); + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } + + return true; +}; + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } + + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } + + throw err; + } +} diff --git a/5-1/service/node_modules/express/lib/router/route.js b/5-1/service/node_modules/express/lib/router/route.js new file mode 100644 index 0000000..2788d7b --- /dev/null +++ b/5-1/service/node_modules/express/lib/router/route.js @@ -0,0 +1,210 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:router:route'); +var flatten = require('array-flatten'); +var Layer = require('./layer'); +var methods = require('methods'); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Module exports. + * @public + */ + +module.exports = Route; + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ + +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %s', path); + + // route handlers for various http methods + this.methods = {}; +} + +/** + * Determine if the route handles a given method. + * @private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } + + var name = method.toLowerCase(); + + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } + + return Boolean(this.methods[name]); +}; + +/** + * @return {Array} supported HTTP methods + * @private + */ + +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; +}; + +/** + * dispatch req, res into this route + * @private + */ + +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); + } + + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = this; + + next(); + + function next(err) { + if (err && err === 'route') { + return done(); + } + + var layer = stack[idx++]; + if (!layer) { + return done(err); + } + + if (layer.method && layer.method !== method) { + return next(err); + } + + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires callback functions but got a ' + type; + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); + } + + return this; +}; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires callback functions but got a ' + type; + throw new Error(msg); + } + + debug('%s %s', method, this.path); + + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + } + + return this; + }; +}); diff --git a/5-1/service/node_modules/express/lib/utils.js b/5-1/service/node_modules/express/lib/utils.js new file mode 100644 index 0000000..3d54247 --- /dev/null +++ b/5-1/service/node_modules/express/lib/utils.js @@ -0,0 +1,300 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @api private + */ + +var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var mime = require('send').mime; +var basename = require('path').basename; +var etag = require('etag'); +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); + +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = function (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? new Buffer(body, encoding) + : body; + + return etag(buf, {weak: false}); +}; + +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = function wetag(body, encoding){ + var buf = !Buffer.isBuffer(body) + ? new Buffer(body, encoding) + : body; + + return etag(buf, {weak: true}); +}; + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +exports.isAbsolute = function(path){ + if ('/' == path[0]) return true; + if (':' == path[1] && '\\' == path[2]) return true; + if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; + +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' == pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowDots: false, + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} diff --git a/5-1/service/node_modules/express/lib/view.js b/5-1/service/node_modules/express/lib/view.js new file mode 100644 index 0000000..52415d4 --- /dev/null +++ b/5-1/service/node_modules/express/lib/view.js @@ -0,0 +1,173 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:view'); +var path = require('path'); +var fs = require('fs'); +var utils = require('./utils'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ + +function View(name, options) { + var opts = options || {}; + + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; + } + + if (!opts.engines[this.ext]) { + // load engine + opts.engines[this.ext] = require(this.ext.substr(1)).__express; + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); + + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/5-1/service/node_modules/express/node_modules/accepts/HISTORY.md b/5-1/service/node_modules/express/node_modules/accepts/HISTORY.md new file mode 100644 index 0000000..397636e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/HISTORY.md @@ -0,0 +1,170 @@ +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +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 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/5-1/service/node_modules/express/node_modules/accepts/LICENSE b/5-1/service/node_modules/express/node_modules/accepts/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-1/service/node_modules/express/node_modules/accepts/README.md b/5-1/service/node_modules/express/node_modules/accepts/README.md new file mode 100644 index 0000000..ae36676 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/README.md @@ -0,0 +1,135 @@ +# accepts + +[![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] + +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 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 `*` + +## Installation + +```sh +npm install accepts +``` + +## API + +```js +var accepts = require('accepts') +``` + +### 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) +``` + +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 +[npm-url]: https://npmjs.org/package/accepts +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/accepts +[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 +[downloads-url]: https://npmjs.org/package/accepts diff --git a/5-1/service/node_modules/express/node_modules/accepts/index.js b/5-1/service/node_modules/express/node_modules/accepts/index.js new file mode 100644 index 0000000..e80192a --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/index.js @@ -0,0 +1,231 @@ +/*! + * 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') + +/** + * 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 = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +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 = this.negotiator.mediaTypes(mimes.filter(validMime)); + var first = accepts[0]; + if (!first) return false; + return types[mimes.indexOf(first)]; +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +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 +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +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 +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +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 +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime(type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ + +function validMime(type) { + return typeof type === 'string'; +} diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..61b54b4 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md @@ -0,0 +1,183 @@ +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +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 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md new file mode 100644 index 0000000..e26295d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md @@ -0,0 +1,103 @@ +# mime-types + +[![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] + +The ultimate javascript content-type utility. + +Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, + so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db) +- No `.define()` functionality + +Otherwise, the API is compatible. + +## Install + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://github.com/jshttp/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[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/node/v/mime-types.svg +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js new file mode 100644 index 0000000..f7008b2 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js @@ -0,0 +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 + +/** + * 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) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..41a667a --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -0,0 +1,306 @@ +1.21.0 / 2016-01-06 +=================== + + * Add `application/emergencycalldata.comment+xml` + * Add `application/emergencycalldata.deviceinfo+xml` + * Add `application/emergencycalldata.providerinfo+xml` + * Add `application/emergencycalldata.serviceinfo+xml` + * Add `application/emergencycalldata.subscriberinfo+xml` + * Add `application/vnd.filmit.zfc` + * Add `application/vnd.google-apps.document` + * Add `application/vnd.google-apps.presentation` + * Add `application/vnd.google-apps.spreadsheet` + * Add `application/vnd.mapbox-vector-tile` + * Add `application/vnd.ms-printdevicecapabilities+xml` + * Add `application/vnd.ms-windows.devicepairing` + * Add `application/vnd.ms-windows.nwprinting.oob` + * Add `application/vnd.tml` + * Add `audio/evs` + +1.20.0 / 2015-11-10 +=================== + + * Add `application/cdni` + * Add `application/csvm+json` + * Add `application/rfc+xml` + * Add `application/vnd.3gpp.access-transfer-events+xml` + * Add `application/vnd.3gpp.srvcc-ext+xml` + * Add `application/vnd.ms-windows.wsd.oob` + * Add `application/vnd.oxli.countgraph` + * Add `application/vnd.pagerduty+json` + * Add `text/x-suse-ymp` + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.3gpp-prose-pc3ch+xml` + * Add `application/vnd.3gpp.srvcc-info+xml` + * Add `application/vnd.apple.pkpass` + * Add `application/vnd.drive+json` + +1.18.0 / 2015-09-03 +=================== + + * Add `application/pkcs12` + * Add `application/vnd.3gpp-prose+xml` + * Add `application/vnd.3gpp.mid-call+xml` + * Add `application/vnd.3gpp.state-and-event-info+xml` + * Add `application/vnd.anki` + * Add `application/vnd.firemonkeys.cloudcell` + * Add `application/vnd.openblox.game+xml` + * Add `application/vnd.openblox.game-binary` + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +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 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md new file mode 100644 index 0000000..7662440 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md @@ -0,0 +1,82 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +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 + +```bash +npm install mime-db +``` + +### 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 +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + 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 can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +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 +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[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 +[node-url]: http://nodejs.org/download/ diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json new file mode 100644 index 0000000..412ba9e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json @@ -0,0 +1,6552 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana" + }, + "application/3gpp-ims+xml": { + "source": "iana" + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana" + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana" + }, + "application/bacnet-xdd+zip": { + "source": "iana" + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana" + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana" + }, + "application/ccxml+xml": { + "source": "iana", + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana" + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana" + }, + "application/cellml+xml": { + "source": "iana" + }, + "application/cfw": { + "source": "iana" + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana" + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana" + }, + "application/cstadata+xml": { + "source": "iana" + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "extensions": ["mdp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana" + }, + "application/dicom": { + "source": "iana" + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana" + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/emergencycalldata.comment+xml": { + "source": "iana" + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana" + }, + "application/emma+xml": { + "source": "iana", + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana" + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana" + }, + "application/epub+zip": { + "source": "iana", + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana" + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false, + "extensions": ["woff"] + }, + "application/font-woff2": { + "compressible": false, + "extensions": ["woff2"] + }, + "application/framework-attributes+xml": { + "source": "iana" + }, + "application/gml+xml": { + "source": "apache", + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana" + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana" + }, + "application/ibe-pkg-reply+xml": { + "source": "iana" + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana" + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana" + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana" + }, + "application/kpml-response+xml": { + "source": "iana" + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana" + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana" + }, + "application/mathml-presentation+xml": { + "source": "iana" + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana" + }, + "application/mbms-deregister+xml": { + "source": "iana" + }, + "application/mbms-envelope+xml": { + "source": "iana" + }, + "application/mbms-msk+xml": { + "source": "iana" + }, + "application/mbms-msk-response+xml": { + "source": "iana" + }, + "application/mbms-protection-description+xml": { + "source": "iana" + }, + "application/mbms-reception-report+xml": { + "source": "iana" + }, + "application/mbms-register+xml": { + "source": "iana" + }, + "application/mbms-register-response+xml": { + "source": "iana" + }, + "application/mbms-schedule+xml": { + "source": "iana" + }, + "application/mbms-user-service-description+xml": { + "source": "iana" + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana" + }, + "application/media_control+xml": { + "source": "iana" + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mods+xml": { + "source": "iana", + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana" + }, + "application/mrb-publish+xml": { + "source": "iana" + }, + "application/msc-ivr+xml": { + "source": "iana" + }, + "application/msc-mixer+xml": { + "source": "iana" + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "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", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana" + }, + "application/parityfec": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana" + }, + "application/pidf-diff+xml": { + "source": "iana" + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana" + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/provenance+xml": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana" + }, + "application/pskc+xml": { + "source": "iana", + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf"] + }, + "application/reginfo+xml": { + "source": "iana", + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana" + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana" + }, + "application/rls-services+xml": { + "source": "iana", + "extensions": ["rs"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana" + }, + "application/samlmetadata+xml": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana" + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/sep+xml": { + "source": "iana" + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana" + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana" + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "extensions": ["ssml"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/ttml+xml": { + "source": "iana" + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana" + }, + "application/urc-ressheet+xml": { + "source": "iana" + }, + "application/urc-targetdesc+xml": { + "source": "iana" + }, + "application/urc-uisocketdesc+xml": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana" + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana" + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana" + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana" + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "extensions": ["mpkg"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avistar+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "extensions": ["cdxml"] + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana" + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana" + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana" + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume-movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana" + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana" + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana" + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana" + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana" + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana" + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana" + }, + "application/vnd.etsi.cug+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana" + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana" + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana" + }, + "application/vnd.etsi.sci+xml": { + "source": "iana" + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana" + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana" + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana" + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana" + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana" + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana" + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana" + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana" + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana" + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+xml": { + "source": "iana", + "extensions": ["lasxml"] + }, + "application/vnd.liberty-request+xml": { + "source": "iana" + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana" + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana" + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana" + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache" + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana" + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana" + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana" + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana" + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana" + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana" + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana" + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana" + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana" + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana" + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana" + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana" + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana" + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana" + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana" + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana" + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana" + }, + "application/vnd.omads-email+xml": { + "source": "iana" + }, + "application/vnd.omads-file+xml": { + "source": "iana" + }, + "application/vnd.omads-folder+xml": { + "source": "iana" + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana" + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "apache", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "apache", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "apache", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana" + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana" + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos+xml": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "apache" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana" + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana" + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana" + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana" + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana" + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana" + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana" + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana" + }, + "application/vnd.wv.ssp+xml": { + "source": "iana" + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana" + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "extensions": ["vxml"] + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/watcherinfo+xml": { + "source": "iana" + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-otf": { + "source": "apache", + "compressible": true, + "extensions": ["otf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-ttf": { + "source": "apache", + "compressible": true, + "extensions": ["ttf","ttc"] + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "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, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "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, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana" + }, + "application/xaml+xml": { + "source": "apache", + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana" + }, + "application/xcap-caps+xml": { + "source": "iana" + }, + "application/xcap-diff+xml": { + "source": "iana", + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana" + }, + "application/xcap-error+xml": { + "source": "iana" + }, + "application/xcap-ns+xml": { + "source": "iana" + }, + "application/xcon-conference-info+xml": { + "source": "iana" + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana" + }, + "application/xenc+xml": { + "source": "iana", + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache" + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana" + }, + "application/xmpp+xml": { + "source": "iana" + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yin+xml": { + "source": "iana", + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana" + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4a","m4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/opentype": { + "compressible": true, + "extensions": ["otf"] + }, + "image/bmp": { + "source": "apache", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/fits": { + "source": "iana" + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jp2": { + "source": "iana" + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana" + }, + "image/jpx": { + "source": "iana" + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana" + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana" + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tiff","tif"] + }, + "image/tiff-fx": { + "source": "iana" + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana" + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana" + }, + "image/vnd.valve.source.texture": { + "source": "iana" + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "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"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana" + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana" + }, + "message/global-delivery-status": { + "source": "iana" + }, + "message/global-disposition-notification": { + "source": "iana" + }, + "message/global-headers": { + "source": "iana" + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana" + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana" + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hjson": { + "extensions": ["hjson"] + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana" + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["markdown","md","mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "apache" + }, + "video/3gpp": { + "source": "apache", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "apache" + }, + "video/3gpp2": { + "source": "apache", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "apache" + }, + "video/bt656": { + "source": "apache" + }, + "video/celb": { + "source": "apache" + }, + "video/dv": { + "source": "apache" + }, + "video/h261": { + "source": "apache", + "extensions": ["h261"] + }, + "video/h263": { + "source": "apache", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "apache" + }, + "video/h263-2000": { + "source": "apache" + }, + "video/h264": { + "source": "apache", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "apache" + }, + "video/h264-svc": { + "source": "apache" + }, + "video/jpeg": { + "source": "apache", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "apache" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "apache", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "apache" + }, + "video/mp2p": { + "source": "apache" + }, + "video/mp2t": { + "source": "apache", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "apache", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "apache" + }, + "video/mpeg": { + "source": "apache", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "apache" + }, + "video/mpv": { + "source": "apache" + }, + "video/nv": { + "source": "apache" + }, + "video/ogg": { + "source": "apache", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "apache" + }, + "video/pointer": { + "source": "apache" + }, + "video/quicktime": { + "source": "apache", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raw": { + "source": "apache" + }, + "video/rtp-enc-aescm128": { + "source": "apache" + }, + "video/rtx": { + "source": "apache" + }, + "video/smpte292m": { + "source": "apache" + }, + "video/ulpfec": { + "source": "apache" + }, + "video/vc1": { + "source": "apache" + }, + "video/vnd.cctv": { + "source": "apache" + }, + "video/vnd.dece.hd": { + "source": "apache", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "apache", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "apache" + }, + "video/vnd.dece.pd": { + "source": "apache", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "apache", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "apache", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "apache" + }, + "video/vnd.directv.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dvb.file": { + "source": "apache", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "apache", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "apache" + }, + "video/vnd.motorola.video": { + "source": "apache" + }, + "video/vnd.motorola.videop": { + "source": "apache" + }, + "video/vnd.mpegurl": { + "source": "apache", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "apache", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "apache" + }, + "video/vnd.nokia.videovoip": { + "source": "apache" + }, + "video/vnd.objectvideo": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "apache" + }, + "video/vnd.sealed.mpeg4": { + "source": "apache" + }, + "video/vnd.sealed.swf": { + "source": "apache" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "apache" + }, + "video/vnd.uvvu.mp4": { + "source": "apache", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "apache", + "extensions": ["viv"] + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json new file mode 100644 index 0000000..e6c9732 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json @@ -0,0 +1,94 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.21.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "devDependencies": { + "bluebird": "3.1.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "1.0.1", + "gnode": "0.1.1", + "istanbul": "0.4.1", + "mocha": "1.21.5", + "raw-body": "2.1.5", + "stream-to-array": "2.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "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": "9ab92f0a912a602408a64db5741dfef6f82c597f", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "homepage": "https://github.com/jshttp/mime-db", + "_id": "mime-db@1.21.0", + "_shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "_from": "mime-db@>=1.21.0 <1.22.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" + } + ], + "dist": { + "shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json new file mode 100644 index 0000000..d1a5ffa --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json @@ -0,0 +1,84 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "dependencies": { + "mime-db": "~1.21.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec test/test.js", + "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": "329f1c77e1a77c8fac59b15038e3808e9e314d96", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "homepage": "https://github.com/jshttp/mime-types", + "_id": "mime-types@2.1.9", + "_shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "_from": "mime-types@>=2.1.6 <2.2.0", + "_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" + } + ], + "dist": { + "shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md new file mode 100644 index 0000000..aa2a7c4 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md @@ -0,0 +1,76 @@ +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE new file mode 100644 index 0000000..ea6b9e2 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +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 +'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/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md new file mode 100644 index 0000000..ef507fa --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md @@ -0,0 +1,203 @@ +# negotiator + +[![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] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +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 + +```js +negotiator = new Negotiator(request) + +availableLanguages = 'en', 'es', 'fr' + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +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 + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +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 + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +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 +[npm-url]: https://npmjs.org/package/negotiator +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/negotiator +[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 +[downloads-url]: https://npmjs.org/package/negotiator diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js new file mode 100644 index 0000000..edae9cf --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js @@ -0,0 +1,62 @@ + +var preferredCharsets = require('./lib/charset'); +var preferredEncodings = require('./lib/encoding'); +var preferredLanguages = require('./lib/language'); +var preferredMediaTypes = require('./lib/mediaType'); + +module.exports = Negotiator; +Negotiator.Negotiator = Negotiator; + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available) { + var set = this.encodings(available); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available) { + return preferredEncodings(this.request.headers['accept-encoding'], available); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; diff --git a/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js new file mode 100644 index 0000000..7abd17c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js @@ -0,0 +1,102 @@ +module.exports = preferredCharsets; +preferredCharsets.preferredCharsets = preferredCharsets; + +function parseAcceptCharset(accept) { + 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) { + var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +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; + } + } + + return priority; +} + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + 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/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js new file mode 100644 index 0000000..7fed673 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,118 @@ +module.exports = preferredEncodings; +preferredEncodings.preferredEncodings = preferredEncodings; + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + 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 (!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 + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +function parseEncoding(s, i) { + var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); + + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +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; + } + } + + return priority; +} + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +function preferredEncodings(accept, provided) { + 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/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js new file mode 100644 index 0000000..ed9e1ec --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js @@ -0,0 +1,112 @@ +module.exports = preferredLanguages; +preferredLanguages.preferredLanguages = preferredLanguages; + +function parseAcceptLanguage(accept) { + 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) { + var match = s.match(/^\s*(\S+?)(?:-(\S+?))?\s*(?:;(.*))?$/); + if (!match) return null; + + var prefix = match[1], + suffix = match[2], + full = prefix; + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +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; + } + } + + return priority; +} + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + 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/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 0000000..4170c25 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,179 @@ +/** + * 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) { + 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) { + var match = s.match(/\s*(\S+?)\/([^;\s]+)\s*(?:;(.*))?/); + if (!match) return null; + + var type = match[1], + subtype = match[2], + full = "" + type + "/" + subtype, + params = {}, + q = 1; + + if (match[3]) { + params = match[3].split(';').map(function(s) { + return s.trim().split('='); + }).reduce(function (set, p) { + 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) { + q = parseFloat(params.q); + delete params.q; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i, + full: full + }; +} + +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; + } + } + + return priority; +} + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } + +} + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + 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/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json new file mode 100644 index 0000000..66d2824 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json @@ -0,0 +1,86 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "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/" + } + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/negotiator.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "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": "cbb717b3f164f25820f90b160cda6d0166b9d922", + "bugs": { + "url": "https://github.com/jshttp/negotiator/issues" + }, + "homepage": "https://github.com/jshttp/negotiator", + "_id": "negotiator@0.5.3", + "_shasum": "269d5c476810ec92edbe7b6c2f28316384f9a7e8", + "_from": "negotiator@0.5.3", + "_npmVersion": "1.4.28", + "_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": "269d5c476810ec92edbe7b6c2f28316384f9a7e8", + "tarball": "http://registry.npmjs.org/negotiator/-/negotiator-0.5.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.5.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/accepts/package.json b/5-1/service/node_modules/express/node_modules/accepts/package.json new file mode 100644 index 0000000..6455e64 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/accepts/package.json @@ -0,0 +1,98 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "1.2.13", + "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": "git+https://github.com/jshttp/accepts.git" + }, + "dependencies": { + "mime-types": "~2.1.6", + "negotiator": "0.5.3" + }, + "devDependencies": { + "istanbul": "0.3.19", + "mocha": "~1.21.5" + }, + "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/" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ], + "gitHead": "b7e15ecb25dacc0b2133ed0553d64f8a79537e01", + "bugs": { + "url": "https://github.com/jshttp/accepts/issues" + }, + "homepage": "https://github.com/jshttp/accepts", + "_id": "accepts@1.2.13", + "_shasum": "e5f1f3928c6d95fd96558c36ec3d9d0de4a6ecea", + "_from": "accepts@>=1.2.12 <1.3.0", + "_npmVersion": "1.4.28", + "_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": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "e5f1f3928c6d95fd96558c36ec3d9d0de4a6ecea", + "tarball": "http://registry.npmjs.org/accepts/-/accepts-1.2.13.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.2.13.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/array-flatten/LICENSE b/5-1/service/node_modules/express/node_modules/array-flatten/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/array-flatten/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/5-1/service/node_modules/express/node_modules/array-flatten/README.md b/5-1/service/node_modules/express/node_modules/array-flatten/README.md new file mode 100644 index 0000000..91fa5b6 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/array-flatten/README.md @@ -0,0 +1,43 @@ +# Array Flatten + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +> Flatten an array of nested arrays into a single flat array. Accepts an optional depth. + +## Installation + +``` +npm install array-flatten --save +``` + +## Usage + +```javascript +var flatten = require('array-flatten') + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) +//=> [1, 2, 3, 4, 5, 6, 7, 8, 9] + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) +//=> [1, 2, 3, [4, [5], 6], 7, 8, 9] + +(function () { + flatten(arguments) //=> [1, 2, 3] +})(1, [2, 3]) +``` + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat +[npm-url]: https://npmjs.org/package/array-flatten +[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat +[downloads-url]: https://npmjs.org/package/array-flatten +[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat +[travis-url]: https://travis-ci.org/blakeembrey/array-flatten +[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat +[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master diff --git a/5-1/service/node_modules/express/node_modules/array-flatten/array-flatten.js b/5-1/service/node_modules/express/node_modules/array-flatten/array-flatten.js new file mode 100644 index 0000000..089117b --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/array-flatten/array-flatten.js @@ -0,0 +1,64 @@ +'use strict' + +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result +} + +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result +} + +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) +} diff --git a/5-1/service/node_modules/express/node_modules/array-flatten/package.json b/5-1/service/node_modules/express/node_modules/array-flatten/package.json new file mode 100644 index 0000000..f80f937 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/array-flatten/package.json @@ -0,0 +1,62 @@ +{ + "name": "array-flatten", + "version": "1.1.1", + "description": "Flatten an array of nested arrays into a single flat array", + "main": "array-flatten.js", + "files": [ + "array-flatten.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/blakeembrey/array-flatten.git" + }, + "keywords": [ + "array", + "flatten", + "arguments", + "depth" + ], + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/blakeembrey/array-flatten/issues" + }, + "homepage": "https://github.com/blakeembrey/array-flatten", + "devDependencies": { + "istanbul": "^0.3.13", + "mocha": "^2.2.4", + "pre-commit": "^1.0.7", + "standard": "^3.7.3" + }, + "gitHead": "1963a9189229d408e1e8f585a00c8be9edbd1803", + "_id": "array-flatten@1.1.1", + "_shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2", + "_from": "array-flatten@1.1.1", + "_npmVersion": "2.11.3", + "_nodeVersion": "2.3.3", + "_npmUser": { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + }, + "maintainers": [ + { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + } + ], + "dist": { + "shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2", + "tarball": "http://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/content-disposition/HISTORY.md b/5-1/service/node_modules/express/node_modules/content-disposition/HISTORY.md new file mode 100644 index 0000000..76d494c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/content-disposition/HISTORY.md @@ -0,0 +1,45 @@ +0.5.1 / 2016-01-17 +================== + + * perf: enable strict mode + +0.5.0 / 2014-10-11 +================== + + * Add `parse` function + +0.4.0 / 2014-09-21 +================== + + * Expand non-Unicode `filename` to the full ISO-8859-1 charset + +0.3.0 / 2014-09-20 +================== + + * Add `fallback` option + * Add `type` option + +0.2.0 / 2014-09-19 +================== + + * Reduce ambiguity of file names with hex escape in buggy browsers + +0.1.2 / 2014-09-19 +================== + + * Fix periodic invalid Unicode filename header + +0.1.1 / 2014-09-19 +================== + + * Fix invalid characters appearing in `filename*` parameter + +0.1.0 / 2014-09-18 +================== + + * Make the `filename` argument optional + +0.0.0 / 2014-09-18 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/content-disposition/LICENSE b/5-1/service/node_modules/express/node_modules/content-disposition/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/content-disposition/README.md b/5-1/service/node_modules/express/node_modules/content-disposition/README.md new file mode 100644 index 0000000..5cebce4 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/content-disposition/README.md @@ -0,0 +1,141 @@ +# content-disposition + +[![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] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + +```js +var contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + +```js +var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'); +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +var contentDisposition = require('content-disposition') +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +var filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest(req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + var stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://tools.ietf.org/html/rfc2616 +[rfc-5987]: https://tools.ietf.org/html/rfc5987 +[rfc-6266]: https://tools.ietf.org/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition.svg?style=flat +[npm-url]: https://npmjs.org/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/content-disposition +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg?style=flat +[downloads-url]: https://npmjs.org/package/content-disposition diff --git a/5-1/service/node_modules/express/node_modules/content-disposition/index.js b/5-1/service/node_modules/express/node_modules/content-disposition/index.js new file mode 100644 index 0000000..4a352dc --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/content-disposition/index.js @@ -0,0 +1,445 @@ +/*! + * content-disposition + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * Module dependencies. + */ + +var basename = require('path').basename + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + */ + +var encodeUriAttrCharRegExp = /[\x00-\x20"'\(\)*,\/:;<=>?@\[\\\]\{\}\x7f]/g + +/** + * RegExp to match percent encoding escape. + */ + +var hexEscapeRegExp = /%[0-9A-Fa-f]{2}/ +var hexEscapeReplaceRegExp = /%([0-9A-Fa-f]{2})/g + +/** + * RegExp to match non-latin1 characters. + */ + +var nonLatin1RegExp = /[^\x20-\x7e\xa0-\xff]/g + +/** + * 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 for various RFC 2616 grammar + * + * 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 = + * HT = + * CTL = + * OCTET = + */ + +var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g +var textRegExp = /^[\x20-\x7e\x80-\xff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + */ + +var extValueRegExp = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+\-\.^_`|~])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + */ + +var dispositionTypeRegExp = /^([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *(?:$|;)/ + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @api public + */ + +function contentDisposition(filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @api private + */ + +function createparams(filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && nonLatin1RegExp.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = textRegExp.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || hexEscapeRegExp.test(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @api private + */ + +function format(obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !tokenRegExp.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // 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] + + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 6987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @api private + */ + +function decodefield(str) { + var match = extValueRegExp.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + + // to binary string + var binary = encoded.replace(hexEscapeReplaceRegExp, pdecode) + + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = new Buffer(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @api private + */ + +function getlatin1(val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(nonLatin1RegExp, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @api private + */ + +function parse(string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = dispositionTypeRegExp.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = paramRegExp.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + 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 (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + 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') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @api private + */ + +function pdecode(str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @api private + */ + +function pencode(char) { + var hex = String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() + return hex.length === 1 + ? '%0' + hex + : '%' + hex +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @api private + */ + +function qstring(val) { + var str = String(val) + + return '"' + str.replace(quoteRegExp, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @api private + */ + +function ustring(val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(encodeUriAttrCharRegExp, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + */ + +function ContentDisposition(type, parameters) { + this.type = type + this.parameters = parameters +} diff --git a/5-1/service/node_modules/express/node_modules/content-disposition/package.json b/5-1/service/node_modules/express/node_modules/content-disposition/package.json new file mode 100644 index 0000000..1b22eb9 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/content-disposition/package.json @@ -0,0 +1,66 @@ +{ + "name": "content-disposition", + "description": "Create and parse Content-Disposition header", + "version": "0.5.1", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-disposition.git" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "7b391db3af5629d4c698f1de21802940bb9f22a5", + "bugs": { + "url": "https://github.com/jshttp/content-disposition/issues" + }, + "homepage": "https://github.com/jshttp/content-disposition", + "_id": "content-disposition@0.5.1", + "_shasum": "87476c6a67c8daa87e32e87616df883ba7fb071b", + "_from": "content-disposition@0.5.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "87476c6a67c8daa87e32e87616df883ba7fb071b", + "tarball": "http://registry.npmjs.org/content-disposition/-/content-disposition-0.5.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/content-type/HISTORY.md b/5-1/service/node_modules/express/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..8a623a2 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/content-type/HISTORY.md @@ -0,0 +1,9 @@ +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/5-1/service/node_modules/express/node_modules/content-type/LICENSE b/5-1/service/node_modules/express/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/5-1/service/node_modules/express/node_modules/content-type/README.md b/5-1/service/node_modules/express/node_modules/content-type/README.md new file mode 100644 index 0000000..3ed6741 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/content-type/README.md @@ -0,0 +1,92 @@ +# content-type + +[![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] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a content 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 media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({type: 'image/svg+xml'}) +``` + +Format an object into a content type string. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-type.svg +[npm-url]: https://npmjs.org/package/content-type +[node-version-image]: https://img.shields.io/node/v/content-type.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg +[travis-url]: https://travis-ci.org/jshttp/content-type +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-type +[downloads-image]: https://img.shields.io/npm/dm/content-type.svg +[downloads-url]: https://npmjs.org/package/content-type diff --git a/5-1/service/node_modules/express/node_modules/content-type/index.js b/5-1/service/node_modules/express/node_modules/content-type/index.js new file mode 100644 index 0000000..6a2ea9f --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/content-type/index.js @@ -0,0 +1,214 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) */g +var textRegExp = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var qescRegExp = /\\([\u000b\u0020-\u00ff])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var quoteRegExp = /([\\"])/g + +/** + * RegExp to match type in RFC 6838 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+\/[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !typeRegExp.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // 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} + * @public + */ + +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string === 'object') { + // support req/res-like objects as argument + string = getcontenttype(string) + + if (typeof string !== 'string') { + throw new TypeError('content-type header is missing from object'); + } + } + + 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).trim() + : string.trim() + + if (!typeRegExp.test(type)) { + throw new TypeError('invalid media type') + } + + var key + var match + var obj = new ContentType(type.toLowerCase()) + 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') + } + + obj.parameters[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @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} + * @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') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType(type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/5-1/service/node_modules/express/node_modules/content-type/package.json b/5-1/service/node_modules/express/node_modules/content-type/package.json new file mode 100644 index 0000000..e23403c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/content-type/package.json @@ -0,0 +1,65 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-type.git" + }, + "devDependencies": { + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail 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": "3aa58f9c5a358a3634b8601602177888b4a477d8", + "bugs": { + "url": "https://github.com/jshttp/content-type/issues" + }, + "homepage": "https://github.com/jshttp/content-type", + "_id": "content-type@1.0.1", + "_shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "_from": "content-type@>=1.0.1 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "tarball": "http://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/cookie-signature/.npmignore b/5-1/service/node_modules/express/node_modules/cookie-signature/.npmignore new file mode 100644 index 0000000..f1250e5 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/cookie-signature/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/5-1/service/node_modules/express/node_modules/cookie-signature/History.md b/5-1/service/node_modules/express/node_modules/cookie-signature/History.md new file mode 100644 index 0000000..78513cc --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/cookie-signature/History.md @@ -0,0 +1,38 @@ +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 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/cookie-signature/Readme.md b/5-1/service/node_modules/express/node_modules/cookie-signature/Readme.md new file mode 100644 index 0000000..2559e84 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/cookie-signature/Readme.md @@ -0,0 +1,42 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +(The MIT License) + +Copyright (c) 2012 LearnBoost <tj@learnboost.com> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/5-1/service/node_modules/express/node_modules/cookie-signature/index.js b/5-1/service/node_modules/express/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..b8c9463 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/cookie-signature/index.js @@ -0,0 +1,51 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie 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) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("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); + + return sha1(mac) == sha1(val) ? str : false; +}; + +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} diff --git a/5-1/service/node_modules/express/node_modules/cookie-signature/package.json b/5-1/service/node_modules/express/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..28f87d0 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/cookie-signature/package.json @@ -0,0 +1,59 @@ +{ + "name": "cookie-signature", + "version": "1.0.6", + "description": "Sign and unsign cookies", + "keywords": [ + "cookie", + "sign", + "unsign" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@learnboost.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/visionmedia/node-cookie-signature.git" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, + "main": "index", + "gitHead": "391b56cf44d88c493491b7e3fc53208cfb976d2a", + "bugs": { + "url": "https://github.com/visionmedia/node-cookie-signature/issues" + }, + "homepage": "https://github.com/visionmedia/node-cookie-signature", + "_id": "cookie-signature@1.0.6", + "_shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c", + "_from": "cookie-signature@1.0.6", + "_npmVersion": "2.3.0", + "_nodeVersion": "0.10.36", + "_npmUser": { + "name": "natevw", + "email": "natevw@yahoo.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "natevw", + "email": "natevw@yahoo.com" + } + ], + "dist": { + "shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c", + "tarball": "http://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/cookie/HISTORY.md b/5-1/service/node_modules/express/node_modules/cookie/HISTORY.md new file mode 100644 index 0000000..c9803ce --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/cookie/HISTORY.md @@ -0,0 +1,72 @@ +0.1.5 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.1.4 / 2015-09-17 +================== + + * Throw better error for invalid argument to parse + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.1.3 / 2015-05-19 +================== + + * Reduce the scope of try-catch deopt + * Remove argument reassignments + +0.1.2 / 2014-04-16 +================== + + * Remove unnecessary files from npm package + +0.1.1 / 2014-02-23 +================== + + * Fix bad parse when cookie value contained a comma + * Fix support for `maxAge` of `0` + +0.1.0 / 2013-05-01 +================== + + * Add `decode` option + * Add `encode` option + +0.0.6 / 2013-04-08 +================== + + * Ignore cookie parts missing `=` + +0.0.5 / 2012-10-29 +================== + + * Return raw cookie value if value unescape errors + +0.0.4 / 2012-06-21 +================== + + * Use encode/decodeURIComponent for cookie encoding/decoding + - Improve server/client interoperability + +0.0.3 / 2012-06-06 +================== + + * Only escape special characters per the cookie RFC + +0.0.2 / 2012-06-01 +================== + + * Fix `maxAge` option to not throw error + +0.0.1 / 2012-05-28 +================== + + * Add more tests + +0.0.0 / 2012-05-28 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/cookie/LICENSE b/5-1/service/node_modules/express/node_modules/cookie/LICENSE new file mode 100644 index 0000000..e849495 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +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 +'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/5-1/service/node_modules/express/node_modules/cookie/README.md b/5-1/service/node_modules/express/node_modules/cookie/README.md new file mode 100644 index 0000000..acdb5c2 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/cookie/README.md @@ -0,0 +1,64 @@ +# cookie + +[![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] + +cookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers. + +See [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies. + +## how? + +``` +npm install cookie +``` + +```javascript +var cookie = require('cookie'); + +var hdr = cookie.serialize('foo', 'bar'); +// hdr = 'foo=bar'; + +var cookies = cookie.parse('foo=bar; cat=meow; dog=ruff'); +// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' }; +``` + +## more + +The serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values. + +### path +> cookie path + +### expires +> absolute expiration date for the cookie (Date object) + +### maxAge +> relative max age of the cookie from when the client receives it (seconds) + +### domain +> domain for the cookie + +### secure +> true or false + +### httpOnly +> true or false + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/cookie.svg +[npm-url]: https://npmjs.org/package/cookie +[node-version-image]: https://img.shields.io/node/v/cookie.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/cookie/master.svg +[travis-url]: https://travis-ci.org/jshttp/cookie +[coveralls-image]: https://img.shields.io/coveralls/jshttp/cookie/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[downloads-image]: https://img.shields.io/npm/dm/cookie.svg +[downloads-url]: https://npmjs.org/package/cookie diff --git a/5-1/service/node_modules/express/node_modules/cookie/index.js b/5-1/service/node_modules/express/node_modules/cookie/index.js new file mode 100644 index 0000000..b8389a1 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/cookie/index.js @@ -0,0 +1,156 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var decode = decodeURIComponent; +var encode = encodeURIComponent; + +/** + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF + */ + +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var pairs = str.split(/; */); + var dec = opt.decode || decode; + + pairs.forEach(function(pair) { + var eq_idx = pair.indexOf('=') + + // skip things that don't look like key=value + if (eq_idx < 0) { + return; + } + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + }); + + return obj; +} + +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var pairs = [name + '=' + value]; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + pairs.push('Max-Age=' + maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + + pairs.push('Domain=' + opt.domain); + } + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + pairs.push('Path=' + opt.path); + } + + if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString()); + if (opt.httpOnly) pairs.push('HttpOnly'); + if (opt.secure) pairs.push('Secure'); + + return pairs.join('; '); +} + +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ + +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} diff --git a/5-1/service/node_modules/express/node_modules/cookie/package.json b/5-1/service/node_modules/express/node_modules/cookie/package.json new file mode 100644 index 0000000..01399d0 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/cookie/package.json @@ -0,0 +1,76 @@ +{ + "name": "cookie", + "description": "cookie parsing and serialization", + "version": "0.1.5", + "author": { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "cookie", + "cookies" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/cookie.git" + }, + "devDependencies": { + "istanbul": "0.3.20", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --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": "0dfc4876575cef2609cdc1082fccf832743822c2", + "bugs": { + "url": "https://github.com/jshttp/cookie/issues" + }, + "homepage": "https://github.com/jshttp/cookie", + "_id": "cookie@0.1.5", + "_shasum": "6ab9948a4b1ae21952cd2588530a4722d4044d7c", + "_from": "cookie@0.1.5", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "6ab9948a4b1ae21952cd2588530a4722d4044d7c", + "tarball": "http://registry.npmjs.org/cookie/-/cookie-0.1.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/debug/.jshintrc b/5-1/service/node_modules/express/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/5-1/service/node_modules/express/node_modules/debug/.npmignore b/5-1/service/node_modules/express/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/5-1/service/node_modules/express/node_modules/debug/History.md b/5-1/service/node_modules/express/node_modules/debug/History.md new file mode 100644 index 0000000..854c971 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/History.md @@ -0,0 +1,195 @@ + +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 +================== + + * 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/5-1/service/node_modules/express/node_modules/debug/Makefile b/5-1/service/node_modules/express/node_modules/debug/Makefile new file mode 100644 index 0000000..5cf4a59 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/Makefile @@ -0,0 +1,36 @@ + +# 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 dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +distclean: clean + @rm -rf node_modules + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean distclean diff --git a/5-1/service/node_modules/express/node_modules/debug/Readme.md b/5-1/service/node_modules/express/node_modules/debug/Readme.md new file mode 100644 index 0000000..b4f45e3 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/Readme.md @@ -0,0 +1,188 @@ +# 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'); +``` + +### 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 + - 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/5-1/service/node_modules/express/node_modules/debug/bower.json b/5-1/service/node_modules/express/node_modules/debug/bower.json new file mode 100644 index 0000000..6af573f --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/bower.json @@ -0,0 +1,28 @@ +{ + "name": "visionmedia-debug", + "main": "dist/debug.js", + "version": "2.2.0", + "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/5-1/service/node_modules/express/node_modules/debug/browser.js b/5-1/service/node_modules/express/node_modules/debug/browser.js new file mode 100644 index 0000000..7c76452 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/browser.js @@ -0,0 +1,168 @@ + +/** + * 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; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : 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) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.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/5-1/service/node_modules/express/node_modules/debug/component.json b/5-1/service/node_modules/express/node_modules/debug/component.json new file mode 100644 index 0000000..ca10637 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.2.0", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/5-1/service/node_modules/express/node_modules/debug/debug.js b/5-1/service/node_modules/express/node_modules/debug/debug.js new file mode 100644 index 0000000..7571a86 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * 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/5-1/service/node_modules/express/node_modules/debug/node.js b/5-1/service/node_modules/express/node_modules/debug/node.js new file mode 100644 index 0000000..1d392a8 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/node.js @@ -0,0 +1,209 @@ + +/** + * 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/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/.npmignore b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/History.md b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/LICENSE b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/README.md b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/index.js b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/package.json b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/debug/package.json b/5-1/service/node_modules/express/node_modules/debug/package.json new file mode 100644 index 0000000..24bb9c9 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/debug/package.json @@ -0,0 +1,73 @@ +{ + "name": "debug", + "version": "2.2.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "license": "MIT", + "dependencies": { + "ms": "0.7.1" + }, + "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": "b38458422b5aa8aa6d286b10dfe427e8a67e2b35", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@2.2.0", + "scripts": {}, + "_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "_from": "debug@>=2.2.0 <2.3.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "tarball": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/depd/History.md b/5-1/service/node_modules/express/node_modules/depd/History.md new file mode 100644 index 0000000..ace1171 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/depd/History.md @@ -0,0 +1,84 @@ +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/5-1/service/node_modules/express/node_modules/depd/LICENSE b/5-1/service/node_modules/express/node_modules/depd/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-1/service/node_modules/express/node_modules/depd/Readme.md b/5-1/service/node_modules/express/node_modules/depd/Readme.md new file mode 100644 index 0000000..09bb979 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/depd/Readme.md @@ -0,0 +1,281 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction() { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: http://nodejs.org/download/ +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/5-1/service/node_modules/express/node_modules/depd/index.js b/5-1/service/node_modules/express/node_modules/depd/index.js new file mode 100644 index 0000000..fddcae8 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/depd/index.js @@ -0,0 +1,521 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace(str, namespace) { + var val = str.split(/[ ,]+/) + + namespace = String(namespace).toLowerCase() + + for (var i = 0 ; i < val.length; i++) { + if (!(str = val[i])) continue; + + // namespace contained + if (str === '*' || str.toLowerCase() === namespace) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor(obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter() { return value } + + if (descriptor.writable) { + descriptor.set = function setter(val) { return value = val } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString(arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString(stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate(message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log(message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + callSite = callSiteLocation(stack[1]) + callSite.name = site.name + file = callSite[0] + } else { + // get call site + i = 2 + site = callSiteLocation(stack[i]) + callSite = site + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? site.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + if (!message) { + message = callSite === site || !callSite.name + ? defaultMessage(site) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, message, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var msg = format.call(this, message, caller, stack.slice(i)) + process.stderr.write(msg + '\n', 'utf8') + + return +} + +/** + * Get call site location as array. + */ + +function callSiteLocation(callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage(site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain(msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor(msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' // bold cyan + + ' \x1b[33;1mdeprecated\x1b[22;39m' // bold yellow + + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation(callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace(obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter() { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter() { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError(namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return stackString = createStackString.call(this, stack) + }, + set: function setter(val) { + stackString = val + } + }) + + return error +} diff --git a/5-1/service/node_modules/express/node_modules/depd/lib/browser/index.js b/5-1/service/node_modules/express/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..f464e05 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/depd/lib/browser/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate(message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + return +} diff --git a/5-1/service/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js b/5-1/service/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js new file mode 100644 index 0000000..4b73381 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js @@ -0,0 +1,35 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = bufferConcat + +/** + * Concatenate an array of Buffers. + */ + +function bufferConcat(bufs) { + var length = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + length += bufs[i].length + } + + var buf = new Buffer(length) + var pos = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + bufs[i].copy(buf, pos) + pos += bufs[i].length + } + + return buf +} diff --git a/5-1/service/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js b/5-1/service/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 0000000..9ecef34 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation(callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString(callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName(obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/5-1/service/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js b/5-1/service/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 0000000..a05fceb --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount(emitter, type) { + return emitter.listeners(type).length +} diff --git a/5-1/service/node_modules/express/node_modules/depd/lib/compat/index.js b/5-1/service/node_modules/express/node_modules/depd/lib/compat/index.js new file mode 100644 index 0000000..aa3c1de --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/depd/lib/compat/index.js @@ -0,0 +1,84 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('buffer') +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'bufferConcat', function bufferConcat() { + return Buffer.concat || require('./buffer-concat') +}) + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace(obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount() { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty(obj, prop, getter) { + function get() { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString(obj) { + return obj.toString() +} diff --git a/5-1/service/node_modules/express/node_modules/depd/package.json b/5-1/service/node_modules/express/node_modules/depd/package.json new file mode 100644 index 0000000..9da460a --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/depd/package.json @@ -0,0 +1,67 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "1.1.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/dougwilson/nodejs-depd.git" + }, + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail test/", + "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": "78c659de20283e3a6bee92bda455e6daff01686a", + "bugs": { + "url": "https://github.com/dougwilson/nodejs-depd/issues" + }, + "homepage": "https://github.com/dougwilson/nodejs-depd", + "_id": "depd@1.1.0", + "_shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "_from": "depd@>=1.1.0 <1.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "tarball": "http://registry.npmjs.org/depd/-/depd-1.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/depd/-/depd-1.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/escape-html/LICENSE b/5-1/service/node_modules/express/node_modules/escape-html/LICENSE new file mode 100644 index 0000000..2e70de9 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/escape-html/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2013 TJ Holowaychuk +Copyright (c) 2015 Andreas Lubbe +Copyright (c) 2015 Tiancheng "Timothy" Gu + +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/5-1/service/node_modules/express/node_modules/escape-html/Readme.md b/5-1/service/node_modules/express/node_modules/escape-html/Readme.md new file mode 100644 index 0000000..653d9ea --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/escape-html/Readme.md @@ -0,0 +1,43 @@ + +# escape-html + + Escape string for use in HTML + +## Example + +```js +var escape = require('escape-html'); +var html = escape('foo & bar'); +// -> foo & bar +``` + +## Benchmark + +``` +$ npm run-script bench + +> escape-html@1.0.3 bench nodejs-escape-html +> 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 + + 1 test completed. + 2 tests completed. + 3 tests completed. + + no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) + single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) + many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) +``` + +## License + + MIT \ No newline at end of file diff --git a/5-1/service/node_modules/express/node_modules/escape-html/index.js b/5-1/service/node_modules/express/node_modules/escape-html/index.js new file mode 100644 index 0000000..bf9e226 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/escape-html/index.js @@ -0,0 +1,78 @@ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} diff --git a/5-1/service/node_modules/express/node_modules/escape-html/package.json b/5-1/service/node_modules/express/node_modules/escape-html/package.json new file mode 100644 index 0000000..eb73427 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/escape-html/package.json @@ -0,0 +1,57 @@ +{ + "name": "escape-html", + "description": "Escape string for use in HTML", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "escape", + "html", + "utility" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/component/escape-html.git" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4" + }, + "files": [ + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "bench": "node benchmark/index.js" + }, + "gitHead": "7ac2ea3977fcac3d4c5be8d2a037812820c65f28", + "bugs": { + "url": "https://github.com/component/escape-html/issues" + }, + "homepage": "https://github.com/component/escape-html", + "_id": "escape-html@1.0.3", + "_shasum": "0258eae4d3d0c0974de1c169188ef0051d1d1988", + "_from": "escape-html@>=1.0.3 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "0258eae4d3d0c0974de1c169188ef0051d1d1988", + "tarball": "http://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/etag/HISTORY.md b/5-1/service/node_modules/express/node_modules/etag/HISTORY.md new file mode 100644 index 0000000..bd0f26d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/etag/HISTORY.md @@ -0,0 +1,71 @@ +1.7.0 / 2015-06-08 +================== + + * Always include entity length in ETags for hash length extensions + * Generate non-Stats ETags using MD5 only (no longer CRC32) + * Improve stat performance by removing hashing + * Remove base64 padding in ETags to shorten + * Use MD5 instead of MD4 in weak ETags over 1KB + +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 +================== + + * deps: crc@3.2.1 + - Minor fixes + +1.5.0 / 2014-10-14 +================== + + * Improve string performance + * Slightly improve speed for weak ETags over 1KB + +1.4.0 / 2014-09-21 +================== + + * Support "fake" stats objects + * Support Node.js 0.6 + +1.3.1 / 2014-09-14 +================== + + * Use the (new and improved) `crc` for crc32 + +1.3.0 / 2014-08-29 +================== + + * Default strings to strong ETags + * Improve speed for weak ETags over 1KB + +1.2.1 / 2014-08-29 +================== + + * Use the (much faster) `buffer-crc32` for crc32 + +1.2.0 / 2014-08-24 +================== + + * Add support for file stat objects + +1.1.0 / 2014-08-24 +================== + + * Add fast-path for empty entity + * Add weak ETag generation + * Shrink size of generated ETags + +1.0.1 / 2014-08-24 +================== + + * Fix behavior of string containing Unicode + +1.0.0 / 2014-05-18 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/etag/LICENSE b/5-1/service/node_modules/express/node_modules/etag/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/etag/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-1/service/node_modules/express/node_modules/etag/README.md b/5-1/service/node_modules/express/node_modules/etag/README.md new file mode 100644 index 0000000..8da9e05 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/etag/README.md @@ -0,0 +1,165 @@ +# etag + +[![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] + +Create simple ETags + +## Installation + +```sh +$ npm install etag +``` + +## API + +```js +var etag = require('etag') +``` + +### etag(entity, [options]) + +Generate a strong ETag for the given entity. This should be the complete +body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By +default, a strong ETag is generated except for `fs.Stats`, which will +generate a weak ETag (this can be overwritten by `options.weak`). + +```js +res.setHeader('ETag', etag(body)) +``` + +#### Options + +`etag` accepts these properties in the options object. + +##### weak + +Specifies if the generated ETag will include the weak validator mark (that +is, the leading `W/`). The actual entity tag is the same. The default value +is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +```bash +$ npm run-script bench + +> 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 + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 289,198 ops/sec ±1.09% (190 runs sampled) +* buffer - weak x 287,838 ops/sec ±0.91% (189 runs sampled) +* string - strong x 284,586 ops/sec ±1.05% (192 runs sampled) +* string - weak x 287,439 ops/sec ±0.82% (192 runs sampled) + +> node benchmark/body1-1kb.js + + 1KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 212,423 ops/sec ±0.75% (193 runs sampled) +* buffer - weak x 211,871 ops/sec ±0.74% (194 runs sampled) + string - strong x 205,291 ops/sec ±0.86% (194 runs sampled) + string - weak x 208,463 ops/sec ±0.79% (192 runs sampled) + +> node benchmark/body2-5kb.js + + 5KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 92,901 ops/sec ±0.58% (195 runs sampled) +* buffer - weak x 93,045 ops/sec ±0.65% (192 runs sampled) + string - strong x 89,621 ops/sec ±0.68% (194 runs sampled) + string - weak x 90,070 ops/sec ±0.70% (196 runs sampled) + +> node benchmark/body3-10kb.js + + 10KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 54,220 ops/sec ±0.85% (192 runs sampled) +* buffer - weak x 54,069 ops/sec ±0.83% (191 runs sampled) + string - strong x 53,078 ops/sec ±0.53% (194 runs sampled) + string - weak x 53,849 ops/sec ±0.47% (197 runs sampled) + +> node benchmark/body4-100kb.js + + 100KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 6,673 ops/sec ±0.15% (197 runs sampled) +* buffer - weak x 6,716 ops/sec ±0.12% (198 runs sampled) + string - strong x 6,357 ops/sec ±0.14% (197 runs sampled) + string - weak x 6,344 ops/sec ±0.21% (197 runs sampled) + +> node benchmark/stats.js + + stats + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* real - strong x 1,671,989 ops/sec ±0.13% (197 runs sampled) +* real - weak x 1,681,297 ops/sec ±0.12% (198 runs sampled) + fake - strong x 927,063 ops/sec ±0.14% (198 runs sampled) + fake - weak x 914,461 ops/sec ±0.41% (191 runs sampled) +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master +[downloads-image]: https://img.shields.io/npm/dm/etag.svg +[downloads-url]: https://npmjs.org/package/etag diff --git a/5-1/service/node_modules/express/node_modules/etag/index.js b/5-1/service/node_modules/express/node_modules/etag/index.js new file mode 100644 index 0000000..b582c84 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/etag/index.js @@ -0,0 +1,132 @@ +/*! + * etag + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = etag + +/** + * Module dependencies. + * @private + */ + +var crypto = require('crypto') +var Stats = require('fs').Stats + +/** + * Module variables. + * @private + */ + +var base64PadCharRegExp = /=+$/ +var toString = Object.prototype.toString + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag(entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-1B2M2Y8AsgTpgAmY7PhCfg"' + } + + // compute hash of entity + var hash = crypto + .createHash('md5') + .update(entity, 'utf8') + .digest('base64') + .replace(base64PadCharRegExp, '') + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag(entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats(obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + 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' + && 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag(stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} diff --git a/5-1/service/node_modules/express/node_modules/etag/package.json b/5-1/service/node_modules/express/node_modules/etag/package.json new file mode 100644 index 0000000..8dc110c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/etag/package.json @@ -0,0 +1,73 @@ +{ + "name": "etag", + "description": "Create simple ETags", + "version": "1.7.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "David Björklund", + "email": "david.bjorklund@gmail.com" + } + ], + "license": "MIT", + "keywords": [ + "etag", + "http", + "res" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/etag.git" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.3.14", + "mocha": "~1.21.4", + "seedrandom": "2.3.11" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "a511f5c8c930fd9546dbd88acb080f96bc788cfc", + "bugs": { + "url": "https://github.com/jshttp/etag/issues" + }, + "homepage": "https://github.com/jshttp/etag", + "_id": "etag@1.7.0", + "_shasum": "03d30b5f67dd6e632d2945d30d6652731a34d5d8", + "_from": "etag@>=1.7.0 <1.8.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "03d30b5f67dd6e632d2945d30d6652731a34d5d8", + "tarball": "http://registry.npmjs.org/etag/-/etag-1.7.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/etag/-/etag-1.7.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/finalhandler/HISTORY.md b/5-1/service/node_modules/express/node_modules/finalhandler/HISTORY.md new file mode 100644 index 0000000..78dddc0 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/finalhandler/HISTORY.md @@ -0,0 +1,98 @@ +0.4.1 / 2015-12-02 +================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + +0.4.0 / 2015-06-14 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + * Support `statusCode` property on `Error` objects + * Use `unpipe` module for unpiping requests + * deps: escape-html@1.0.2 + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.3.1 / 2014-10-16 +================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + +0.3.0 / 2014-09-17 +================== + + * Terminate in progress response only on error + * Use `on-finished` to determine request status + +0.2.0 / 2014-09-03 +================== + + * Set `X-Content-Type-Options: nosniff` header + * deps: debug@~2.0.0 + +0.1.0 / 2014-07-16 +================== + + * Respond after request fully read + - prevents hung responses and socket hang ups + * deps: debug@1.0.4 + +0.0.3 / 2014-07-11 +================== + + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.0.2 / 2014-06-19 +================== + + * Handle invalid status codes + +0.0.1 / 2014-06-05 +================== + + * deps: debug@1.0.2 + +0.0.0 / 2014-06-05 +================== + + * Extracted from connect/express diff --git a/5-1/service/node_modules/express/node_modules/finalhandler/LICENSE b/5-1/service/node_modules/express/node_modules/finalhandler/LICENSE new file mode 100644 index 0000000..b60a5ad --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/finalhandler/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-1/service/node_modules/express/node_modules/finalhandler/README.md b/5-1/service/node_modules/express/node_modules/finalhandler/README.md new file mode 100644 index 0000000..6b171d4 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/finalhandler/README.md @@ -0,0 +1,133 @@ +# finalhandler + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js function to invoke as the final step to respond to HTTP request. + +## Installation + +```sh +$ npm install finalhandler +``` + +## API + +```js +var finalhandler = require('finalhandler') +``` + +### finalhandler(req, res, [options]) + +Returns function to be invoked as the final step for the given `req` and `res`. +This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will +write out a 404 response to the `res`. If it is truthy, an error response will +be written out to the `res`, and `res.statusCode` is set from `err.status`. + +The final handler will also unpipe anything from `req` when it is invoked. + +#### options.env + +By default, the environment is determined by `NODE_ENV` variable, but it can be +overridden by this option. + +#### options.onerror + +Provide a function to be called with the `err` when it exists. Can be used for +writing errors to a central location without excessive function generation. Called +as `onerror(err, req, res)`. + +## Examples + +### always 404 + +```js +var finalhandler = require('finalhandler') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + done() +}) + +server.listen(3000) +``` + +### perform simple action + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) +``` + +### use with middleware-style functions + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +var serve = serveStatic('public') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + serve(req, res, done) +}) + +server.listen(3000) +``` + +### keep log of all errors + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res, {onerror: logerror}) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) + +function logerror(err) { + console.error(err.stack || err.toString()) +} +``` + +## License + +[MIT](LICENSE) + +[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 +[node-url]: http://nodejs.org/download/ +[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 +[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg +[downloads-url]: https://npmjs.org/package/finalhandler diff --git a/5-1/service/node_modules/express/node_modules/finalhandler/index.js b/5-1/service/node_modules/express/node_modules/finalhandler/index.js new file mode 100644 index 0000000..0de7c6b --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/finalhandler/index.js @@ -0,0 +1,151 @@ +/*! + * finalhandler + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('finalhandler') +var escapeHtml = require('escape-html') +var http = require('http') +var onFinished = require('on-finished') +var unpipe = require('unpipe') + +/** + * Module variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished + +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler(req, res, options) { + var opts = options || {} + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + + return function (err) { + var status = res.statusCode + + // ignore 404 on in-flight response + if (!err && res._header) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect err.statusCode + if (err.statusCode) { + status = err.statusCode + } + + // respect err.status + if (err.status) { + status = err.status + } + + // default status code to 500 + if (!status || status < 400) { + status = 500 + } + + // production gets a basic error message + var msg = env === 'production' + ? http.STATUS_CODES[status] + : err.stack || err.toString() + msg = escapeHtml(msg) + .replace(/\n/g, '
') + .replace(/ /g, '  ') + '\n' + } else { + status = 404 + msg = 'Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl || req.url) + '\n' + } + + debug('default %s', status) + + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } + + // cannot actually respond + if (res._header) { + return req.socket.destroy() + } + + send(req, res, status, msg) + } +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {string} body + * @private + */ + +function send(req, res, status, body) { + function write() { + res.statusCode = status + + // security header for content sniffing + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() +} diff --git a/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md b/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md new file mode 100644 index 0000000..85e0f8d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE b/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE new file mode 100644 index 0000000..aed0138 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md b/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md new file mode 100644 index 0000000..e536ad2 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js b/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js new file mode 100644 index 0000000..15c3d97 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json b/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json new file mode 100644 index 0000000..4af1b49 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json @@ -0,0 +1,59 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/unpipe.git" + }, + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "d2df901c06487430e78dca62b6edb8bb2fc5e99d", + "bugs": { + "url": "https://github.com/stream-utils/unpipe/issues" + }, + "homepage": "https://github.com/stream-utils/unpipe", + "_id": "unpipe@1.0.0", + "_shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "_from": "unpipe@>=1.0.0 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "tarball": "http://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/finalhandler/package.json b/5-1/service/node_modules/express/node_modules/finalhandler/package.json new file mode 100644 index 0000000..0afe7fc --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/finalhandler/package.json @@ -0,0 +1,81 @@ +{ + "name": "finalhandler", + "description": "Node.js final http responder", + "version": "0.4.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/finalhandler.git" + }, + "dependencies": { + "debug": "~2.2.0", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "unpipe": "~1.0.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "2.3.4", + "readable-stream": "2.0.4", + "supertest": "1.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "ac2036774059eb93dbac8475580e52433204d4d4", + "bugs": { + "url": "https://github.com/pillarjs/finalhandler/issues" + }, + "homepage": "https://github.com/pillarjs/finalhandler", + "_id": "finalhandler@0.4.1", + "_shasum": "85a17c6c59a94717d262d61230d4b0ebe3d4a14d", + "_from": "finalhandler@0.4.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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "85a17c6c59a94717d262d61230d4b0ebe3d4a14d", + "tarball": "http://registry.npmjs.org/finalhandler/-/finalhandler-0.4.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-0.4.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/fresh/HISTORY.md b/5-1/service/node_modules/express/node_modules/fresh/HISTORY.md new file mode 100644 index 0000000..3c95fbb --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/fresh/HISTORY.md @@ -0,0 +1,38 @@ +0.3.0 / 2015-05-12 +================== + + * Add weak `ETag` matching support + +0.2.4 / 2014-09-07 +================== + + * Support Node.js 0.6 + +0.2.3 / 2014-09-07 +================== + + * Move repository to jshttp + +0.2.2 / 2014-02-19 +================== + + * Revert "Fix for blank page on Safari reload" + +0.2.1 / 2014-01-29 +================== + + * Fix for blank page on Safari reload + +0.2.0 / 2013-08-11 +================== + + * Return stale for `Cache-Control: no-cache` + +0.1.0 / 2012-06-15 +================== + * Add `If-None-Match: *` support + +0.0.1 / 2012-06-10 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/fresh/LICENSE b/5-1/service/node_modules/express/node_modules/fresh/LICENSE new file mode 100644 index 0000000..f527394 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/fresh/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/fresh/README.md b/5-1/service/node_modules/express/node_modules/fresh/README.md new file mode 100644 index 0000000..0813e30 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/fresh/README.md @@ -0,0 +1,58 @@ +# fresh + +[![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] + +HTTP response freshness testing + +## Installation + +``` +$ npm install fresh +``` + +## API + +```js +var fresh = require('fresh') +``` + +### fresh(req, res) + + Check freshness of `req` and `res` headers. + + When the cache is "fresh" __true__ is returned, + otherwise __false__ is returned to indicate that + the cache is now stale. + +## Example + +```js +var req = { 'if-none-match': 'tobi' }; +var res = { 'etag': 'luna' }; +fresh(req, res); +// => false + +var req = { 'if-none-match': 'tobi' }; +var res = { 'etag': 'tobi' }; +fresh(req, res); +// => true +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/fresh.svg +[npm-url]: https://npmjs.org/package/fresh +[node-version-image]: https://img.shields.io/node/v/fresh.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg +[travis-url]: https://travis-ci.org/jshttp/fresh +[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master +[downloads-image]: https://img.shields.io/npm/dm/fresh.svg +[downloads-url]: https://npmjs.org/package/fresh diff --git a/5-1/service/node_modules/express/node_modules/fresh/index.js b/5-1/service/node_modules/express/node_modules/fresh/index.js new file mode 100644 index 0000000..a900873 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/fresh/index.js @@ -0,0 +1,57 @@ + +/** + * Expose `fresh()`. + */ + +module.exports = fresh; + +/** + * Check freshness of `req` and `res` headers. + * + * When the cache is "fresh" __true__ is returned, + * otherwise __false__ is returned to indicate that + * the cache is now stale. + * + * @param {Object} req + * @param {Object} res + * @return {Boolean} + * @api public + */ + +function fresh(req, res) { + // defaults + var etagMatches = true; + var notModified = true; + + // fields + var modifiedSince = req['if-modified-since']; + var noneMatch = req['if-none-match']; + var lastModified = res['last-modified']; + var etag = res['etag']; + var cc = req['cache-control']; + + // unconditional request + if (!modifiedSince && !noneMatch) return false; + + // check for no-cache cache request directive + if (cc && cc.indexOf('no-cache') !== -1) return false; + + // parse if-none-match + if (noneMatch) noneMatch = noneMatch.split(/ *, */); + + // if-none-match + if (noneMatch) { + etagMatches = noneMatch.some(function (match) { + return match === '*' || match === etag || match === 'W/' + etag; + }); + } + + // if-modified-since + if (modifiedSince) { + modifiedSince = new Date(modifiedSince); + lastModified = new Date(lastModified); + notModified = lastModified <= modifiedSince; + } + + return !! (etagMatches && notModified); +} diff --git a/5-1/service/node_modules/express/node_modules/fresh/package.json b/5-1/service/node_modules/express/node_modules/fresh/package.json new file mode 100644 index 0000000..74332c4 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/fresh/package.json @@ -0,0 +1,87 @@ +{ + "name": "fresh", + "description": "HTTP response freshness testing", + "version": "0.3.0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "fresh", + "http", + "conditional", + "cache" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/fresh.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "14616c9748368ca08cd6a955dd88ab659b778634", + "bugs": { + "url": "https://github.com/jshttp/fresh/issues" + }, + "homepage": "https://github.com/jshttp/fresh", + "_id": "fresh@0.3.0", + "_shasum": "651f838e22424e7566de161d8358caa199f83d4f", + "_from": "fresh@0.3.0", + "_npmVersion": "1.4.28", + "_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": "651f838e22424e7566de161d8358caa199f83d4f", + "tarball": "http://registry.npmjs.org/fresh/-/fresh-0.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/merge-descriptors/HISTORY.md b/5-1/service/node_modules/express/node_modules/merge-descriptors/HISTORY.md new file mode 100644 index 0000000..486771f --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/merge-descriptors/HISTORY.md @@ -0,0 +1,21 @@ +1.0.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.0.0 / 2015-03-01 +================== + + * Add option to only add new descriptors + * Add simple argument validation + * Add jsdoc to source file + +0.0.2 / 2013-12-14 +================== + + * Move repository to `component` organization + +0.0.1 / 2013-10-29 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/merge-descriptors/LICENSE b/5-1/service/node_modules/express/node_modules/merge-descriptors/LICENSE new file mode 100644 index 0000000..274bfd8 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/merge-descriptors/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 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 +'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/5-1/service/node_modules/express/node_modules/merge-descriptors/README.md b/5-1/service/node_modules/express/node_modules/merge-descriptors/README.md new file mode 100644 index 0000000..d593c0e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/merge-descriptors/README.md @@ -0,0 +1,48 @@ +# Merge Descriptors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Merge objects using descriptors. + +```js +var thing = { + get name() { + return 'jon' + } +} + +var animal = { + +} + +merge(animal, thing) + +animal.name === 'jon' +``` + +## API + +### merge(destination, source) + +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 + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/merge-descriptors.svg +[npm-url]: https://npmjs.org/package/merge-descriptors +[travis-image]: https://img.shields.io/travis/component/merge-descriptors/master.svg +[travis-url]: https://travis-ci.org/component/merge-descriptors +[coveralls-image]: https://img.shields.io/coveralls/component/merge-descriptors/master.svg +[coveralls-url]: https://coveralls.io/r/component/merge-descriptors?branch=master +[downloads-image]: https://img.shields.io/npm/dm/merge-descriptors.svg +[downloads-url]: https://npmjs.org/package/merge-descriptors diff --git a/5-1/service/node_modules/express/node_modules/merge-descriptors/index.js b/5-1/service/node_modules/express/node_modules/merge-descriptors/index.js new file mode 100644 index 0000000..573b132 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/merge-descriptors/index.js @@ -0,0 +1,60 @@ +/*! + * merge-descriptors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * 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 +} diff --git a/5-1/service/node_modules/express/node_modules/merge-descriptors/package.json b/5-1/service/node_modules/express/node_modules/merge-descriptors/package.json new file mode 100644 index 0000000..a65d2e8 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/merge-descriptors/package.json @@ -0,0 +1,138 @@ +{ + "name": "merge-descriptors", + "description": "Merge objects using descriptors", + "version": "1.0.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Mike Grabowski", + "email": "grabbou@gmail.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/component/merge-descriptors.git" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --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": "f26c49c3b423b0b2ac31f6e32a84e1632f2d7ac2", + "bugs": { + "url": "https://github.com/component/merge-descriptors/issues" + }, + "homepage": "https://github.com/component/merge-descriptors", + "_id": "merge-descriptors@1.0.1", + "_shasum": "b00aaa556dd8b44568150ec9d1b953f3f90cbb61", + "_from": "merge-descriptors@1.0.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "anthonyshort", + "email": "antshort@gmail.com" + }, + { + "name": "clintwood", + "email": "clint@anotherway.co.za" + }, + { + "name": "dfcreative", + "email": "df.creative@gmail.com" + }, + { + "name": "dominicbarnes", + "email": "dominic@dbarnes.info" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "ianstormtaylor", + "email": "ian@ianstormtaylor.com" + }, + { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + { + "name": "mattmueller", + "email": "mattmuelle@gmail.com" + }, + { + "name": "queckezz", + "email": "fabian.eichenberger@gmail.com" + }, + { + "name": "stephenmathieson", + "email": "me@stephenmathieson.com" + }, + { + "name": "thehydroimpulse", + "email": "dnfagnan@gmail.com" + }, + { + "name": "timaschew", + "email": "timaschew@gmail.com" + }, + { + "name": "timoxley", + "email": "secoif@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + { + "name": "trevorgerhardt", + "email": "trevorgerhardt@gmail.com" + }, + { + "name": "yields", + "email": "yields@icloud.com" + } + ], + "dist": { + "shasum": "b00aaa556dd8b44568150ec9d1b953f3f90cbb61", + "tarball": "http://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/methods/HISTORY.md b/5-1/service/node_modules/express/node_modules/methods/HISTORY.md new file mode 100644 index 0000000..c0ecf07 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/methods/HISTORY.md @@ -0,0 +1,29 @@ +1.1.2 / 2016-01-17 +================== + + * perf: enable strict mode + +1.1.1 / 2014-12-30 +================== + + * Improve `browserify` support + +1.1.0 / 2014-07-05 +================== + + * Add `CONNECT` method + +1.0.1 / 2014-06-02 +================== + + * Fix module to work with harmony transform + +1.0.0 / 2014-05-08 +================== + + * Add `PURGE` method + +0.1.0 / 2013-10-28 +================== + + * Add `http.METHODS` support diff --git a/5-1/service/node_modules/express/node_modules/methods/LICENSE b/5-1/service/node_modules/express/node_modules/methods/LICENSE new file mode 100644 index 0000000..220dc1a --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/methods/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013-2014 TJ Holowaychuk +Copyright (c) 2015-2016 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/5-1/service/node_modules/express/node_modules/methods/README.md b/5-1/service/node_modules/express/node_modules/methods/README.md new file mode 100644 index 0000000..672a32b --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/methods/README.md @@ -0,0 +1,51 @@ +# Methods + +[![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] + +HTTP verbs that Node.js core's HTTP parser supports. + +This module provides an export that is just like `http.METHODS` from Node.js core, +with the following differences: + + * All method names are lower-cased. + * Contains a fallback list of methods for Node.js versions that do not have a + `http.METHODS` export (0.10 and lower). + * Provides the fallback list when using tools like `browserify` without pulling + in the `http` shim module. + +## Install + +```bash +$ npm install methods +``` + +## API + +```js +var methods = require('methods') +``` + +### methods + +This is an array of lower-cased method names that Node.js supports. If Node.js +provides the `http.METHODS` export, then this is the same array lower-cased, +otherwise it is a snapshot of the verbs from Node.js 0.10. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat +[npm-url]: https://npmjs.org/package/methods +[node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/methods +[coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master +[downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat +[downloads-url]: https://npmjs.org/package/methods diff --git a/5-1/service/node_modules/express/node_modules/methods/index.js b/5-1/service/node_modules/express/node_modules/methods/index.js new file mode 100644 index 0000000..667a50b --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/methods/index.js @@ -0,0 +1,69 @@ +/*! + * methods + * Copyright(c) 2013-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var http = require('http'); + +/** + * Module exports. + * @public + */ + +module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); + +/** + * Get the current Node.js methods. + * @private + */ + +function getCurrentNodeMethods() { + return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { + return method.toLowerCase(); + }); +} + +/** + * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * @private + */ + +function getBasicNodeMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect' + ]; +} diff --git a/5-1/service/node_modules/express/node_modules/methods/package.json b/5-1/service/node_modules/express/node_modules/methods/package.json new file mode 100644 index 0000000..fd072fc --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/methods/package.json @@ -0,0 +1,88 @@ +{ + "name": "methods", + "description": "HTTP methods that node supports", + "version": "1.1.2", + "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+https://github.com/jshttp/methods.git" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE" + ], + "engines": { + "node": ">= 0.6" + }, + "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/" + }, + "browser": { + "http": false + }, + "keywords": [ + "http", + "methods" + ], + "gitHead": "25d257d913f1b94bd2d73581521ff72c81469140", + "bugs": { + "url": "https://github.com/jshttp/methods/issues" + }, + "homepage": "https://github.com/jshttp/methods", + "_id": "methods@1.1.2", + "_shasum": "5529a4d67654134edcc5266656835b0f851afcee", + "_from": "methods@>=1.1.2 <1.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "5529a4d67654134edcc5266656835b0f851afcee", + "tarball": "http://registry.npmjs.org/methods/-/methods-1.1.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/on-finished/HISTORY.md b/5-1/service/node_modules/express/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000..98ff0e9 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/on-finished/HISTORY.md @@ -0,0 +1,88 @@ +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +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 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/on-finished/LICENSE b/5-1/service/node_modules/express/node_modules/on-finished/LICENSE new file mode 100644 index 0000000..5931fd2 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/on-finished/README.md b/5-1/service/node_modules/express/node_modules/on-finished/README.md new file mode 100644 index 0000000..a0e1157 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/on-finished/README.md @@ -0,0 +1,154 @@ +# on-finished + +[![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] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to 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, res) { + // clean up open fds, etc. + // err contains the error is request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to 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 = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg +[downloads-url]: https://npmjs.org/package/on-finished diff --git a/5-1/service/node_modules/express/node_modules/on-finished/index.js b/5-1/service/node_modules/express/node_modules/on-finished/index.js new file mode 100644 index 0000000..9abd98f --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/on-finished/index.js @@ -0,0 +1,196 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener(msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish(error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket) + callback(socket) + } +} diff --git a/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE b/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md b/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js b/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json b/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json new file mode 100644 index 0000000..1d223fb --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json @@ -0,0 +1,64 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jonathanong/ee-first.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "512e0ce4cc3643f603708f965a97b61b1a9c0441", + "bugs": { + "url": "https://github.com/jonathanong/ee-first/issues" + }, + "homepage": "https://github.com/jonathanong/ee-first", + "_id": "ee-first@1.1.1", + "_shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "_from": "ee-first@1.1.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/on-finished/package.json b/5-1/service/node_modules/express/node_modules/on-finished/package.json new file mode 100644 index 0000000..7b2ebdd --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/on-finished/package.json @@ -0,0 +1,71 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.3.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/on-finished.git" + }, + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "34babcb58126a416fcf5205768204f2e12699dda", + "bugs": { + "url": "https://github.com/jshttp/on-finished/issues" + }, + "homepage": "https://github.com/jshttp/on-finished", + "_id": "on-finished@2.3.0", + "_shasum": "20f1336481b083cd75337992a16971aa2d906947", + "_from": "on-finished@>=2.3.0 <2.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "20f1336481b083cd75337992a16971aa2d906947", + "tarball": "http://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/parseurl/HISTORY.md b/5-1/service/node_modules/express/node_modules/parseurl/HISTORY.md new file mode 100644 index 0000000..395041e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/parseurl/HISTORY.md @@ -0,0 +1,47 @@ +1.3.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.3.0 / 2014-08-09 +================== + + * Add `parseurl.original` for parsing `req.originalUrl` with fallback + * Return `undefined` if `req.url` is `undefined` + +1.2.0 / 2014-07-21 +================== + + * Cache URLs based on original value + * Remove no-longer-needed URL mis-parse work-around + * Simplify the "fast-path" `RegExp` + +1.1.3 / 2014-07-08 +================== + + * Fix typo + +1.1.2 / 2014-07-08 +================== + + * Seriously fix Node.js 0.8 compatibility + +1.1.1 / 2014-07-08 +================== + + * Fix Node.js 0.8 compatibility + +1.1.0 / 2014-07-08 +================== + + * Incorporate URL href-only parse fast-path + +1.0.1 / 2014-03-08 +================== + + * Add missing `require` + +1.0.0 / 2014-03-08 +================== + + * Genesis from `connect` diff --git a/5-1/service/node_modules/express/node_modules/parseurl/LICENSE b/5-1/service/node_modules/express/node_modules/parseurl/LICENSE new file mode 100644 index 0000000..ec7dfe7 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/parseurl/LICENSE @@ -0,0 +1,24 @@ + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/parseurl/README.md b/5-1/service/node_modules/express/node_modules/parseurl/README.md new file mode 100644 index 0000000..f4796eb --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/parseurl/README.md @@ -0,0 +1,120 @@ +# parseurl + +[![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] + +Parse a URL with memoization. + +## Install + +```bash +$ npm install parseurl +``` + +## API + +```js +var parseurl = require('parseurl') +``` + +### parseurl(req) + +Parse the URL of the given request object (looks at the `req.url` property) +and return the result. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.url` does +not change will return a cached parsed object, rather than parsing again. + +### parseurl.original(req) + +Parse the original URL of the given request object and return the result. +This works by trying to parse `req.originalUrl` if it is a string, otherwise +parses `req.url`. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.originalUrl` +does not change will return a cached parsed object, rather than parsing again. + +## Benchmark + +```bash +$ npm run-script bench + +> parseurl@1.3.1 bench nodejs-parseurl +> node benchmark/index.js + +> node benchmark/fullurl.js + + Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 1,290,780 ops/sec ±0.46% (195 runs sampled) + nativeurl x 56,401 ops/sec ±0.22% (196 runs sampled) + parseurl x 55,231 ops/sec ±0.22% (194 runs sampled) + +> node benchmark/pathquery.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 1,986,668 ops/sec ±0.27% (190 runs sampled) + nativeurl x 98,740 ops/sec ±0.21% (195 runs sampled) + parseurl x 2,628,171 ops/sec ±0.36% (195 runs sampled) + +> node benchmark/samerequest.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 2,184,468 ops/sec ±0.40% (194 runs sampled) + nativeurl x 99,437 ops/sec ±0.71% (194 runs sampled) + parseurl x 10,498,005 ops/sec ±0.61% (186 runs sampled) + +> node benchmark/simplepath.js + + Parsing URL "/foo/bar" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 4,535,825 ops/sec ±0.27% (191 runs sampled) + nativeurl x 98,769 ops/sec ±0.54% (191 runs sampled) + parseurl x 4,164,865 ops/sec ±0.34% (192 runs sampled) + +> node benchmark/slash.js + + Parsing URL "/" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 4,908,405 ops/sec ±0.42% (191 runs sampled) + nativeurl x 100,945 ops/sec ±0.59% (188 runs sampled) + parseurl x 4,333,208 ops/sec ±0.27% (194 runs sampled) +``` + +## License + + [MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/parseurl.svg +[npm-url]: https://npmjs.org/package/parseurl +[node-version-image]: https://img.shields.io/node/v/parseurl.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/pillarjs/parseurl/master.svg +[travis-url]: https://travis-ci.org/pillarjs/parseurl +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/parseurl/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master +[downloads-image]: https://img.shields.io/npm/dm/parseurl.svg +[downloads-url]: https://npmjs.org/package/parseurl diff --git a/5-1/service/node_modules/express/node_modules/parseurl/index.js b/5-1/service/node_modules/express/node_modules/parseurl/index.js new file mode 100644 index 0000000..56cc6ec --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/parseurl/index.js @@ -0,0 +1,138 @@ +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var url = require('url') +var parse = url.parse +var Url = url.Url + +/** + * Pattern for a simple path case. + * See: https://github.com/joyent/node/pull/7878 + */ + +var simplePathRegExp = /^(\/\/?(?!\/)[^\?#\s]*)(\?[^#\s]*)?$/ + +/** + * Exports. + */ + +module.exports = parseurl +module.exports.original = originalurl + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @api public + */ + +function parseurl(req) { + var url = req.url + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return req._parsedUrl = parsed +}; + +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @api public + */ + +function originalurl(req) { + var url = req.originalUrl + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return req._parsedOriginalUrl = parsed +}; + +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @api private + */ + +function fastparse(str) { + // Try fast path regexp + // See: https://github.com/joyent/node/pull/7878 + var simplePath = typeof str === 'string' && simplePathRegExp.exec(str) + + // Construct simple URL + if (simplePath) { + var pathname = simplePath[1] + var search = simplePath[2] || null + var url = Url !== undefined + ? new Url() + : {} + url.path = str + url.href = str + url.pathname = pathname + url.search = search + url.query = search && search.substr(1) + + return url + } + + return parse(str) +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @api private + */ + +function fresh(url, parsedUrl) { + return typeof parsedUrl === 'object' + && parsedUrl !== null + && (Url === undefined || parsedUrl instanceof Url) + && parsedUrl._raw === url +} diff --git a/5-1/service/node_modules/express/node_modules/parseurl/package.json b/5-1/service/node_modules/express/node_modules/parseurl/package.json new file mode 100644 index 0000000..7ba6287 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/parseurl/package.json @@ -0,0 +1,89 @@ +{ + "name": "parseurl", + "description": "parse a url with memoization", + "version": "1.3.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/parseurl.git" + }, + "license": "MIT", + "devDependencies": { + "benchmark": "2.0.0", + "beautify-benchmark": "0.2.4", + "fast-url-parser": "1.1.3", + "istanbul": "0.4.2", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --check-leaks --bail --reporter spec test/", + "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": "6d22d376d75b927ab2b5347ce3a1d6735133dd43", + "bugs": { + "url": "https://github.com/pillarjs/parseurl/issues" + }, + "homepage": "https://github.com/pillarjs/parseurl", + "_id": "parseurl@1.3.1", + "_shasum": "c8ab8c9223ba34888aa64a297b28853bec18da56", + "_from": "parseurl@>=1.3.1 <1.4.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" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "c8ab8c9223ba34888aa64a297b28853bec18da56", + "tarball": "http://registry.npmjs.org/parseurl/-/parseurl-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/path-to-regexp/History.md b/5-1/service/node_modules/express/node_modules/path-to-regexp/History.md new file mode 100644 index 0000000..7f65878 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/path-to-regexp/History.md @@ -0,0 +1,36 @@ +0.1.7 / 2015-07-28 +================== + + * Fixed regression with escaped round brackets and matching groups. + +0.1.6 / 2015-06-19 +================== + + * Replace `index` feature by outputting all parameters, unnamed and named. + +0.1.5 / 2015-05-08 +================== + + * Add an index property for position in match result. + +0.1.4 / 2015-03-05 +================== + + * Add license information + +0.1.3 / 2014-07-06 +================== + + * Better array support + * Improved support for trailing slash in non-ending mode + +0.1.0 / 2014-03-06 +================== + + * add options.end + +0.0.2 / 2013-02-10 +================== + + * Update to match current express + * add .license property to component.json diff --git a/5-1/service/node_modules/express/node_modules/path-to-regexp/LICENSE b/5-1/service/node_modules/express/node_modules/path-to-regexp/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/path-to-regexp/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/5-1/service/node_modules/express/node_modules/path-to-regexp/Readme.md b/5-1/service/node_modules/express/node_modules/path-to-regexp/Readme.md new file mode 100644 index 0000000..95452a6 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,35 @@ +# Path-to-RegExp + +Turn an Express-style path string such as `/user/:name` into a regular expression. + +**Note:** This is a legacy branch. You should upgrade to `1.x`. + +## Usage + +```javascript +var pathToRegexp = require('path-to-regexp'); +``` + +### pathToRegexp(path, keys, options) + + - **path** A string in the express format, an array of such strings, or a regular expression + - **keys** An array to be populated with the keys present in the url. Once the function completes, this will be an array of strings. + - **options** + - **options.sensitive** Defaults to false, set this to true to make routes case sensitive + - **options.strict** Defaults to false, set this to true to make the trailing slash matter. + - **options.end** Defaults to true, set this to false to only match the prefix of the URL. + +```javascript +var keys = []; +var exp = pathToRegexp('/foo/:bar', keys); +//keys = ['bar'] +//exp = /^\/foo\/(?:([^\/]+?))\/?$/i +``` + +## Live Demo + +You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/). + +## License + + MIT diff --git a/5-1/service/node_modules/express/node_modules/path-to-regexp/index.js b/5-1/service/node_modules/express/node_modules/path-to-regexp/index.js new file mode 100644 index 0000000..500d1da --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/path-to-regexp/index.js @@ -0,0 +1,129 @@ +/** + * Expose `pathtoRegexp`. + */ + +module.exports = pathtoRegexp; + +/** + * Match matching groups in a regular expression. + */ +var MATCHING_GROUP_REGEXP = /\((?!\?)/g; + +/** + * Normalize the given path string, + * returning a regular expression. + * + * An empty array should be passed, + * which will contain the placeholder + * key names. For example "/user/:id" will + * then contain ["id"]. + * + * @param {String|RegExp|Array} path + * @param {Array} keys + * @param {Object} options + * @return {RegExp} + * @api private + */ + +function pathtoRegexp(path, keys, options) { + options = options || {}; + keys = keys || []; + var strict = options.strict; + var end = options.end !== false; + var flags = options.sensitive ? '' : 'i'; + var extraOffset = 0; + var keysOffset = keys.length; + var i = 0; + var name = 0; + var m; + + if (path instanceof RegExp) { + while (m = MATCHING_GROUP_REGEXP.exec(path.source)) { + keys.push({ + name: name++, + optional: false, + offset: m.index + }); + } + + return path; + } + + if (Array.isArray(path)) { + // Map array parts into regexps and return their source. We also pass + // the same keys and options instance into every generation to get + // consistent matching groups before we join the sources together. + path = path.map(function (value) { + return pathtoRegexp(value, keys, options).source; + }); + + return new RegExp('(?:' + path.join('|') + ')', flags); + } + + path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) + .replace(/\/\(/g, '/(?:') + .replace(/([\/\.])/g, '\\$1') + .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) { + slash = slash || ''; + format = format || ''; + capture = capture || '([^\\/' + format + ']+?)'; + optional = optional || ''; + + keys.push({ + name: key, + optional: !!optional, + offset: offset + extraOffset + }); + + var result = '' + + (optional ? '' : slash) + + '(?:' + + format + (optional ? slash : '') + capture + + (star ? '((?:[\\/' + format + '].+?)?)' : '') + + ')' + + optional; + + extraOffset += result.length - match.length; + + return result; + }) + .replace(/\*/g, function (star, index) { + var len = keys.length + + while (len-- > keysOffset && keys[len].offset > index) { + keys[len].offset += 3; // Replacement length minus asterisk length. + } + + return '(.*)'; + }); + + // This is a workaround for handling unnamed matching groups. + while (m = MATCHING_GROUP_REGEXP.exec(path)) { + var escapeCount = 0; + var index = m.index; + + while (path.charAt(--index) === '\\') { + escapeCount++; + } + + // It's possible to escape the bracket. + if (escapeCount % 2 === 1) { + continue; + } + + if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) { + keys.splice(keysOffset + i, 0, { + name: name++, // Unnamed matching groups must be consistently linear. + optional: false, + offset: m.index + }); + } + + i++; + } + + // If the path is non-ending, match until the end or a slash. + path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)')); + + return new RegExp(path, flags); +}; diff --git a/5-1/service/node_modules/express/node_modules/path-to-regexp/package.json b/5-1/service/node_modules/express/node_modules/path-to-regexp/package.json new file mode 100644 index 0000000..118b1e6 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/path-to-regexp/package.json @@ -0,0 +1,185 @@ +{ + "name": "path-to-regexp", + "description": "Express style path to RegExp utility", + "version": "0.1.7", + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "keywords": [ + "express", + "regexp" + ], + "component": { + "scripts": { + "path-to-regexp": "index.js" + } + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/component/path-to-regexp.git" + }, + "devDependencies": { + "mocha": "^1.17.1", + "istanbul": "^0.2.6" + }, + "gitHead": "039118d6c3c186d3f176c73935ca887a32a33d93", + "bugs": { + "url": "https://github.com/component/path-to-regexp/issues" + }, + "homepage": "https://github.com/component/path-to-regexp#readme", + "_id": "path-to-regexp@0.1.7", + "_shasum": "df604178005f522f15eb4490e7247a1bfaa67f8c", + "_from": "path-to-regexp@0.1.7", + "_npmVersion": "2.13.2", + "_nodeVersion": "2.3.3", + "_npmUser": { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "hughsk", + "email": "hughskennedy@gmail.com" + }, + { + "name": "timaschew", + "email": "timaschew@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "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": "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" + }, + { + "name": "dfcreative", + "email": "df.creative@gmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "df604178005f522f15eb4490e7247a1bfaa67f8c", + "tarball": "http://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/HISTORY.md b/5-1/service/node_modules/express/node_modules/proxy-addr/HISTORY.md new file mode 100644 index 0000000..84f11aa --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/HISTORY.md @@ -0,0 +1,80 @@ +1.0.10 / 2015-12-09 +=================== + + * deps: ipaddr.js@1.0.5 + - Fix regression in `isValid` with non-string arguments + +1.0.9 / 2015-12-01 +================== + + * deps: ipaddr.js@1.0.4 + - Fix accepting some invalid IPv6 addresses + - Reject CIDRs with negative or overlong masks + * perf: enable strict mode + +1.0.8 / 2015-05-10 +================== + + * deps: ipaddr.js@1.0.1 + +1.0.7 / 2015-03-16 +================== + + * deps: ipaddr.js@0.1.9 + - Fix OOM on certain inputs to `isValid` + +1.0.6 / 2015-02-01 +================== + + * deps: ipaddr.js@0.1.8 + +1.0.5 / 2015-01-08 +================== + + * deps: ipaddr.js@0.1.6 + +1.0.4 / 2014-11-23 +================== + + * deps: ipaddr.js@0.1.5 + - Fix edge cases with `isValid` + +1.0.3 / 2014-09-21 +================== + + * Use `forwarded` npm module + +1.0.2 / 2014-09-18 +================== + + * Fix a global leak when multiple subnets are trusted + * Support Node.js 0.6 + * deps: ipaddr.js@0.1.3 + +1.0.1 / 2014-06-03 +================== + + * Fix links in npm package + +1.0.0 / 2014-05-08 +================== + + * Add `trust` argument to determine proxy trust on + * Accepts custom function + * Accepts IPv4/IPv6 address(es) + * Accepts subnets + * Accepts pre-defined names + * Add optional `trust` argument to `proxyaddr.all` to + stop at first untrusted + * Add `proxyaddr.compile` to pre-compile `trust` function + to make subsequent calls faster + +0.0.1 / 2014-05-04 +================== + + * Fix bad npm publish + +0.0.0 / 2014-05-04 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/LICENSE b/5-1/service/node_modules/express/node_modules/proxy-addr/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/README.md b/5-1/service/node_modules/express/node_modules/proxy-addr/README.md new file mode 100644 index 0000000..26f7fc0 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/README.md @@ -0,0 +1,137 @@ +# proxy-addr + +[![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] + +Determine address of proxied request + +## Install + +```sh +$ npm install proxy-addr +``` + +## API + +```js +var proxyaddr = require('proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + +```js +proxyaddr(req, function(addr){ return addr === '127.0.0.1' }) +proxyaddr(req, function(addr, i){ return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +proxyaddr(req, ['fe80::/ffc0::']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + +```js +var trust = proxyaddr.compile('localhost') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master +[downloads-image]: https://img.shields.io/npm/dm/proxy-addr.svg +[downloads-url]: https://npmjs.org/package/proxy-addr diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/index.js b/5-1/service/node_modules/express/node_modules/proxy-addr/index.js new file mode 100644 index 0000000..3200efb --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/index.js @@ -0,0 +1,347 @@ +/*! + * proxy-addr + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = proxyaddr; +module.exports.all = alladdrs; +module.exports.compile = compile; + +/** + * Module dependencies. + */ + +var forwarded = require('forwarded'); +var ipaddr = require('ipaddr.js'); + +/** + * Variables. + */ + +var digitre = /^[0-9]+$/; +var isip = ipaddr.isValid; +var parseip = ipaddr.parse; + +/** + * Pre-defined IP ranges. + */ + +var ipranges = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +}; + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @api public + */ + +function alladdrs(req, trust) { + // get addresses + var addrs = forwarded(req); + + if (!trust) { + // Return all addresses + return addrs; + } + + if (typeof trust !== 'function') { + trust = compile(trust); + } + + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue; + + addrs.length = i + 1; + } + + return addrs; +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @api private + */ + +function compile(val) { + if (!val) { + throw new TypeError('argument is required'); + } + + var trust = typeof val === 'string' + ? [val] + : val; + + if (!Array.isArray(trust)) { + throw new TypeError('unsupported trust argument'); + } + + for (var i = 0; i < trust.length; i++) { + val = trust[i]; + + if (!ipranges.hasOwnProperty(val)) { + continue; + } + + // Splice in pre-defined range + val = ipranges[val]; + trust.splice.apply(trust, [i, 1].concat(val)); + i += val.length - 1; + } + + return compileTrust(compileRangeSubnets(trust)); +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @api private + */ + +function compileRangeSubnets(arr) { + var rangeSubnets = new Array(arr.length); + + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]); + } + + return rangeSubnets; +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @api private + */ + +function compileTrust(rangeSubnets) { + // Return optimized function based on length + var len = rangeSubnets.length; + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets); +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @api private + */ + +function parseipNotation(note) { + var ip; + var kind; + var max; + var pos = note.lastIndexOf('/'); + var range; + + ip = pos !== -1 + ? note.substring(0, pos) + : note; + + if (!isip(ip)) { + throw new TypeError('invalid IP address: ' + ip); + } + + ip = parseip(ip); + + kind = ip.kind(); + max = kind === 'ipv6' + ? 128 + : 32; + + range = pos !== -1 + ? note.substring(pos + 1, note.length) + : max; + + if (typeof range !== 'number') { + range = digitre.test(range) + ? parseInt(range, 10) + : isip(range) + ? parseNetmask(range) + : 0; + } + + if (ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address(); + range = range <= max + ? range - 96 + : range; + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note); + } + + return [ip, range]; +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} note + * @api private + */ + +function parseNetmask(netmask) { + var ip = parseip(netmask); + var parts; + var size; + + switch (ip.kind()) { + case 'ipv4': + parts = ip.octets; + size = 8; + break; + case 'ipv6': + parts = ip.parts; + size = 16; + break; + } + + var max = Math.pow(2, size) - 1; + var part; + var range = 0; + + for (var i = 0; i < parts.length; i++) { + part = parts[i] & max; + + if (part === max) { + range += size; + continue; + } + + while (part) { + part = (part << 1) & max; + range += 1; + } + + break; + } + + return range; +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @api public + */ + +function proxyaddr(req, trust) { + if (!req) { + throw new TypeError('req argument is required'); + } + + if (!trust) { + throw new TypeError('trust argument is required'); + } + + var addrs = alladdrs(req, trust); + var addr = addrs[addrs.length - 1]; + + return addr; +} + +/** + * Static trust function to trust nothing. + * + * @api private + */ + +function trustNone() { + return false; +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @api private + */ + +function trustMulti(subnets) { + return function trust(addr) { + if (!isip(addr)) return false; + + var ip = parseip(addr); + var ipv4; + var kind = ip.kind(); + var subnet; + var subnetip; + var subnetkind; + var subnetrange; + var trusted; + + for (var i = 0; i < subnets.length; i++) { + subnet = subnets[i]; + subnetip = subnet[0]; + subnetkind = subnetip.kind(); + subnetrange = subnet[1]; + trusted = ip; + + if (kind !== subnetkind) { + if (kind !== 'ipv6' || subnetkind !== 'ipv4' || !ip.isIPv4MappedAddress()) { + continue; + } + + // Store addr as IPv4 + ipv4 = ipv4 || ip.toIPv4Address(); + trusted = ipv4; + } + + if (trusted.match(subnetip, subnetrange)) return true; + } + + return false; + }; +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @api private + */ + +function trustSingle(subnet) { + var subnetip = subnet[0]; + var subnetkind = subnetip.kind(); + var subnetisipv4 = subnetkind === 'ipv4'; + var subnetrange = subnet[1]; + + return function trust(addr) { + if (!isip(addr)) return false; + + var ip = parseip(addr); + var kind = ip.kind(); + + return kind === subnetkind + ? ip.match(subnetip, subnetrange) + : subnetisipv4 && kind === 'ipv6' && ip.isIPv4MappedAddress() + ? ip.toIPv4Address().match(subnetip, subnetrange) + : false; + }; +} diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md new file mode 100644 index 0000000..97fa1d1 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md @@ -0,0 +1,4 @@ +0.1.0 / 2014-09-21 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md new file mode 100644 index 0000000..2b4988f --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md @@ -0,0 +1,53 @@ +# forwarded + +[![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] + +Parse HTTP X-Forwarded-For header + +## Installation + +```sh +$ npm install forwarded +``` + +## API + +```js +var forwarded = require('forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`. In reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/forwarded.svg?style=flat +[npm-url]: https://npmjs.org/package/forwarded +[node-version-image]: https://img.shields.io/node/v/forwarded.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/forwarded.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/forwarded +[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master +[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg?style=flat +[downloads-url]: https://npmjs.org/package/forwarded diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js new file mode 100644 index 0000000..2f5c340 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js @@ -0,0 +1,35 @@ +/*! + * forwarded + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {Object} req + * @api public + */ + +function forwarded(req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = (req.headers['x-forwarded-for'] || '') + .split(/ *, */) + .filter(Boolean) + .reverse() + var socketAddr = req.connection.remoteAddress + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json new file mode 100644 index 0000000..7d24004 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json @@ -0,0 +1,65 @@ +{ + "name": "forwarded", + "description": "Parse HTTP X-Forwarded-For header", + "version": "0.1.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "x-forwarded-for", + "http", + "req" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/forwarded.git" + }, + "devDependencies": { + "istanbul": "0.3.2", + "mocha": "~1.21.4" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "e9a9faeb3cfaadf40eb57d144fff26bca9b818e8", + "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 <0.2.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", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore new file mode 100644 index 0000000..7a1537b --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore @@ -0,0 +1,2 @@ +.idea +node_modules diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml new file mode 100644 index 0000000..aa3d14a --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml @@ -0,0 +1,10 @@ +language: node_js + +node_js: + - "0.10" + - "0.11" + - "0.12" + - "4.0" + - "4.1" + - "4.2" + - "5" diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile new file mode 100644 index 0000000..7fd355a --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile @@ -0,0 +1,18 @@ +fs = require 'fs' +CoffeeScript = require 'coffee-script' +nodeunit = require 'nodeunit' +UglifyJS = require 'uglify-js' + +task 'build', 'build the JavaScript files from CoffeeScript source', build = (cb) -> + source = fs.readFileSync 'src/ipaddr.coffee' + fs.writeFileSync 'lib/ipaddr.js', CoffeeScript.compile source.toString() + + invoke 'test' + invoke 'compress' + +task 'test', 'run the bundled tests', (cb) -> + nodeunit.reporters.default.run ['test'] + +task 'compress', 'uglify the resulting javascript', (cb) -> + result = UglifyJS.minify('lib/ipaddr.js') + fs.writeFileSync('ipaddr.min.js', result.code) diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE new file mode 100644 index 0000000..3493f0d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011 Peter Zotov + +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/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md new file mode 100644 index 0000000..f4f8776 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md @@ -0,0 +1,161 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +var ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and +`ipaddr.process`. All of them receive a string as a single parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 couterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. +Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); +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"` +(the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with both +IPv6 and IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +var rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "he.net" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. +(Actually, JavaScript mostly does not know about byte buffers. They are emulated with +arrays of numbers, each in range of 0..255.) + +```js +var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them +have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address +for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with +the `::` substitution); the `toNormalizedString()` method will return an address where +all zeroes are explicit. + +For example: + +```js +var addr = ipaddr.parse("2001:0db8::0001"); +addr.toString(); // => "2001:db8::1" +addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +var addr = ipaddr.parse("192.168.1.1"); +addr.octets // => [192, 168, 1, 1] +``` diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json new file mode 100644 index 0000000..bc04ffe --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json @@ -0,0 +1,29 @@ +{ + "name": "ipaddr.js", + "version": "1.0.5", + "homepage": "https://github.com/whitequark/ipaddr.js", + "authors": [ + "whitequark " + ], + "description": "IP address manipulation library in JavaScript (CoffeeScript, actually)", + "main": "lib/ipaddr.js", + "moduleType": [ + "globals", + "node" + ], + "keywords": [ + "javscript", + "ip", + "address", + "ipv4", + "ipv6" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 0000000..ee5179d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.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),r[i]>>o!==t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(e in t)for(i=t[e],!i[0]||i[0]instanceof Array||(i=[i]),a=0,s=i.length;s>a;a++)if(o=i[a],r.match.apply(r,o))return e;return n},t.IPv4=function(){function r(r){var t,n,e;if(4!==r.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(n=0,e=r.length;e>n;n++)if(t=r[n],!(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 n;if(void 0===t&&(n=r,r=n[0],t=n[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}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(o=t.slice(1,6),a=[],r=0,e=o.length;e>r;r++)i=o[r],a.push(n(i));return a}();if(t=r.match(e.longValue)){if(a=n(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,n,e;if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8");for(n=0,e=r.length;e>n;n++)if(t=r[n],!(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,n,e,i,o,a;for(i=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),r=[],n=function(t){return r.push(t)},e=0,o=0,a=i.length;a>o;o++)switch(t=i[o],e){case 0:n("0"===t?"":t),e=1;break;case 1:"0"===t?e=2:n(t);break;case 2:"0"!==t&&(n(""),n(t),e=3);break;case 3:n(t)}return 2===e&&(n(""),n("")),r.join(":")},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],i=this.parts,n=0,e=i.length;e>n;n++)t=i[n],r.push(t>>8),r.push(255&t);return r},r.prototype.toNormalizedString=function(){var r;return 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).join(":")},r.prototype.match=function(r,t){var n;if(void 0===t&&(n=r,r=n[0],t=n[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,n,e;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=this.parts.slice(-2),r=e[0],n=e[1],new t.IPv4([r>>8,255&r,n>>8,255&n])},r}(),i="(?:[0-9a-f]+::?)+",o={"native":new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+(""+n+"\\."+n+"\\."+n+"\\."+n+"$"),"i")},r=function(r,t){var n,e,i,o,a;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for(n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(a=t-n,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,n,e,o;for(e=r.split(":"),o=[],t=0,n=e.length;n>t;t++)i=e[t],o.push(parseInt(i,16));return o}()},t.IPv6.parser=function(t){var n,e;return t.match(o["native"])?r(t,8):(n=t.match(o.transitional))&&(e=r(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},t.IPv4.isIPv4=t.IPv6.isIPv6=function(r){return null!==this.parser(r)},t.IPv4.isValid=function(r){var t;try{return new this(this.parser(r)),!0}catch(n){return t=n,!1}},t.IPv6.isValid=function(r){var t;if("string"==typeof r&&-1===r.indexOf(":"))return!1;try{return new this(this.parser(r)),!0}catch(n){return t=n,!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=function(r){var t,n;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&32>=t))return[this.parse(n[1]),t];throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv6.parseCIDR=function(r){var t,n;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&128>=t))return[this.parse(n[1]),t];throw new Error("ipaddr: string is not formatted like an IPv6 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 n;try{return t.IPv6.parseCIDR(r)}catch(e){n=e;try{return t.IPv4.parseCIDR(r)}catch(e){throw n=e,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/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js new file mode 100644 index 0000000..ef179b4 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js @@ -0,0 +1,467 @@ +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root; + + ipaddr = {}; + + root = this; + + if ((typeof module !== "undefined" && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } + + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var rangeName, rangeSubnets, subnet, _i, _len; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (_i = 0, _len = rangeSubnets.length; _i < _len; _i++) { + subnet = rangeSubnets[_i]; + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + return defaultName; + }; + + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var octet, _i, _len; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (_i = 0, _len = octets.length; _i < _len; _i++) { + octet = octets[_i]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet is a byte"); + } + } + this.octets = octets; + } + + IPv4.prototype.kind = function() { + return 'ipv4'; + }; + + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + + 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"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; + + return IPv4; + + })(); + + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; + + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var _i, _len, _ref, _results; + _ref = match.slice(1, 6); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(parseIntAuto(part)); + } + return _results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var _i, _results; + _results = []; + for (shift = _i = 0; _i <= 24; shift = _i += 8) { + _results.push((value >> shift) & 0xff); + } + return _results; + })()).reverse(); + } else { + return null; + } + }; + + ipaddr.IPv6 = (function() { + function IPv6(parts) { + var part, _i, _len; + if (parts.length !== 8) { + throw new Error("ipaddr: ipv6 part count should be 8"); + } + for (_i = 0, _len = parts.length; _i < _len; _i++) { + part = parts[_i]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit to two octets"); + } + } + this.parts = parts; + } + + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + + IPv6.prototype.toString = function() { + var compactStringParts, part, pushPart, state, stringParts, _i, _len; + stringParts = (function() { + var _i, _len, _ref, _results; + _ref = this.parts; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(part.toString(16)); + } + return _results; + }).call(this); + compactStringParts = []; + pushPart = function(part) { + return compactStringParts.push(part); + }; + state = 0; + for (_i = 0, _len = stringParts.length; _i < _len; _i++) { + part = stringParts[_i]; + switch (state) { + case 0: + if (part === '0') { + pushPart(''); + } else { + pushPart(part); + } + state = 1; + break; + case 1: + if (part === '0') { + state = 2; + } else { + pushPart(part); + } + break; + case 2: + if (part !== '0') { + pushPart(''); + pushPart(part); + state = 3; + } + break; + case 3: + pushPart(part); + } + } + if (state === 2) { + pushPart(''); + pushPart(''); + } + return compactStringParts.join(":"); + }; + + IPv6.prototype.toByteArray = function() { + var bytes, part, _i, _len, _ref; + bytes = []; + _ref = this.parts; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; + + IPv6.prototype.toNormalizedString = function() { + var part; + return ((function() { + var _i, _len, _ref, _results; + _ref = this.parts; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(part.toString(16)); + } + return _results; + }).call(this)).join(":"); + }; + + 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"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; + + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; + + IPv6.prototype.toIPv4Address = function() { + var high, low, _ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + _ref = this.parts.slice(-2), high = _ref[0], low = _ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + return IPv6; + + })(); + + ipv6Part = "(?:[0-9a-f]+::?)+"; + + ipv6Regexes = { + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + ("" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$"), 'i') + }; + + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + return (function() { + var _i, _len, _ref, _results; + _ref = string.split(":"); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(parseInt(part, 16)); + } + return _results; + })(); + }; + + ipaddr.IPv6.parser = function(string) { + var match, parts; + if (string.match(ipv6Regexes['native'])) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + parts = expandIPv6(match[1].slice(0, -1), 6); + if (parts) { + parts.push(parseInt(match[2]) << 8 | parseInt(match[3])); + parts.push(parseInt(match[4]) << 8 | parseInt(match[5])); + return parts; + } + } + return null; + }; + + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (_error) { + e = _error; + return false; + } + }; + + ipaddr.IPv6.isValid = function(string) { + var e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + new this(this.parser(string)); + return true; + } catch (_error) { + e = _error; + return false; + } + }; + + ipaddr.IPv4.parse = ipaddr.IPv6.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + return [this.parse(match[1]), maskLength]; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + return [this.parse(match[1]), maskLength]; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + + 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); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + +}).call(this); diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json new file mode 100644 index 0000000..6b61f32 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json @@ -0,0 +1,60 @@ +{ + "name": "ipaddr.js", + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "version": "1.0.5", + "author": { + "name": "whitequark", + "email": "whitequark@whitequark.org" + }, + "directories": { + "lib": "./lib" + }, + "dependencies": {}, + "devDependencies": { + "coffee-script": "~1.6", + "nodeunit": ">=0.8.2 <0.8.7", + "uglify-js": "latest" + }, + "scripts": { + "test": "cake build test" + }, + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "repository": { + "type": "git", + "url": "git://github.com/whitequark/ipaddr.js.git" + }, + "main": "./lib/ipaddr", + "engines": { + "node": ">= 0.10" + }, + "license": "MIT", + "gitHead": "46438c8bfa187505b7007a277f09a4a9e73d5686", + "bugs": { + "url": "https://github.com/whitequark/ipaddr.js/issues" + }, + "_id": "ipaddr.js@1.0.5", + "_shasum": "5fa78cf301b825c78abc3042d812723049ea23c7", + "_from": "ipaddr.js@1.0.5", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "whitequark", + "email": "whitequark@whitequark.org" + }, + "maintainers": [ + { + "name": "whitequark", + "email": "whitequark@whitequark.org" + } + ], + "dist": { + "shasum": "5fa78cf301b825c78abc3042d812723049ea23c7", + "tarball": "http://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.0.5.tgz" + }, + "_resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.0.5.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/whitequark/ipaddr.js#readme" +} diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee new file mode 100644 index 0000000..550174f --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee @@ -0,0 +1,396 @@ +# Define the main object +ipaddr = {} + +root = this + +# Export for both the CommonJS and browser-like environment +if module? && module.exports + module.exports = ipaddr +else + root['ipaddr'] = ipaddr + +# A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher. +matchCIDR = (first, second, partSize, cidrBits) -> + if first.length != second.length + throw new Error "ipaddr: cannot match CIDR for objects with different lengths" + + part = 0 + while cidrBits > 0 + shift = partSize - cidrBits + shift = 0 if shift < 0 + + if first[part] >> shift != second[part] >> shift + return false + + cidrBits -= partSize + part += 1 + + return true + +# An utility function to ease named range matching. See examples below. +ipaddr.subnetMatch = (address, rangeList, defaultName='unicast') -> + for rangeName, rangeSubnets of rangeList + # ECMA5 Array.isArray isn't available everywhere + if rangeSubnets[0] && !(rangeSubnets[0] instanceof Array) + rangeSubnets = [ rangeSubnets ] + + for subnet in rangeSubnets + return rangeName if address.match.apply(address, subnet) + + return defaultName + +# An IPv4 address (RFC791). +class ipaddr.IPv4 + # Constructs a new IPv4 address from an array of four octets. + # Verifies the input. + constructor: (octets) -> + if octets.length != 4 + throw new Error "ipaddr: ipv4 octet count should be 4" + + for octet in octets + if !(0 <= octet <= 255) + throw new Error "ipaddr: ipv4 octet is a byte" + + @octets = octets + + # The 'kind' method exists on both IPv4 and IPv6 classes. + kind: -> + return 'ipv4' + + # Returns the address in convenient, decimal-dotted format. + toString: -> + return @octets.join "." + + # Returns an array of byte-sized values in network order + toByteArray: -> + return @octets.slice(0) # octets.clone + + # 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" + + return matchCIDR(this.octets, other.octets, 8, cidrRange) + + # Special IPv4 address ranges. + SpecialRanges: + unspecified: [ + [ new IPv4([0, 0, 0, 0]), 8 ] + ] + broadcast: [ + [ new IPv4([255, 255, 255, 255]), 32 ] + ] + multicast: [ # RFC3171 + [ new IPv4([224, 0, 0, 0]), 4 ] + ] + linkLocal: [ # RFC3927 + [ new IPv4([169, 254, 0, 0]), 16 ] + ] + loopback: [ # RFC5735 + [ new IPv4([127, 0, 0, 0]), 8 ] + ] + private: [ # RFC1918 + [ new IPv4([10, 0, 0, 0]), 8 ] + [ new IPv4([172, 16, 0, 0]), 12 ] + [ new IPv4([192, 168, 0, 0]), 16 ] + ] + reserved: [ # Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700 + [ new IPv4([192, 0, 0, 0]), 24 ] + [ new IPv4([192, 0, 2, 0]), 24 ] + [ new IPv4([192, 88, 99, 0]), 24 ] + [ new IPv4([198, 51, 100, 0]), 24 ] + [ new IPv4([203, 0, 113, 0]), 24 ] + [ new IPv4([240, 0, 0, 0]), 4 ] + ] + + # Checks if the address corresponds to one of the special ranges. + range: -> + return ipaddr.subnetMatch(this, @SpecialRanges) + + # Convrets this IPv4 address to an IPv4-mapped IPv6 address. + toIPv4MappedAddress: -> + return ipaddr.IPv6.parse "::ffff:#{@toString()}" + +# A list of regular expressions that match arbitrary IPv4 addresses, +# for which a number of weird notations exist. +# Note that an address like 0010.0xa5.1.1 is considered legal. +ipv4Part = "(0?\\d+|0x[a-f0-9]+)" +ipv4Regexes = + fourOctet: new RegExp "^#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' + longValue: new RegExp "^#{ipv4Part}$", 'i' + +# Classful variants (like a.b, where a is an octet, and b is a 24-bit +# value representing last three octets; this corresponds to a class C +# address) are omitted due to classless nature of modern Internet. +ipaddr.IPv4.parser = (string) -> + parseIntAuto = (string) -> + if string[0] == "0" && string[1] != "x" + parseInt(string, 8) + else + parseInt(string) + + # parseInt recognizes all that octal & hexadecimal weirdness for us + if match = string.match(ipv4Regexes.fourOctet) + return (parseIntAuto(part) for part in match[1..5]) + else if match = string.match(ipv4Regexes.longValue) + value = parseIntAuto(match[1]) + if value > 0xffffffff || value < 0 + throw new Error "ipaddr: address outside defined range" + return ((value >> shift) & 0xff for shift in [0..24] by 8).reverse() + else + return null + +# An IPv6 address (RFC2460) +class ipaddr.IPv6 + # Constructs an IPv6 address from an array of eight 16-bit parts. + # Throws an error if the input is invalid. + constructor: (parts) -> + if parts.length != 8 + throw new Error "ipaddr: ipv6 part count should be 8" + + for part in parts + if !(0 <= part <= 0xffff) + throw new Error "ipaddr: ipv6 part should fit to two octets" + + @parts = parts + + # The 'kind' method exists on both IPv4 and IPv6 classes. + kind: -> + return 'ipv6' + + # Returns the address in compact, human-readable format like + # 2001:db8:8:66::1 + toString: -> + stringParts = (part.toString(16) for part in @parts) + + compactStringParts = [] + pushPart = (part) -> compactStringParts.push part + + state = 0 + for part in stringParts + switch state + when 0 + if part == '0' + pushPart('') + else + pushPart(part) + + state = 1 + when 1 + if part == '0' + state = 2 + else + pushPart(part) + when 2 + unless part == '0' + pushPart('') + pushPart(part) + state = 3 + when 3 + pushPart(part) + + if state == 2 + pushPart('') + pushPart('') + + return compactStringParts.join ":" + + # Returns an array of byte-sized values in network order + toByteArray: -> + bytes = [] + for part in @parts + bytes.push(part >> 8) + bytes.push(part & 0xff) + + return bytes + + # Returns the address in expanded format with all zeroes included, like + # 2001:db8:8:66:0:0:0:1 + toNormalizedString: -> + return (part.toString(16) for part in @parts).join ":" + + # 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" + + return matchCIDR(this.parts, other.parts, 16, cidrRange) + + # Special IPv6 ranges + SpecialRanges: + unspecified: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128 ] # RFC4291, here and after + linkLocal: [ new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10 ] + multicast: [ new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8 ] + loopback: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128 ] + uniqueLocal: [ new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7 ] + ipv4Mapped: [ new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96 ] + rfc6145: [ new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96 ] # RFC6145 + rfc6052: [ new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96 ] # RFC6052 + '6to4': [ new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16 ] # RFC3056 + teredo: [ new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32 ] # RFC6052, RFC6146 + reserved: [ + [ new IPv6([ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32 ] # RFC4291 + ] + + # Checks if the address corresponds to one of the special ranges. + range: -> + return ipaddr.subnetMatch(this, @SpecialRanges) + + # Checks if this address is an IPv4-mapped IPv6 address. + isIPv4MappedAddress: -> + return @range() == 'ipv4Mapped' + + # Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address. + # Throws an error otherwise. + toIPv4Address: -> + unless @isIPv4MappedAddress() + throw new Error "ipaddr: trying to convert a generic ipv6 address to ipv4" + + [high, low] = @parts[-2..-1] + + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]) + +# IPv6-matching regular expressions. +# For IPv6, the task is simpler: it is enough to match the colon-delimited +# hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at +# the end. +ipv6Part = "(?:[0-9a-f]+::?)+" +ipv6Regexes = + native: new RegExp "^(::)?(#{ipv6Part})?([0-9a-f]+)?(::)?$", 'i' + transitional: new RegExp "^((?:#{ipv6Part})|(?:::)(?:#{ipv6Part})?)" + + "#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' + +# Expand :: in an IPv6 address or address part consisting of `parts` groups. +expandIPv6 = (string, parts) -> + # More than one '::' means invalid adddress + if string.indexOf('::') != string.lastIndexOf('::') + return null + + # How many parts do we already have? + colonCount = 0 + lastColon = -1 + while (lastColon = string.indexOf(':', lastColon + 1)) >= 0 + colonCount++ + + # 0::0 is two parts more than :: + colonCount-- if string.substr(0, 2) == '::' + colonCount-- if string.substr(-2, 2) == '::' + + # The following loop would hang if colonCount > parts + if colonCount > parts + return null + + # replacement = ':' + '0:' * (parts - colonCount) + replacementCount = parts - colonCount + replacement = ':' + while replacementCount-- + replacement += '0:' + + # Insert the missing zeroes + string = string.replace('::', replacement) + + # Trim any garbage which may be hanging around if :: was at the edge in + # the source string + string = string[1..-1] if string[0] == ':' + string = string[0..-2] if string[string.length-1] == ':' + + return (parseInt(part, 16) for part in string.split(":")) + +# Parse an IPv6 address. +ipaddr.IPv6.parser = (string) -> + if string.match(ipv6Regexes['native']) + return expandIPv6(string, 8) + + else if match = string.match(ipv6Regexes['transitional']) + parts = expandIPv6(match[1][0..-2], 6) + if parts + parts.push(parseInt(match[2]) << 8 | parseInt(match[3])) + parts.push(parseInt(match[4]) << 8 | parseInt(match[5])) + return parts + + return null + +# Checks if a given string is formatted like IPv4/IPv6 address. +ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = (string) -> + return @parser(string) != null + +# Checks if a given string is a valid IPv4/IPv6 address. +ipaddr.IPv4.isValid = (string) -> + try + new this(@parser(string)) + return true + catch e + return false + +ipaddr.IPv6.isValid = (string) -> + # Since IPv6.isValid is always called first, this shortcut + # provides a substantial performance gain. + if typeof string == "string" and string.indexOf(":") == -1 + return false + + try + new this(@parser(string)) + return true + catch e + return false + +# Tries to parse and validate a string with IPv4/IPv6 address. +# Throws an error if it fails. +ipaddr.IPv4.parse = ipaddr.IPv6.parse = (string) -> + parts = @parser(string) + if parts == null + throw new Error "ipaddr: string is not formatted like ip address" + + return new this(parts) + +ipaddr.IPv4.parseCIDR = (string) -> + if match = string.match(/^(.+)\/(\d+)$/) + maskLength = parseInt(match[2]) + if maskLength >= 0 and maskLength <= 32 + return [@parse(match[1]), maskLength] + + throw new Error "ipaddr: string is not formatted like an IPv4 CIDR range" + +ipaddr.IPv6.parseCIDR = (string) -> + if match = string.match(/^(.+)\/(\d+)$/) + maskLength = parseInt(match[2]) + if maskLength >= 0 and maskLength <= 128 + return [@parse(match[1]), maskLength] + + throw new Error "ipaddr: string is not formatted like an IPv6 CIDR range" + +# Checks if the address is valid IP address +ipaddr.isValid = (string) -> + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string) + +# Try to parse an address and throw an error if it is impossible +ipaddr.parse = (string) -> + if ipaddr.IPv6.isValid(string) + return ipaddr.IPv6.parse(string) + else if ipaddr.IPv4.isValid(string) + return ipaddr.IPv4.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) + if addr.kind() == 'ipv6' && addr.isIPv4MappedAddress() + return addr.toIPv4Address() + else + return addr diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee new file mode 100644 index 0000000..17739e2 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee @@ -0,0 +1,282 @@ +ipaddr = require '../lib/ipaddr' + +module.exports = + 'should define main classes': (test) -> + test.ok(ipaddr.IPv4?, 'defines IPv4 class') + test.ok(ipaddr.IPv6?, 'defines IPv6 class') + test.done() + + 'can construct IPv4 from octets': (test) -> + test.doesNotThrow -> + new ipaddr.IPv4([192, 168, 1, 2]) + test.done() + + 'refuses to construct invalid IPv4': (test) -> + test.throws -> + new ipaddr.IPv4([300, 1, 2, 3]) + test.throws -> + new ipaddr.IPv4([8, 8, 8]) + test.done() + + 'converts IPv4 to string correctly': (test) -> + addr = new ipaddr.IPv4([192, 168, 1, 1]) + test.equal(addr.toString(), '192.168.1.1') + test.done() + + 'returns correct kind for IPv4': (test) -> + addr = new ipaddr.IPv4([1, 2, 3, 4]) + test.equal(addr.kind(), 'ipv4') + test.done() + + 'allows to access IPv4 octets': (test) -> + addr = new ipaddr.IPv4([42, 0, 0, 0]) + test.equal(addr.octets[0], 42) + test.done() + + 'checks IPv4 address format': (test) -> + test.equal(ipaddr.IPv4.isIPv4('192.168.007.0xa'), true) + test.equal(ipaddr.IPv4.isIPv4('1024.0.0.1'), true) + test.equal(ipaddr.IPv4.isIPv4('8.0xa.wtf.6'), false) + test.done() + + 'validates IPv4 addresses': (test) -> + test.equal(ipaddr.IPv4.isValid('192.168.007.0xa'), true) + test.equal(ipaddr.IPv4.isValid('1024.0.0.1'), false) + test.equal(ipaddr.IPv4.isValid('8.0xa.wtf.6'), false) + test.done() + + 'parses IPv4 in several weird formats': (test) -> + test.deepEqual(ipaddr.IPv4.parse('192.168.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('0xc0.168.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('192.0250.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('0xc0a80101').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('030052000401').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('3232235777').octets, [192, 168, 1, 1]) + test.done() + + 'barfs at invalid IPv4': (test) -> + test.throws -> + ipaddr.IPv4.parse('10.0.0.wtf') + test.done() + + 'matches IPv4 CIDR correctly': (test) -> + addr = new ipaddr.IPv4([10, 5, 0, 1]) + test.equal(addr.match(ipaddr.IPv4.parse('0.0.0.0'), 0), true) + test.equal(addr.match(ipaddr.IPv4.parse('11.0.0.0'), 8), false) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.0'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.1'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.10'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.5.5.0'), 16), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 16), false) + test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 15), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.5.0.2'), 32), false) + 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.throws -> + ipaddr.IPv4.parseCIDR('0.0.0.0/-1') + test.throws -> + ipaddr.IPv4.parseCIDR('0.0.0.0/33') + 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') + test.equal(ipaddr.IPv4.parse('10.1.0.1').range(), 'private') + test.equal(ipaddr.IPv4.parse('192.168.2.1').range(), 'private') + test.equal(ipaddr.IPv4.parse('224.100.0.1').range(), 'multicast') + test.equal(ipaddr.IPv4.parse('169.254.15.0').range(), 'linkLocal') + test.equal(ipaddr.IPv4.parse('127.1.1.1').range(), 'loopback') + test.equal(ipaddr.IPv4.parse('255.255.255.255').range(), 'broadcast') + test.equal(ipaddr.IPv4.parse('240.1.2.3').range(), 'reserved') + test.equal(ipaddr.IPv4.parse('8.8.8.8').range(), 'unicast') + test.done() + + 'can construct IPv6 from parts': (test) -> + test.doesNotThrow -> + new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.done() + + 'refuses to construct invalid IPv6': (test) -> + test.throws -> + new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 0, 1]) + test.throws -> + new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 1]) + test.done() + + 'converts IPv6 to string correctly': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.equal(addr.toNormalizedString(), '2001:db8:f53a:0:0:0:0:1') + test.equal(addr.toString(), '2001:db8:f53a::1') + test.equal(new ipaddr.IPv6([0, 0, 0, 0, 0, 0, 0, 1]).toString(), '::1') + test.equal(new ipaddr.IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]).toString(), '2001:db8::') + test.done() + + 'returns correct kind for IPv6': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.equal(addr.kind(), 'ipv6') + test.done() + + 'allows to access IPv6 address parts': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 42, 0, 1]) + test.equal(addr.parts[5], 42) + test.done() + + 'checks IPv6 address format': (test) -> + test.equal(ipaddr.IPv6.isIPv6('2001:db8:F53A::1'), true) + test.equal(ipaddr.IPv6.isIPv6('200001::1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:192.168.1.1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1:0'), false) + test.equal(ipaddr.IPv6.isIPv6('fe80::wtf'), false) + test.done() + + 'validates IPv6 addresses': (test) -> + test.equal(ipaddr.IPv6.isValid('2001:db8:F53A::1'), true) + test.equal(ipaddr.IPv6.isValid('200001::1'), false) + test.equal(ipaddr.IPv6.isValid('::ffff:192.168.1.1'), true) + test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1'), false) + test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1:0'), false) + test.equal(ipaddr.IPv6.isValid('2001:db8::F53A::1'), false) + test.equal(ipaddr.IPv6.isValid('fe80::wtf'), false) + test.equal(ipaddr.IPv6.isValid('2002::2:'), false) + test.equal(ipaddr.IPv6.isValid(undefined), false) + test.done() + + 'parses IPv6 in different formats': (test) -> + test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A:0:0:0:0:1').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.deepEqual(ipaddr.IPv6.parse('fe80::10').parts, [0xfe80, 0, 0, 0, 0, 0, 0, 0x10]) + test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A::').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 0]) + test.deepEqual(ipaddr.IPv6.parse('::1').parts, [0, 0, 0, 0, 0, 0, 0, 1]) + test.deepEqual(ipaddr.IPv6.parse('::').parts, [0, 0, 0, 0, 0, 0, 0, 0]) + test.done() + + 'barfs at invalid IPv6': (test) -> + test.throws -> + ipaddr.IPv6.parse('fe80::0::1') + test.done() + + 'matches IPv6 CIDR correctly': (test) -> + addr = ipaddr.IPv6.parse('2001:db8:f53a::1') + test.equal(addr.match(ipaddr.IPv6.parse('::'), 0), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53a::1:1'), 64), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53b::1:1'), 48), false) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f531::1:1'), 44), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f500::1'), 40), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db9:f500::1'), 40), false) + 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.throws -> + ipaddr.IPv6.parseCIDR('2001:db8:f53a::1/-1') + test.throws -> + ipaddr.IPv6.parseCIDR('2001:db8:f53a::1/129') + test.done() + + 'converts between IPv4-mapped IPv6 addresses and IPv4 addresses': (test) -> + addr = ipaddr.IPv4.parse('77.88.21.11') + mapped = addr.toIPv4MappedAddress() + test.deepEqual(mapped.parts, [0, 0, 0, 0, 0, 0xffff, 0x4d58, 0x150b]) + test.deepEqual(mapped.toIPv4Address().octets, addr.octets) + test.done() + + 'refuses to convert non-IPv4-mapped IPv6 address to IPv4 address': (test) -> + test.throws -> + ipaddr.IPv6.parse('2001:db8::1').toIPv4Address() + test.done() + + 'detects reserved IPv6 networks': (test) -> + test.equal(ipaddr.IPv6.parse('::').range(), 'unspecified') + test.equal(ipaddr.IPv6.parse('fe80::1234:5678:abcd:0123').range(), 'linkLocal') + test.equal(ipaddr.IPv6.parse('ff00::1234').range(), 'multicast') + test.equal(ipaddr.IPv6.parse('::1').range(), 'loopback') + test.equal(ipaddr.IPv6.parse('fc00::').range(), 'uniqueLocal') + test.equal(ipaddr.IPv6.parse('::ffff:192.168.1.10').range(), 'ipv4Mapped') + test.equal(ipaddr.IPv6.parse('::ffff:0:192.168.1.10').range(), 'rfc6145') + test.equal(ipaddr.IPv6.parse('64:ff9b::1234').range(), 'rfc6052') + test.equal(ipaddr.IPv6.parse('2002:1f63:45e8::1').range(), '6to4') + test.equal(ipaddr.IPv6.parse('2001::4242').range(), 'teredo') + test.equal(ipaddr.IPv6.parse('2001:db8::3210').range(), 'reserved') + test.equal(ipaddr.IPv6.parse('2001:470:8:66::1').range(), 'unicast') + test.done() + + 'is able to determine IP address type': (test) -> + test.equal(ipaddr.parse('8.8.8.8').kind(), 'ipv4') + test.equal(ipaddr.parse('2001:db8:3312::1').kind(), 'ipv6') + test.done() + + 'throws an error if tried to parse an invalid address': (test) -> + test.throws -> + ipaddr.parse('::some.nonsense') + test.done() + + 'correctly processes IPv4-mapped addresses': (test) -> + test.equal(ipaddr.process('8.8.8.8').kind(), 'ipv4') + test.equal(ipaddr.process('2001:db8:3312::1').kind(), 'ipv6') + test.equal(ipaddr.process('::ffff:192.168.1.1').kind(), 'ipv4') + test.done() + + 'correctly converts IPv6 and IPv4 addresses to byte arrays': (test) -> + test.deepEqual(ipaddr.parse('1.2.3.4').toByteArray(), + [0x1, 0x2, 0x3, 0x4]); + # Fuck yeah. The first byte of Google's IPv6 address is 42. 42! + test.deepEqual(ipaddr.parse('2a00:1450:8007::68').toByteArray(), + [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68 ]) + test.done() + + 'correctly parses 1 as an IPv4 address': (test) -> + test.equal(ipaddr.IPv6.isValid('1'), false) + test.equal(ipaddr.IPv4.isValid('1'), true) + 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) + test.done() + + 'does not hang on ::8:8:8:8:8:8:8:8:8': (test) -> + test.equal(ipaddr.IPv6.isValid('::8:8:8:8:8:8:8:8:8'), false) + test.done() + + 'subnetMatch does not fail on empty range': (test) -> + ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {}, false) + ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {subnet: []}, false) + test.done() + + 'subnetMatch returns default subnet on empty range': (test) -> + test.equal(ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {}, false), false) + test.equal(ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {subnet: []}, false), false) + test.done() diff --git a/5-1/service/node_modules/express/node_modules/proxy-addr/package.json b/5-1/service/node_modules/express/node_modules/proxy-addr/package.json new file mode 100644 index 0000000..04af756 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/proxy-addr/package.json @@ -0,0 +1,90 @@ +{ + "name": "proxy-addr", + "description": "Determine address of proxied request", + "version": "1.0.10", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/proxy-addr.git" + }, + "dependencies": { + "forwarded": "~0.1.0", + "ipaddr.js": "1.0.5" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "0cdb6444100a7930285ed2555d0c3c687690a7a5", + "bugs": { + "url": "https://github.com/jshttp/proxy-addr/issues" + }, + "homepage": "https://github.com/jshttp/proxy-addr", + "_id": "proxy-addr@1.0.10", + "_shasum": "0d40a82f801fc355567d2ecb65efe3f077f121c5", + "_from": "proxy-addr@>=1.0.10 <1.1.0", + "_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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "0d40a82f801fc355567d2ecb65efe3f077f121c5", + "tarball": "http://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.10.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.10.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/qs/.eslintignore b/5-1/service/node_modules/express/node_modules/qs/.eslintignore new file mode 100644 index 0000000..1521c8b --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/.eslintignore @@ -0,0 +1 @@ +dist diff --git a/5-1/service/node_modules/express/node_modules/qs/.npmignore b/5-1/service/node_modules/express/node_modules/qs/.npmignore new file mode 100644 index 0000000..2abba8d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/.npmignore @@ -0,0 +1,19 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov +complexity.md +dist diff --git a/5-1/service/node_modules/express/node_modules/qs/.travis.yml b/5-1/service/node_modules/express/node_modules/qs/.travis.yml new file mode 100644 index 0000000..f502178 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/.travis.yml @@ -0,0 +1,6 @@ +language: node_js + +node_js: + - 0.10 + - 0.12 + - iojs diff --git a/5-1/service/node_modules/express/node_modules/qs/CHANGELOG.md b/5-1/service/node_modules/express/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000..1fadc78 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/CHANGELOG.md @@ -0,0 +1,88 @@ + +## [**3.1.0**](https://github.com/hapijs/qs/issues?milestone=24&state=open) +- [**#89**](https://github.com/hapijs/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/hapijs/qs/issues?milestone=23&state=closed) +- [**#77**](https://github.com/hapijs/qs/issues/77) Perf boost +- [**#60**](https://github.com/hapijs/qs/issues/60) Add explicit option to disable array parsing +- [**#80**](https://github.com/hapijs/qs/issues/80) qs.parse silently drops properties +- [**#74**](https://github.com/hapijs/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/hapijs/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/hapijs/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/hapijs/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/hapijs/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/hapijs/qs/issues/85) No equal sign +- [**#84**](https://github.com/hapijs/qs/issues/84) update license attribute + +## [**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". + +## [**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 + +## [**2.2.5**](https://github.com/hapijs/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/hapijs/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/hapijs/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/hapijs/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/hapijs/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/hapijs/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/hapijs/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/hapijs/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/hapijs/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/hapijs/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/hapijs/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/hapijs/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/hapijs/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/hapijs/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/hapijs/qs/issues/32) account for circular references properly, closes #31 +- [**#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 +- [**#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 +- [**#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) +- [**#22**](https://github.com/hapijs/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/hapijs/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/hapijs/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/hapijs/qs/issues/20) Configurable parametersLimit +- [**#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 + +## [**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 +- [**#15**](https://github.com/hapijs/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/hapijs/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/hapijs/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/hapijs/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/hapijs/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/hapijs/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/hapijs/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/hapijs/qs/issues/6) Minor grammar fix in README + +## [**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/5-1/service/node_modules/express/node_modules/qs/CONTRIBUTING.md b/5-1/service/node_modules/express/node_modules/qs/CONTRIBUTING.md new file mode 100644 index 0000000..8928361 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/CONTRIBUTING.md @@ -0,0 +1 @@ +Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md). diff --git a/5-1/service/node_modules/express/node_modules/qs/LICENSE b/5-1/service/node_modules/express/node_modules/qs/LICENSE new file mode 100644 index 0000000..d456948 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/5-1/service/node_modules/express/node_modules/qs/README.md b/5-1/service/node_modules/express/node_modules/qs/README.md new file mode 100644 index 0000000..48a0de9 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/README.md @@ -0,0 +1,317 @@ +# qs + +A querystring parsing and stringifying library with some added security. + +[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs) + +Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var Qs = require('qs'); + +var obj = Qs.parse('a=c'); // { a: 'c' } +var str = Qs.stringify(obj); // 'a=c' +``` + +### Parsing Objects + +```javascript +Qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`, or prefixing the sub-key with a dot `.`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +{ + foo: { + bar: 'baz' + } +} +``` + +When using the `plainObjects` option the parsed value is returned as a plain object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +Qs.parse('a.hasOwnProperty=b', { plainObjects: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. + +```javascript +Qs.parse('a.hasOwnProperty=b', { allowPrototypes: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +URI encoded strings work too: + +```javascript +Qs.parse('a%5Bb%5D=c'); +// { a: { b: 'c' } } +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +{ + foo: { + bar: { + baz: 'foobarbaz' + } + } +} +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +{ + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +} +``` + +This depth can be overridden by passing a `depth` option to `Qs.parse(string, [options])`: + +```javascript +Qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } } +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +Qs.parse('a=b&c=d', { parameterLimit: 1 }); +// { a: 'b' } +``` + +An optional delimiter can also be passed: + +```javascript +Qs.parse('a=b;c=d', { delimiter: ';' }); +// { a: 'b', c: 'd' } +``` + +Delimiters can be a regular expression too: + +```javascript +Qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +// { a: 'b', c: 'd', e: 'f' } +``` + +Option `allowDots` can be used to disable dot notation: + +```javascript +Qs.parse('a.b=c', { allowDots: false }); +// { 'a.b': 'c' } } +``` + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +Qs.parse('a[]=b&a[]=c'); +// { a: ['b', 'c'] } +``` + +You may specify an index as well: + +```javascript +Qs.parse('a[1]=c&a[0]=b'); +// { a: ['b', 'c'] } +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +Qs.parse('a[1]=b&a[15]=c'); +// { a: ['b', 'c'] } +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +Qs.parse('a[]=&a[]=b'); +// { a: ['', 'b'] } +Qs.parse('a[0]=b&a[1]=&a[2]=c'); +// { a: ['b', '', 'c'] } +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key: + +```javascript +Qs.parse('a[100]=b'); +// { a: { '100': 'b' } } +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +Qs.parse('a[1]=b', { arrayLimit: 0 }); +// { a: { '1': 'b' } } +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +Qs.parse('a[]=b', { parseArrays: false }); +// { a: { '0': 'b' } } +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +Qs.parse('a[0]=b&a[b]=c'); +// { a: { '0': 'b', b: 'c' } } +``` + +You can also create arrays of objects: + +```javascript +Qs.parse('a[][b]=c'); +// { a: [{ b: 'c' }] } +``` + +### Stringifying + +```javascript +Qs.stringify(object, [options]); +``` + +When stringifying, **qs** always URI encodes output. Objects are stringified as you would expect: + +```javascript +Qs.stringify({ a: 'b' }); +// 'a=b' +Qs.stringify({ a: { b: 'c' } }); +// 'a%5Bb%5D=c' +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +Qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +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 +Qs.stringify({ a: '' }); +// 'a=' +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +Qs.stringify({ a: null, b: undefined }); +// 'a=' +``` + +The delimiter may be overridden with stringify as well: + +```javascript +Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }); +// 'a=b;c=d' +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +Qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }) +// 'a=b&c=d&e[f]=123&e[g][0]=4' +Qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }) +// 'a=b&e=f' +Qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }) +// 'a[0]=b&a[2]=d' +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +Qs.stringify({ a: null, b: '' }); +// 'a=&b=' +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +Qs.parse('a&b=') +// { a: '', b: '' } +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +Qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +// 'a&b=' +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +Qs.parse('a&b=', { strictNullHandling: true }); +// { a: null, b: '' } + +``` diff --git a/5-1/service/node_modules/express/node_modules/qs/bower.json b/5-1/service/node_modules/express/node_modules/qs/bower.json new file mode 100644 index 0000000..ffd0641 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/bower.json @@ -0,0 +1,22 @@ +{ + "name": "qs", + "main": "dist/qs.js", + "version": "3.0.0", + "homepage": "https://github.com/hapijs/qs", + "authors": [ + "Nathan LaFreniere " + ], + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/5-1/service/node_modules/express/node_modules/qs/lib/index.js b/5-1/service/node_modules/express/node_modules/qs/lib/index.js new file mode 100644 index 0000000..0e09493 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/lib/index.js @@ -0,0 +1,15 @@ +// Load modules + +var Stringify = require('./stringify'); +var Parse = require('./parse'); + + +// Declare internals + +var internals = {}; + + +module.exports = { + stringify: Stringify, + parse: Parse +}; diff --git a/5-1/service/node_modules/express/node_modules/qs/lib/parse.js b/5-1/service/node_modules/express/node_modules/qs/lib/parse.js new file mode 100644 index 0000000..e7c56c5 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/lib/parse.js @@ -0,0 +1,186 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + depth: 5, + arrayLimit: 20, + parameterLimit: 1000, + strictNullHandling: false, + plainObjects: false, + allowPrototypes: false +}; + + +internals.parseValues = function (str, options) { + + var obj = {}; + var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); + + for (var i = 0, il = parts.length; i < il; ++i) { + var part = parts[i]; + var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; + + if (pos === -1) { + obj[Utils.decode(part)] = ''; + + if (options.strictNullHandling) { + obj[Utils.decode(part)] = null; + } + } + else { + var key = Utils.decode(part.slice(0, pos)); + var val = Utils.decode(part.slice(pos + 1)); + + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + obj[key] = val; + } + else { + obj[key] = [].concat(obj[key]).concat(val); + } + } + } + + return obj; +}; + + +internals.parseObject = function (chain, val, options) { + + if (!chain.length) { + return val; + } + + var root = chain.shift(); + + var obj; + if (root === '[]') { + obj = []; + obj = obj.concat(internals.parseObject(chain, val, options)); + } + else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; + var index = parseInt(cleanRoot, 10); + var indexString = '' + index; + if (!isNaN(index) && + root !== cleanRoot && + indexString === cleanRoot && + index >= 0 && + (options.parseArrays && + index <= options.arrayLimit)) { + + obj = []; + obj[index] = internals.parseObject(chain, val, options); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val, options); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, options) { + + if (!key) { + return; + } + + // Transform dot notation to bracket notation + + if (options.allowDots) { + key = key.replace(/\.([^\.\[]+)/g, '[$1]'); + } + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1])) { + + if (!options.allowPrototypes) { + return; + } + } + + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + + ++i; + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { + + if (!options.allowPrototypes) { + continue; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val, options); +}; + + +module.exports = function (str, options) { + + options = options || {}; + options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.allowDots = options.allowDots !== false; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : internals.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : internals.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var newObj = internals.parseKeys(key, tempObj[key], options); + obj = Utils.merge(obj, newObj, options); + } + + return Utils.compact(obj); +}; diff --git a/5-1/service/node_modules/express/node_modules/qs/lib/stringify.js b/5-1/service/node_modules/express/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000..7414284 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/lib/stringify.js @@ -0,0 +1,121 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + arrayPrefixGenerators: { + brackets: function (prefix, key) { + + return prefix + '[]'; + }, + indices: function (prefix, key) { + + return prefix + '[' + key + ']'; + }, + repeat: function (prefix, key) { + + return prefix; + } + }, + strictNullHandling: false +}; + + +internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, filter) { + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } + else if (Utils.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + else if (obj === null) { + if (strictNullHandling) { + return Utils.encode(prefix); + } + + obj = ''; + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + return [Utils.encode(prefix) + '=' + Utils.encode(obj)]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys = Array.isArray(filter) ? filter : Object.keys(obj); + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (Array.isArray(obj)) { + values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, filter)); + } + else { + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, filter)); + } + } + + return values; +}; + + +module.exports = function (obj, options) { + + options = options || {}; + var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + var objKeys; + var filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } + else if (Array.isArray(options.filter)) { + objKeys = filter = options.filter; + } + + var keys = []; + + if (typeof obj !== 'object' || + obj === null) { + + 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]; + + if (!objKeys) { + 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, generateArrayPrefix, strictNullHandling, filter)); + } + + return keys.join(delimiter); +}; diff --git a/5-1/service/node_modules/express/node_modules/qs/lib/utils.js b/5-1/service/node_modules/express/node_modules/qs/lib/utils.js new file mode 100644 index 0000000..88f3147 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/lib/utils.js @@ -0,0 +1,190 @@ +// Load modules + + +// Declare internals + +var internals = {}; +internals.hexTable = new Array(256); +for (var h = 0; h < 256; ++h) { + internals.hexTable[h] = '%' + ((h < 16 ? '0' : '') + h.toString(16)).toUpperCase(); +} + + +exports.arrayToObject = function (source, options) { + + var obj = options.plainObjects ? Object.create(null) : {}; + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.merge = function (target, source, options) { + + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } + else if (typeof target === 'object') { + target[source] = true; + } + else { + target = [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + target = [target].concat(source); + return target; + } + + if (Array.isArray(target) && + !Array.isArray(source)) { + + target = exports.arrayToObject(target, options); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = value; + } + else { + target[key] = exports.merge(target[key], value, options); + } + } + + return target; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function (str) { + + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + if (typeof str !== 'string') { + str = '' + str; + } + + var out = ''; + for (var i = 0, il = str.length; i < il; ++i) { + var c = str.charCodeAt(i); + + if (c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A)) { // A-Z + + out += str[i]; + continue; + } + + if (c < 0x80) { + out += internals.hexTable[c]; + continue; + } + + if (c < 0x800) { + out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + ++i; + c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF)); + out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function (obj, refs) { + + if (typeof obj !== 'object' || + obj === null) { + + return obj; + } + + refs = refs || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } + + refs.push(obj); + + if (Array.isArray(obj)) { + var compacted = []; + + for (var i = 0, il = obj.length; i < il; ++i) { + if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } + + return compacted; + } + + var keys = Object.keys(obj); + for (i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + obj[key] = exports.compact(obj[key], refs); + } + + return obj; +}; + + +exports.isRegExp = function (obj) { + + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + + +exports.isBuffer = function (obj) { + + if (obj === null || + typeof obj === 'undefined') { + + return false; + } + + return !!(obj.constructor && + obj.constructor.isBuffer && + obj.constructor.isBuffer(obj)); +}; diff --git a/5-1/service/node_modules/express/node_modules/qs/package.json b/5-1/service/node_modules/express/node_modules/qs/package.json new file mode 100644 index 0000000..1bae0ed --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/package.json @@ -0,0 +1,57 @@ +{ + "name": "qs", + "version": "4.0.0", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/hapijs/qs", + "main": "lib/index.js", + "dependencies": {}, + "devDependencies": { + "browserify": "^10.2.1", + "code": "1.x.x", + "lab": "5.x.x" + }, + "scripts": { + "test": "lab -a code -t 100 -L", + "test-cov-html": "lab -a code -r html -o coverage.html", + "dist": "browserify --standalone Qs lib/index.js > dist/qs.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/hapijs/qs.git" + }, + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "gitHead": "e573dd08eae6cce30d2202704691a102dfa3782a", + "bugs": { + "url": "https://github.com/hapijs/qs/issues" + }, + "_id": "qs@4.0.0", + "_shasum": "c31d9b74ec27df75e543a86c78728ed8d4623607", + "_from": "qs@4.0.0", + "_npmVersion": "2.12.0", + "_nodeVersion": "0.12.4", + "_npmUser": { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + "dist": { + "shasum": "c31d9b74ec27df75e543a86c78728ed8d4623607", + "tarball": "http://registry.npmjs.org/qs/-/qs-4.0.0.tgz" + }, + "maintainers": [ + { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/qs/-/qs-4.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/qs/test/parse.js b/5-1/service/node_modules/express/node_modules/qs/test/parse.js new file mode 100644 index 0000000..a19d764 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/test/parse.js @@ -0,0 +1,478 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('parse()', function () { + + it('parses a simple string', function (done) { + + expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' }); + expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' }); + expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } }); + expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } }); + expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } }); + expect(Qs.parse('foo', { strictNullHandling: true })).to.deep.equal({ foo: null }); + expect(Qs.parse('foo' )).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=')).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' }); + expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' }); + expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' }); + expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' }); + expect(Qs.parse('foo2=bar2&baz2=')).to.deep.equal({ foo2: 'bar2', baz2: '' }); + expect(Qs.parse('foo=bar&baz', { strictNullHandling: true })).to.deep.equal({ foo: 'bar', baz: null }); + expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' }); + expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({ + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + done(); + }); + + it('allows disabling dot notation', function (done) { + + expect(Qs.parse('a.b=c')).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse('a.b=c', { allowDots: false })).to.deep.equal({ 'a.b': 'c' }); + done(); + }); + + it('parses a single nested string', function (done) { + + expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } }); + done(); + }); + + it('parses a double nested string', function (done) { + + expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } }); + done(); + }); + + it('defaults to a depth of 5', function (done) { + + expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }); + done(); + }); + + it('only parses one level when depth = 1', function (done) { + + expect(Qs.parse('a[b][c]=d', { depth: 1 })).to.deep.equal({ a: { b: { '[c]': 'd' } } }); + expect(Qs.parse('a[b][c][d]=e', { depth: 1 })).to.deep.equal({ a: { b: { '[c][d]': 'e' } } }); + done(); + }); + + it('parses a simple array', function (done) { + + expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses an explicit array', function (done) { + + expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] }); + expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + done(); + }); + + it('parses a mix of simple and explicit arrays', function (done) { + + expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses a nested array', function (done) { + + expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } }); + expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } }); + done(); + }); + + it('allows to specify array indices', function (done) { + + expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] }); + done(); + }); + + it('limits specific array indices to 20', function (done) { + + expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] }); + expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } }); + done(); + }); + + it('supports keys that begin with a number', function (done) { + + expect(Qs.parse('a[12b]=c')).to.deep.equal({ a: { '12b': 'c' } }); + done(); + }); + + it('supports encoded = signs', function (done) { + + expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' }); + done(); + }); + + it('is ok with url encoded strings', function (done) { + + expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } }); + expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } }); + done(); + }); + + it('allows brackets in the value', function (done) { + + expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' }); + expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' }); + done(); + }); + + it('allows empty values', function (done) { + + expect(Qs.parse('')).to.deep.equal({}); + expect(Qs.parse(null)).to.deep.equal({}); + expect(Qs.parse(undefined)).to.deep.equal({}); + done(); + }); + + it('transforms arrays to objects', function (done) { + + expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + expect(Qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c')).to.deep.equal({ a: { '0': 'b', t: 'u', c: true } }); + expect(Qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y')).to.deep.equal({ a: { '0': 'b', '1': 'c', x: 'y' } }); + done(); + }); + + it('transforms arrays to objects (dot notation)', function (done) { + + expect(Qs.parse('foo[0].baz=bar&fool.bad=baz')).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz=bar&fool.bad.boo=baz')).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + expect(Qs.parse('foo[0][0].baz=bar&fool.bad=baz')).to.deep.equal({ foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].bar=2')).to.deep.equal({ foo: [{ baz: ['15'], bar: '2' }] }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2')).to.deep.equal({ foo: [{ baz: ['15', '16'], bar: '2' }] }); + expect(Qs.parse('foo.bad=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo.bad=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + done(); + }); + + it('can add keys to objects', function (done) { + + expect(Qs.parse('a[b]=c&a=d')).to.deep.equal({ a: { b: 'c', d: true } }); + done(); + }); + + it('correctly prunes undefined values when converting an array to an object', function (done) { + + expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } }); + done(); + }); + + it('supports malformed uri characters', function (done) { + + expect(Qs.parse('{%:%}', { strictNullHandling: true })).to.deep.equal({ '{%:%}': null }); + expect(Qs.parse('{%:%}=')).to.deep.equal({ '{%:%}': '' }); + expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' }); + done(); + }); + + it('doesn\'t produce empty keys', function (done) { + + expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' }); + done(); + }); + + it('cannot access Object prototype', function (done) { + + Qs.parse('constructor[prototype][bad]=bad'); + Qs.parse('bad[constructor][prototype][bad]=bad'); + expect(typeof Object.prototype.bad).to.equal('undefined'); + done(); + }); + + it('parses arrays of objects', function (done) { + + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + done(); + }); + + it('allows for empty strings in arrays', function (done) { + + expect(Qs.parse('a[]=b&a[]=&a[]=c')).to.deep.equal({ a: ['b', '', 'c'] }); + expect(Qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true })).to.deep.equal({ a: ['b', null, 'c', ''] }); + expect(Qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true })).to.deep.equal({ a: ['b', '', 'c', null] }); + expect(Qs.parse('a[]=&a[]=b&a[]=c')).to.deep.equal({ a: ['', 'b', 'c'] }); + done(); + }); + + it('compacts sparse arrays', function (done) { + + expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] }); + done(); + }); + + it('parses semi-parsed strings', function (done) { + + expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } }); + done(); + }); + + it('parses buffers correctly', function (done) { + + var b = new Buffer('test'); + expect(Qs.parse({ a: b })).to.deep.equal({ a: b }); + done(); + }); + + it('continues parsing when no parent is found', function (done) { + + expect(Qs.parse('[]=&a=b')).to.deep.equal({ '0': '', a: 'b' }); + expect(Qs.parse('[]&a=b', { strictNullHandling: true })).to.deep.equal({ '0': null, a: 'b' }); + expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' }); + done(); + }); + + it('does not error when parsing a very long array', function (done) { + + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str += '&' + str; + } + + expect(function () { + + Qs.parse(str); + }).to.not.throw(); + + done(); + }); + + it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) { + + Object.prototype.crash = ''; + Array.prototype.crash = ''; + expect(Qs.parse.bind(null, 'a=b')).to.not.throw(); + expect(Qs.parse('a=b')).to.deep.equal({ a: 'b' }); + expect(Qs.parse.bind(null, 'a[][b]=c')).to.not.throw(); + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + done(); + }); + + it('parses a string with an alternative string delimiter', function (done) { + + expect(Qs.parse('a=b;c=d', { delimiter: ';' })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('parses a string with an alternative RegExp delimiter', function (done) { + + expect(Qs.parse('a=b; c=d', { delimiter: /[;,] */ })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not use non-splittable objects as delimiters', function (done) { + + expect(Qs.parse('a=b&c=d', { delimiter: true })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('allows overriding parameter limit', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: 1 })).to.deep.equal({ a: 'b' }); + done(); + }); + + it('allows setting the parameter limit to Infinity', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: Infinity })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + 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(); + }); + + it('allows disabling array parsing', function (done) { + + expect(Qs.parse('a[0]=b&a[1]=c', { parseArrays: false })).to.deep.equal({ a: { '0': 'b', '1': 'c' } }); + done(); + }); + + it('parses an object', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object in dot notation', function (done) { + + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object and not child values', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': { 'test': 3 } }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': { 'test': 3 } }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('does not blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = Qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + expect(result).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not crash when parsing circular references', function (done) { + + var a = {}; + a.b = a; + + var parsed; + + expect(function () { + + parsed = Qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }).to.not.throw(); + + 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(); + }); + + it('parses plain objects correctly', function (done) { + + var a = Object.create(null); + a.b = 'c'; + + expect(Qs.parse(a)).to.deep.equal({ b: 'c' }); + var result = Qs.parse({ a: a }); + expect(result).to.contain('a'); + expect(result.a).to.deep.equal(a); + done(); + }); + + it('parses dates correctly', function (done) { + + var now = new Date(); + expect(Qs.parse({ a: now })).to.deep.equal({ a: now }); + done(); + }); + + it('parses regular expressions correctly', function (done) { + + var re = /^test$/; + expect(Qs.parse({ a: re })).to.deep.equal({ a: re }); + done(); + }); + + it('can allow overwriting prototype properties', function (done) { + + expect(Qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true })).to.deep.equal({ a: { hasOwnProperty: 'b' } }, { prototype: false }); + expect(Qs.parse('hasOwnProperty=b', { allowPrototypes: true })).to.deep.equal({ hasOwnProperty: 'b' }, { prototype: false }); + done(); + }); + + it('can return plain objects', function (done) { + + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + expect(Qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true })).to.deep.equal(expected); + expect(Qs.parse(null, { plainObjects: true })).to.deep.equal(Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a['0'] = 'b'; + expectedArray.a.c = 'd'; + expect(Qs.parse('a[]=b&a[c]=d', { plainObjects: true })).to.deep.equal(expectedArray); + done(); + }); +}); diff --git a/5-1/service/node_modules/express/node_modules/qs/test/stringify.js b/5-1/service/node_modules/express/node_modules/qs/test/stringify.js new file mode 100644 index 0000000..48b7803 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/test/stringify.js @@ -0,0 +1,259 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('stringify()', function () { + + it('stringifies a querystring object', function (done) { + + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 })).to.equal('a=1'); + expect(Qs.stringify({ a: 1, b: 2 })).to.equal('a=1&b=2'); + expect(Qs.stringify({ a: 'A_Z' })).to.equal('a=A_Z'); + expect(Qs.stringify({ a: '€' })).to.equal('a=%E2%82%AC'); + expect(Qs.stringify({ a: '' })).to.equal('a=%EE%80%80'); + expect(Qs.stringify({ a: 'א' })).to.equal('a=%D7%90'); + expect(Qs.stringify({ a: '𐐷' })).to.equal('a=%F0%90%90%B7'); + done(); + }); + + it('stringifies a nested object', function (done) { + + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + expect(Qs.stringify({ a: { b: { c: { d: 'e' } } } })).to.equal('a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + done(); + }); + + it('stringifies an array value', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d'); + done(); + }); + + it('omits array indices when asked', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false })).to.equal('a=b&a=c&a=d'); + done(); + }); + + it('stringifies a nested array value', function (done) { + + expect(Qs.stringify({ a: { b: ['c', 'd'] } })).to.equal('a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + done(); + }); + + it('stringifies an object inside an array', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] })).to.equal('a%5B0%5D%5Bb%5D=c'); + expect(Qs.stringify({ a: [{ b: { c: [1] } }] })).to.equal('a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1'); + done(); + }); + + it('does not omit object keys when indices = false', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] }, { indices: false })).to.equal('a%5Bb%5D=c'); + 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'); + done(); + }); + + it('stringifies an empty value', function (done) { + + expect(Qs.stringify({ a: '' })).to.equal('a='); + expect(Qs.stringify({ a: null }, { strictNullHandling: true })).to.equal('a'); + + expect(Qs.stringify({ a: '', b: '' })).to.equal('a=&b='); + expect(Qs.stringify({ a: null, b: '' }, { strictNullHandling: true })).to.equal('a&b='); + + expect(Qs.stringify({ a: { b: '' } })).to.equal('a%5Bb%5D='); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: true })).to.equal('a%5Bb%5D'); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: false })).to.equal('a%5Bb%5D='); + + done(); + }); + + it('stringifies an empty object', function (done) { + + var obj = Object.create(null); + obj.a = 'b'; + expect(Qs.stringify(obj)).to.equal('a=b'); + done(); + }); + + it('returns an empty string for invalid input', function (done) { + + expect(Qs.stringify(undefined)).to.equal(''); + expect(Qs.stringify(false)).to.equal(''); + expect(Qs.stringify(null)).to.equal(''); + expect(Qs.stringify('')).to.equal(''); + done(); + }); + + it('stringifies an object with an empty object as a child', function (done) { + + var obj = { + a: Object.create(null) + }; + + obj.a.b = 'c'; + expect(Qs.stringify(obj)).to.equal('a%5Bb%5D=c'); + done(); + }); + + it('drops keys with a value of undefined', function (done) { + + expect(Qs.stringify({ a: undefined })).to.equal(''); + + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true })).to.equal('a%5Bc%5D'); + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false })).to.equal('a%5Bc%5D='); + expect(Qs.stringify({ a: { b: undefined, c: '' } })).to.equal('a%5Bc%5D='); + done(); + }); + + it('url encodes values', function (done) { + + expect(Qs.stringify({ a: 'b c' })).to.equal('a=b%20c'); + done(); + }); + + it('stringifies a date', function (done) { + + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + expect(Qs.stringify({ a: now })).to.equal(str); + done(); + }); + + it('stringifies the weird object from qs', function (done) { + + expect(Qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' })).to.equal('my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + done(); + }); + + it('skips properties that are part of the object prototype', function (done) { + + Object.prototype.crash = 'test'; + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + delete Object.prototype.crash; + done(); + }); + + it('stringifies boolean values', function (done) { + + expect(Qs.stringify({ a: true })).to.equal('a=true'); + expect(Qs.stringify({ a: { b: true } })).to.equal('a%5Bb%5D=true'); + expect(Qs.stringify({ b: false })).to.equal('b=false'); + expect(Qs.stringify({ b: { c: false } })).to.equal('b%5Bc%5D=false'); + done(); + }); + + it('stringifies buffer values', function (done) { + + expect(Qs.stringify({ a: new Buffer('test') })).to.equal('a=test'); + expect(Qs.stringify({ a: { b: new Buffer('test') } })).to.equal('a%5Bb%5D=test'); + done(); + }); + + it('stringifies an object using an alternative delimiter', function (done) { + + expect(Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' })).to.equal('a=b;c=d'); + done(); + }); + + it('doesn\'t blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + expect(Qs.stringify({ a: 'b', c: 'd' })).to.equal('a=b&c=d'); + global.Buffer = tempBuffer; + done(); + }); + + it('selects properties when filter=array', function (done) { + + expect(Qs.stringify({ a: 'b' }, { filter: ['a'] })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 }, { filter: [] })).to.equal(''); + expect(Qs.stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] })).to.equal('a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3'); + done(); + + }); + + it('supports custom representations when filter=function', function (done) { + + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + + calls++; + if (calls === 1) { + expect(prefix).to.be.empty(); + expect(value).to.equal(obj); + } + else if (prefix === 'c') { + return; + } + else if (value instanceof Date) { + expect(prefix).to.equal('e[f]'); + return value.getTime(); + } + return value; + }; + + expect(Qs.stringify(obj, { filter: filterFunc })).to.equal('a=b&e%5Bf%5D=1257894000000'); + expect(calls).to.equal(5); + done(); + + }); +}); diff --git a/5-1/service/node_modules/express/node_modules/qs/test/utils.js b/5-1/service/node_modules/express/node_modules/qs/test/utils.js new file mode 100644 index 0000000..a9a6b52 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/qs/test/utils.js @@ -0,0 +1,28 @@ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Utils = require('../lib/utils'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('merge()', function () { + + it('can merge two objects with the same key', function (done) { + + expect(Utils.merge({ a: 'b' }, { a: 'c' })).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); +}); diff --git a/5-1/service/node_modules/express/node_modules/range-parser/HISTORY.md b/5-1/service/node_modules/express/node_modules/range-parser/HISTORY.md new file mode 100644 index 0000000..f640bea --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/range-parser/HISTORY.md @@ -0,0 +1,40 @@ +unreleased +========== + + * perf: enable strict mode + +1.0.2 / 2014-09-08 +================== + + * Support Node.js 0.6 + +1.0.1 / 2014-09-07 +================== + + * Move repository to jshttp + +1.0.0 / 2013-12-11 +================== + + * Add repository to package.json + * Add MIT license + +0.0.4 / 2012-06-17 +================== + + * Change ret -1 for unsatisfiable and -2 when invalid + +0.0.3 / 2012-06-17 +================== + + * Fix last-byte-pos default to len - 1 + +0.0.2 / 2012-06-14 +================== + + * Add `.type` + +0.0.1 / 2012-06-11 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/range-parser/LICENSE b/5-1/service/node_modules/express/node_modules/range-parser/LICENSE new file mode 100644 index 0000000..a491841 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/range-parser/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/range-parser/README.md b/5-1/service/node_modules/express/node_modules/range-parser/README.md new file mode 100644 index 0000000..32f58f6 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/range-parser/README.md @@ -0,0 +1,57 @@ +# range-parser + +[![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] + +Range header field parser. + +## Installation + +``` +$ npm install range-parser +``` + +## API + +```js +var parseRange = require('range-parser') +``` + +### parseRange(size, header) + +Parse the given `header` string where `size` is the maximum size of the resource. +An array of ranges will be returned or negative numbers indicating an error parsing. + + * `-2` signals a malformed header string + * `-1` signals an invalid range + +```js +// parse header from request +var range = parseRange(req.headers.range) + +// the type of the range +if (range.type === 'bytes') { + // the ranges + range.forEach(function (r) { + // do something with r.start and r.end + }) +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/range-parser.svg +[npm-url]: https://npmjs.org/package/range-parser +[node-version-image]: https://img.shields.io/node/v/range-parser.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/range-parser.svg +[travis-url]: https://travis-ci.org/jshttp/range-parser +[coveralls-image]: https://img.shields.io/coveralls/jshttp/range-parser.svg +[coveralls-url]: https://coveralls.io/r/jshttp/range-parser +[downloads-image]: https://img.shields.io/npm/dm/range-parser.svg +[downloads-url]: https://npmjs.org/package/range-parser diff --git a/5-1/service/node_modules/express/node_modules/range-parser/index.js b/5-1/service/node_modules/express/node_modules/range-parser/index.js new file mode 100644 index 0000000..814e533 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/range-parser/index.js @@ -0,0 +1,63 @@ +/*! + * range-parser + * Copyright(c) 2012-2014 TJ Holowaychuk + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = rangeParser; + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @return {Array} + * @public + */ + +function rangeParser(size, str) { + var valid = true; + var i = str.indexOf('='); + + if (-1 == i) return -2; + + var arr = str.slice(i + 1).split(',').map(function(range){ + var range = range.split('-') + , start = parseInt(range[0], 10) + , end = parseInt(range[1], 10); + + // -nnn + if (isNaN(start)) { + start = size - end; + end = size - 1; + // nnn- + } else if (isNaN(end)) { + end = size - 1; + } + + // limit last-byte-pos to current length + if (end > size - 1) end = size - 1; + + // invalid + if (isNaN(start) + || isNaN(end) + || start > end + || start < 0) valid = false; + + return { + start: start, + end: end + }; + }); + + arr.type = str.slice(0, i); + + return valid ? arr : -1; +} diff --git a/5-1/service/node_modules/express/node_modules/range-parser/package.json b/5-1/service/node_modules/express/node_modules/range-parser/package.json new file mode 100644 index 0000000..5d4411b --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/range-parser/package.json @@ -0,0 +1,75 @@ +{ + "name": "range-parser", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "description": "Range header field string parser", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "range", + "parser", + "http" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/range-parser.git" + }, + "devDependencies": { + "istanbul": "0.4.0", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "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" + }, + "gitHead": "18e46a3de74afff9f4e22717f11ddd6e9aa6d845", + "bugs": { + "url": "https://github.com/jshttp/range-parser/issues" + }, + "homepage": "https://github.com/jshttp/range-parser", + "_id": "range-parser@1.0.3", + "_shasum": "6872823535c692e2c2a0103826afd82c2e0ff175", + "_from": "range-parser@>=1.0.3 <1.1.0", + "_npmVersion": "1.4.28", + "_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": "6872823535c692e2c2a0103826afd82c2e0ff175", + "tarball": "http://registry.npmjs.org/range-parser/-/range-parser-1.0.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/send/HISTORY.md b/5-1/service/node_modules/express/node_modules/send/HISTORY.md new file mode 100644 index 0000000..d3dca9c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/HISTORY.md @@ -0,0 +1,310 @@ +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * 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: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.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/5-1/service/node_modules/express/node_modules/send/LICENSE b/5-1/service/node_modules/express/node_modules/send/LICENSE new file mode 100644 index 0000000..e4d595b --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +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: + +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/5-1/service/node_modules/express/node_modules/send/README.md b/5-1/service/node_modules/express/node_modules/send/README.md new file mode 100644 index 0000000..3586060 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/README.md @@ -0,0 +1,195 @@ +# send + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Send is a library for streaming files from the file system as a http response +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. + +Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). + +## 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"). + + - `'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. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### 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 example + +```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 +[npm-url]: https://npmjs.org/package/send +[travis-image]: https://img.shields.io/travis/pillarjs/send/master.svg?label=linux +[travis-url]: https://travis-ci.org/pillarjs/send +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/send/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/send +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/send/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master +[downloads-image]: https://img.shields.io/npm/dm/send.svg +[downloads-url]: https://npmjs.org/package/send +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/5-1/service/node_modules/express/node_modules/send/index.js b/5-1/service/node_modules/express/node_modules/send/index.js new file mode 100644 index 0000000..3510989 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/index.js @@ -0,0 +1,820 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('send') +var deprecate = require('depd')('send') +var destroy = require('destroy') +var escapeHtml = require('escape-html') + , parseRange = require('range-parser') + , Stream = require('stream') + , mime = require('mime') + , fresh = require('fresh') + , path = require('path') + , fs = require('fs') + , normalize = path.normalize + , join = path.join +var etag = require('etag') +var EventEmitter = require('events').EventEmitter; +var ms = require('ms'); +var onFinished = require('on-finished') +var statuses = require('statuses') + +/** + * Variables. + */ +var extname = path.extname +var maxMaxAge = 60 * 60 * 24 * 365 * 1000; // 1 year +var resolve = path.resolve +var sep = path.sep +var toString = Object.prototype.toString +var upPathRegexp = /(?:^|[\\\/])\.\.(?:[\\\/]|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = send +module.exports.mime = mime + +/** + * Shim EventEmitter.listenerCount for node.js < 0.10 + */ + +/* istanbul ignore next */ +var listenerCount = EventEmitter.listenerCount + || function(emitter, type){ return emitter.listeners(type).length; }; + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ + +function send(req, path, options) { + return new SendStream(req, path, options); +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ + +function SendStream(req, path, options) { + var opts = options || {} + + this.options = opts + this.path = path + this.req = req + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true + + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' + + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + this._hidden = Boolean(opts.hidden) + + if (opts.hidden !== undefined) { + deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') + } + + // legacy support + if (opts.dotfiles === undefined) { + this._dotfiles = undefined + } + + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] + + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] + + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true + + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), maxMaxAge) + : 0 + + this._root = opts.root + ? resolve(opts.root) + : null + + if (!this._root && opts.from) { + this.from(opts.from) + } +} + +/** + * Inherits from `Stream.prototype`. + */ + +SendStream.prototype.__proto__ = Stream.prototype; + +/** + * Enable or disable etag generation. + * + * @param {Boolean} val + * @return {SendStream} + * @api public + */ + +SendStream.prototype.etag = deprecate.function(function etag(val) { + val = Boolean(val); + debug('etag %s', val); + this._etag = val; + return this; +}, 'send.etag: pass etag as option'); + +/** + * Enable or disable "hidden" (dot) files. + * + * @param {Boolean} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.hidden = deprecate.function(function hidden(val) { + val = Boolean(val); + debug('hidden %s', val); + this._hidden = val; + this._dotfiles = undefined + return this; +}, 'send.hidden: use dotfiles option'); + +/** + * Set index `paths`, set to a falsy + * value to disable index support. + * + * @param {String|Boolean|Array} paths + * @return {SendStream} + * @api public + */ + +SendStream.prototype.index = deprecate.function(function index(paths) { + var index = !paths ? [] : normalizeList(paths, 'paths argument'); + debug('index %o', paths); + this._index = index; + return this; +}, 'send.index: pass index as option'); + +/** + * Set root `path`. + * + * @param {String} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.root = function(path){ + path = String(path); + this._root = resolve(path) + return this; +}; + +SendStream.prototype.from = deprecate.function(SendStream.prototype.root, + 'send.from: pass root as option'); + +SendStream.prototype.root = deprecate.function(SendStream.prototype.root, + 'send.root: pass root as option'); + +/** + * Set max-age to `maxAge`. + * + * @param {Number} maxAge + * @return {SendStream} + * @api public + */ + +SendStream.prototype.maxage = deprecate.function(function maxage(maxAge) { + maxAge = typeof maxAge === 'string' + ? ms(maxAge) + : Number(maxAge); + if (isNaN(maxAge)) maxAge = 0; + if (Infinity == maxAge) maxAge = 60 * 60 * 24 * 365 * 1000; + debug('max-age %d', maxAge); + this._maxage = maxAge; + return this; +}, 'send.maxage: pass maxAge as option'); + +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [error] + * @private + */ + +SendStream.prototype.error = function error(status, error) { + // emit if listeners instead of responding + if (listenerCount(this, 'error') !== 0) { + return this.emit('error', createError(error, status, { + expose: false + })) + } + + var res = this.res + var msg = statuses[status] + + // wipe all existing headers + res._headers = null + + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/plain; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(msg) +} + +/** + * Check if the pathname ends with "/". + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.hasTrailingSlash = function(){ + return '/' == this.path[this.path.length - 1]; +}; + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function(){ + return this.req.headers['if-none-match'] + || this.req.headers['if-modified-since']; +}; + +/** + * Strip content-* header fields. + * + * @private + */ + +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields() { + var res = this.res + var headers = Object.keys(res._headers || {}) + + for (var i = 0; i < headers.length; i++) { + var header = headers[i] + if (header.substr(0, 8) === 'content-' && header !== 'content-location') { + res.removeHeader(header) + } + } +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function(){ + var res = this.res; + debug('not modified'); + this.removeContentHeaderFields(); + res.statusCode = 304; + res.end(); +}; + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent(){ + var err = new Error('Can\'t set headers after they are sent.'); + debug('headers already sent'); + this.error(500, err); +}; + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function(){ + var res = this.res; + return (res.statusCode >= 200 && res.statusCode < 300) || 304 == res.statusCode; +}; + +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ + +SendStream.prototype.onStatError = function onStatError(error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function(){ + return fresh(this.req.headers, this.res._headers); +}; + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh(){ + var ifRange = this.req.headers['if-range']; + + if (!ifRange) return true; + + return ~ifRange.indexOf('"') + ? ~ifRange.indexOf(this.res._headers['etag']) + : Date.parse(this.res._headers['last-modified']) <= Date.parse(ifRange); +}; + +/** + * Redirect to path. + * + * @param {string} path + * @private + */ + +SendStream.prototype.redirect = function redirect(path) { + if (listenerCount(this, 'directory') !== 0) { + this.emit('directory') + return + } + + if (this.hasTrailingSlash()) { + this.error(403) + return + } + + var loc = path + '/' + var msg = 'Redirecting to ' + escapeHtml(loc) + '\n' + var res = this.res + + // redirect + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(msg) +} + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function(res){ + var self = this + , args = arguments + , root = this._root; + + // references + this.res = res; + + // decode the path + var path = decode(this.path) + if (path === -1) return this.error(400) + + // null byte(s) + if (~path.indexOf('\0')) return this.error(400); + + var parts + if (root !== null) { + // malicious path + 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 { + // ".." is malicious without "root" + if (upPathRegexp.test(path)) { + debug('malicious path "%s"', path) + return this.error(403) + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + // dotfile handling + if (containsDotFile(parts)) { + var access = this._dotfiles + + // legacy support + if (access === undefined) { + access = parts[parts.length - 1][0] === '.' + ? (this._hidden ? 'allow' : 'ignore') + : 'allow' + } + + debug('%s dotfile "%s"', access, path) + switch (access) { + case 'allow': + break + case 'deny': + return this.error(403) + case 'ignore': + default: + return this.error(404) + } + } + + // index file support + if (this._index.length && this.path[this.path.length - 1] === '/') { + this.sendIndex(path); + return res; + } + + this.sendFile(path); + return res; +}; + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function(path, stat){ + var len = stat.size; + var options = this.options + var opts = {} + var res = this.res; + var req = this.req; + var ranges = req.headers.range; + var offset = options.start || 0; + + if (res._header) { + // impossible to send now + return this.headersAlreadySent(); + } + + debug('pipe "%s"', path) + + // set header fields + this.setHeader(path, stat); + + // set content-type + this.type(path); + + // conditional GET support + if (this.isConditionalGET() + && this.isCachable() + && this.isFresh()) { + return this.notModified(); + } + + // adjust len to start/end options + len = Math.max(0, len - offset); + if (options.end !== undefined) { + var bytes = options.end - offset + 1; + if (len > bytes) len = bytes; + } + + // Range support + if (ranges) { + ranges = parseRange(len, ranges); + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale'); + ranges = -2; + } + + // unsatisfiable + if (-1 == ranges) { + debug('range unsatisfiable'); + res.setHeader('Content-Range', 'bytes */' + stat.size); + return this.error(416); + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (-2 != ranges && ranges.length === 1) { + debug('range %j', ranges); + + // Content-Range + res.statusCode = 206; + res.setHeader('Content-Range', 'bytes ' + + ranges[0].start + + '-' + + ranges[0].end + + '/' + + len); + + 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, opts) +}; + +/** + * Transfer file for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendFile = function sendFile(path) { + var i = 0 + var self = this + + debug('stat "%s"', path); + fs.stat(path, function onstat(err, stat) { + if (err && err.code === 'ENOENT' + && !extname(path) + && path[path.length - 1] !== sep) { + // not found, check extensions + return next(err) + } + if (err) return self.onStatError(err) + if (stat.isDirectory()) return self.redirect(self.path) + self.emit('file', path, stat) + self.send(path, stat) + }) + + function next(err) { + if (self._extensions.length <= i) { + return err + ? self.onStatError(err) + : self.error(404) + } + + var p = path + '.' + self._extensions[i++] + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } +} + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex(path){ + var i = -1; + var self = this; + + function next(err){ + if (++i >= self._index.length) { + if (err) return self.onStatError(err); + return self.error(404); + } + + var p = join(path, self._index[i]); + + debug('stat "%s"', p); + fs.stat(p, function(err, stat){ + if (err) return next(err); + if (stat.isDirectory()) return next(); + self.emit('file', p, stat); + self.send(p, stat); + }); + } + + next(); +}; + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function(path, options){ + // TODO: this is all lame, refactor meeee + var finished = false; + var self = this; + var res = this.res; + var req = this.req; + + // pipe + var stream = fs.createReadStream(path, options); + this.emit('stream', stream); + stream.pipe(res); + + // response finished, done with the fd + onFinished(res, function onfinished(){ + finished = true; + destroy(stream); + }); + + // error handling code-smell + stream.on('error', function onerror(err){ + // request already finished + if (finished) return; + + // clean up stream + finished = true; + destroy(stream); + + // error + self.onStatError(err); + }); + + // end + stream.on('end', function onend(){ + self.emit('end'); + }); +}; + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function(path){ + var res = this.res; + if (res.getHeader('Content-Type')) return; + var type = mime.lookup(path); + var charset = mime.charsets.lookup(type); + debug('content-type %s', type); + res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')); +}; + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader(path, stat){ + var res = this.res; + + this.emit('headers', res, path, stat); + + if (!res.getHeader('Accept-Ranges')) res.setHeader('Accept-Ranges', 'bytes'); + if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + Math.floor(this._maxage / 1000)); + + if (this._lastModified && !res.getHeader('Last-Modified')) { + var modified = stat.mtime.toUTCString() + debug('modified %s', modified) + res.setHeader('Last-Modified', modified) + } + + if (this._etag && !res.getHeader('ETag')) { + var val = etag(stat) + debug('etag %s', val) + res.setHeader('ETag', val) + } +}; + +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ + +function containsDotFile(parts) { + for (var i = 0; i < parts.length; i++) { + if (parts[i][0] === '.') { + return true + } + } + + return false +} + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +function decode(path) { + try { + return decodeURIComponent(path) + } catch (err) { + return -1 + } +} + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +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/5-1/service/node_modules/express/node_modules/send/node_modules/.bin/mime b/5-1/service/node_modules/express/node_modules/send/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/LICENSE b/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/README.md b/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/README.md new file mode 100644 index 0000000..6474bc3 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/README.md @@ -0,0 +1,60 @@ +# Destroy + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Destroy a stream. + +This module is meant to ensure a stream gets destroyed, handling different APIs +and Node.js bugs. + +## API + +```js +var destroy = require('destroy') +``` + +### destroy(stream) + +Destroy the given stream. In most cases, this is identical to a simple +`stream.destroy()` call. The rules are as follows for a given stream: + + 1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()` + and add a listener to the `open` event to call `stream.close()` if it is + fired. This is for a Node.js bug that will leak a file descriptor if + `.destroy()` is called before `open`. + 2. If the `stream` is not an instance of `Stream`, then nothing happens. + 3. If the `stream` has a `.destroy()` method, then call it. + +The function returns the `stream` passed in as the argument. + +## Example + +```js +var destroy = require('destroy') + +var fs = require('fs') +var stream = fs.createReadStream('package.json') + +// ... and later +destroy(stream) +``` + +[npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square +[npm-url]: https://npmjs.org/package/destroy +[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square +[github-url]: https://github.com/stream-utils/destroy/tags +[travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square +[travis-url]: https://travis-ci.org/stream-utils/destroy +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master +[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/destroy +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/index.js b/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/index.js new file mode 100644 index 0000000..6da2d26 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/index.js @@ -0,0 +1,75 @@ +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var ReadStream = require('fs').ReadStream +var Stream = require('stream') + +/** + * Module exports. + * @public + */ + +module.exports = destroy + +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ + +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) + } + + if (!(stream instanceof Stream)) { + return stream + } + + if (typeof stream.destroy === 'function') { + stream.destroy() + } + + return stream +} + +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ + +function destroyReadStream(stream) { + stream.destroy() + + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } + + return stream +} + +/** + * On open handler to close stream. + * @private + */ + +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } +} diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/package.json b/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/package.json new file mode 100644 index 0000000..f7f3f16 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/destroy/package.json @@ -0,0 +1,72 @@ +{ + "name": "destroy", + "description": "destroy a stream if possible", + "version": "1.0.4", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/destroy.git" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4" + }, + "scripts": { + "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" + }, + "files": [ + "index.js", + "LICENSE" + ], + "keywords": [ + "stream", + "streams", + "destroy", + "cleanup", + "leak", + "fd" + ], + "gitHead": "86edea01456f5fa1027f6a47250c34c713cbcc3b", + "bugs": { + "url": "https://github.com/stream-utils/destroy/issues" + }, + "homepage": "https://github.com/stream-utils/destroy", + "_id": "destroy@1.0.4", + "_shasum": "978857442c44749e4206613e37946205826abd80", + "_from": "destroy@>=1.0.4 <1.1.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" + } + ], + "dist": { + "shasum": "978857442c44749e4206613e37946205826abd80", + "tarball": "http://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md new file mode 100644 index 0000000..4c7087d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md @@ -0,0 +1,76 @@ +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/README.md b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/README.md new file mode 100644 index 0000000..520271e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/README.md @@ -0,0 +1,63 @@ +# http-errors + +[![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] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Example + +```js +var createError = require('http-errors'); + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')); + next(); +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +### Error Properties + +- `message` +- `status` and `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + +```js +var err = createError(404, 'This video does not exist!'); +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### new createError\[code || name\](\[msg]\)) + +```js +var err = new createError.NotFound(); +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/http-errors.svg?style=flat +[npm-url]: https://npmjs.org/package/http-errors +[node-version-image]: https://img.shields.io/node/v/http-errors.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/http-errors.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/http-errors +[coveralls-image]: https://img.shields.io/coveralls/jshttp/http-errors.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors +[downloads-image]: https://img.shields.io/npm/dm/http-errors.svg?style=flat +[downloads-url]: https://npmjs.org/package/http-errors diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/index.js b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/index.js new file mode 100644 index 0000000..d84b114 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/index.js @@ -0,0 +1,120 @@ + +var statuses = require('statuses'); +var inherits = require('inherits'); + +function toIdentifier(str) { + return str.split(' ').map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }).join('').replace(/[^ _0-9a-z]/gi, '') +} + +exports = module.exports = function httpError() { + // so much arity going on ~_~ + var err; + var msg; + var status = 500; + var props = {}; + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (arg instanceof Error) { + err = arg; + status = err.status || err.statusCode || status; + continue; + } + switch (typeof arg) { + case 'string': + msg = arg; + break; + case 'number': + status = arg; + break; + case 'object': + props = arg; + break; + } + } + + if (typeof status !== 'number' || !statuses[status]) { + status = 500 + } + + // constructor + var HttpError = exports[status] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, httpError) + } + + if (!HttpError || !(err instanceof HttpError)) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err; +}; + +// create generic error objects +var codes = statuses.codes.filter(function (num) { + return num >= 400; +}); + +codes.forEach(function (code) { + var name = toIdentifier(statuses[code]) + var className = name.match(/Error$/) ? name : name + 'Error' + + if (code >= 500) { + var ServerError = function ServerError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ServerError) + self.__proto__ = ServerError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ServerError, Error); + ServerError.prototype.status = + ServerError.prototype.statusCode = code; + ServerError.prototype.expose = false; + exports[code] = + exports[name] = ServerError + return; + } + + var ClientError = function ClientError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ClientError) + self.__proto__ = ClientError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ClientError, Error); + ClientError.prototype.status = + ClientError.prototype.statusCode = code; + ClientError.prototype.expose = true; + exports[code] = + exports[name] = ClientError + return; +}); + +// backwards-compatibility +exports["I'mateapot"] = exports.ImATeapot diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +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/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +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/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +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/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json new file mode 100644 index 0000000..93d5078 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json @@ -0,0 +1,50 @@ +{ + "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.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "_id": "inherits@2.0.1", + "dist": { + "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/inherits#readme" +} diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +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/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/package.json b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/package.json new file mode 100644 index 0000000..41f845d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/http-errors/package.json @@ -0,0 +1,85 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "1.3.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Alan Plum", + "email": "me@pluma.io" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/http-errors.git" + }, + "dependencies": { + "inherits": "~2.0.1", + "statuses": "1" + }, + "devDependencies": { + "istanbul": "0", + "mocha": "1" + }, + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ], + "gitHead": "89a8502b40d5dd42da2908f265275e2eeb8d0699", + "bugs": { + "url": "https://github.com/jshttp/http-errors/issues" + }, + "homepage": "https://github.com/jshttp/http-errors", + "_id": "http-errors@1.3.1", + "_shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "_from": "http-errors@>=1.3.1 <1.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "egeste", + "email": "npm@egeste.net" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "tarball": "http://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/mime/.npmignore b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/.npmignore new file mode 100644 index 0000000..e69de29 diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/mime/LICENSE b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/LICENSE new file mode 100644 index 0000000..451fc45 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/mime/README.md b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/README.md new file mode 100644 index 0000000..506fbe5 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/README.md @@ -0,0 +1,90 @@ +# mime + +Comprehensive MIME type mapping API based on mime-db module. + +## Install + +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. + +```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.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + +```js +mime.extension('text/html'); // => 'html' +mime.extension('application/octet-stream'); // => 'bin' +``` + +### mime.charsets.lookup() + +Map mime-type to charset + +```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 + +Custom type mappings can be added on a per-project basis via the following APIs. + +### mime.define() + +Add custom mime/extension mappings + +```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' +``` + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + +```js +mime.extension('text/x-some-format'); // => 'x-sf' +``` + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + +```js +mime.load('./my_project.types'); +``` +The .types file format is simple - See the `types` dir for examples. diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/mime/build/build.js b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/build/build.js new file mode 100644 index 0000000..ed5313e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/build/build.js @@ -0,0 +1,11 @@ +var db = require('mime-db'); + +var mapByType = {}; +Object.keys(db).forEach(function(key) { + var extensions = db[key].extensions; + if (extensions) { + mapByType[key] = extensions; + } +}); + +console.log(JSON.stringify(mapByType)); diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/mime/build/test.js b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/build/test.js new file mode 100644 index 0000000..58b9ba7 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/build/test.js @@ -0,0 +1,57 @@ +/** + * Usage: node test.js + */ + +var mime = require('../mime'); +var assert = require('assert'); +var path = require('path'); + +// +// Test mime lookups +// + +assert.equal('text/plain', mime.lookup('text.txt')); // normal file +assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase +assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file +assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file +assert.equal('text/plain', mime.lookup('.txt')); // nameless +assert.equal('text/plain', mime.lookup('txt')); // extension-only +assert.equal('text/plain', mime.lookup('/txt')); // extension-less () +assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less +assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized +assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +assert.equal('txt', mime.extension(mime.types.text)); +assert.equal('html', mime.extension(mime.types.htm)); +assert.equal('bin', mime.extension('application/octet-stream')); +assert.equal('bin', mime.extension('application/octet-stream ')); +assert.equal('html', mime.extension(' text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html; charset=UTF-8 ')); +assert.equal('html', mime.extension('text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html ; charset=UTF-8')); +assert.equal('html', mime.extension('text/html;charset=UTF-8')); +assert.equal('html', mime.extension('text/Html;charset=UTF-8')); +assert.equal(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +assert.equal('application/font-woff', mime.lookup('file.woff')); +assert.equal('application/octet-stream', mime.lookup('file.buffer')); +assert.equal('audio/mp4', mime.lookup('file.m4a')); +assert.equal('font/opentype', mime.lookup('file.otf')); + +// +// Test charsets +// + +assert.equal('UTF-8', mime.charsets.lookup('text/plain')); +assert.equal(undefined, mime.charsets.lookup(mime.types.js)); +assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +console.log('\nAll tests passed'); diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/mime/cli.js b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/cli.js new file mode 100755 index 0000000..20b1ffe --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/cli.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node + +var mime = require('./mime.js'); +var file = process.argv[2]; +var type = mime.lookup(file); + +process.stdout.write(type + '\n'); + diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/mime/mime.js b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/mime.js new file mode 100644 index 0000000..341b6a5 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/mime.js @@ -0,0 +1,108 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts]) { + console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Define built-in types +mime.define(require('./types.json')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/mime/package.json b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/package.json new file mode 100644 index 0000000..31e7669 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/package.json @@ -0,0 +1,73 @@ +{ + "author": { + "name": "Robert Kieffer", + "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", + "email": "benjamin@benjaminthomas.org", + "url": "http://github.com/bentomas" + } + ], + "description": "A comprehensive library for mime-type mapping", + "licenses": [ + { + "type": "MIT", + "url": "https://raw.github.com/broofa/node-mime/master/LICENSE" + } + ], + "dependencies": {}, + "devDependencies": { + "mime-db": "^1.2.0" + }, + "keywords": [ + "util", + "mime" + ], + "main": "mime.js", + "name": "mime", + "repository": { + "url": "git+https://github.com/broofa/node-mime.git", + "type": "git" + }, + "version": "1.3.4", + "gitHead": "1628f6e0187095009dcef4805c3a49706f137974", + "bugs": { + "url": "https://github.com/broofa/node-mime/issues" + }, + "homepage": "https://github.com/broofa/node-mime", + "_id": "mime@1.3.4", + "_shasum": "115f9e3b6b3daf2959983cb38f149a2d40eb5d53", + "_from": "mime@1.3.4", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "broofa", + "email": "robert@broofa.com" + }, + "maintainers": [ + { + "name": "broofa", + "email": "robert@broofa.com" + }, + { + "name": "bentomas", + "email": "benjamin@benjaminthomas.org" + } + ], + "dist": { + "shasum": "115f9e3b6b3daf2959983cb38f149a2d40eb5d53", + "tarball": "http://registry.npmjs.org/mime/-/mime-1.3.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime/-/mime-1.3.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/mime/types.json b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/types.json new file mode 100644 index 0000000..c674b1c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/mime/types.json @@ -0,0 +1 @@ +{"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomsvc+xml":["atomsvc"],"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/cu-seeme":["cu"],"application/dash+xml":["mdp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/font-tdpfr":["pfr"],"application/font-woff":["woff"],"application/font-woff2":["woff2"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/java-archive":["jar"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","buffer"],"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/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"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/postscript":["ai","eps","ps"],"application/prs.cww":["cww"],"application/pskc+xml":["pskcxml"],"application/rdf+xml":["rdf"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"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-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"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.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"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.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.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"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.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.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"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.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"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.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"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.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"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.gmx":["gmx"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"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+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"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.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.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"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.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.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.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"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.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"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-officetheme":["thmx"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["stl"],"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-project":["mpp","mpt"],"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.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"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.n-gage.data":["ngdat"],"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.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.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"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.sailingtracker.track":["st"],"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.teacher":["teacher"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"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.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.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"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.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.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"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.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/voicexml+xml":["vxml"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"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-chrome-extension":["crx"],"application/x-conference":["nsc"],"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-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-otf":["otf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-ttf":["ttf","ttc"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"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-hdf":["hdf"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["iso"],"application/x-java-jnlp-file":["jnlp"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"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-web-app-manifest+json":["webapp"],"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/xaml+xml":["xaml"],"application/xcap-diff+xml":["xdf"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xml":["xml","xsl","xsd"],"application/xml-dtd":["dtd"],"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/adpcm":["adp"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mp4":["mp4a","m4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"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-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-xyz":["xyz"],"font/opentype":["otf"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/g3fax":["g3"],"image/gif":["gif"],"image/ief":["ief"],"image/jpeg":["jpeg","jpg","jpe"],"image/ktx":["ktx"],"image/png":["png"],"image/prs.btif":["btif"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/tiff":["tiff","tif"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["sub"],"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.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"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/rfc822":["eml","mime"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.vtu":["vtu"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["x3db","x3dbz"],"model/x3d+vrml":["x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee"],"text/css":["css"],"text/csv":["csv"],"text/hjson":["hjson"],"text/html":["html","htm"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/prs.lines.tag":["dsc"],"text/richtext":["rtx"],"text/sgml":["sgml","sgm"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"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.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/vtt":["vtt"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["markdown","md","mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-pascal":["p","pas"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"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/5-1/service/node_modules/express/node_modules/send/node_modules/ms/.npmignore b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/ms/History.md b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/ms/LICENSE b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/5-1/service/node_modules/express/node_modules/send/node_modules/ms/README.md b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/ms/index.js b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/5-1/service/node_modules/express/node_modules/send/node_modules/ms/package.json b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/LICENSE b/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/README.md b/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/README.md new file mode 100644 index 0000000..f6ae24c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/README.md @@ -0,0 +1,114 @@ +# Statuses + +[![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] + +HTTP status utility for node. + +## API + +```js +var status = require('statuses'); +``` + +### var code = status(Integer || String) + +If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown. + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status('forbidden') // => 403 +status('Forbidden') // => 403 +status(306) // throws, as it's not supported by node.js +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### var msg = status[code] + +Map of `code` to `status message`. `undefined` for invalid `code`s. + +```js +status[404] // => 'Not Found' +``` + +### var code = status[msg] + +Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s. + +```js +status['not found'] // => 404 +status['Not Found'] // => 404 +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +### statuses/codes.json + +```js +var codes = require('statuses/codes.json'); +``` + +This is a JSON file of the status codes +taken from `require('http').STATUS_CODES`. +This is saved so that codes are consistent even in older node.js versions. +For example, `308` will be added in v0.12. + +## Adding Status Codes + +The status codes are primarily sourced from http://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv. +Additionally, custom codes are added from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes. +These are added manually in the `lib/*.json` files. +If you would like to add a status code, add it to the appropriate JSON file. + +To rebuild `codes.json`, run the following: + +```bash +# update src/iana.json +npm run update +# build codes.json +npm run build +``` + +[npm-image]: https://img.shields.io/npm/v/statuses.svg?style=flat +[npm-url]: https://npmjs.org/package/statuses +[node-version-image]: http://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/statuses.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/statuses +[coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[downloads-image]: http://img.shields.io/npm/dm/statuses.svg?style=flat +[downloads-url]: https://npmjs.org/package/statuses diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/codes.json b/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/codes.json new file mode 100644 index 0000000..4c45a88 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/codes.json @@ -0,0 +1,64 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "(Unused)", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} \ No newline at end of file diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/index.js b/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/index.js new file mode 100644 index 0000000..b06182d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/index.js @@ -0,0 +1,60 @@ + +var codes = require('./codes.json'); + +module.exports = status; + +// [Integer...] +status.codes = Object.keys(codes).map(function (code) { + code = ~~code; + var msg = codes[code]; + status[code] = msg; + status[msg] = status[msg.toLowerCase()] = code; + return code; +}); + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true, +}; + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true, +}; + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true, +}; + +function status(code) { + if (typeof code === 'number') { + if (!status[code]) throw new Error('invalid status code: ' + code); + return code; + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string'); + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n); + return n; + } + + n = status[code.toLowerCase()]; + if (!n) throw new Error('invalid status message: "' + code + '"'); + return n; +} diff --git a/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/package.json b/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/package.json new file mode 100644 index 0000000..81aba72 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/node_modules/statuses/package.json @@ -0,0 +1,84 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "1.2.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/statuses.git" + }, + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "0.0.6", + "istanbul": "0", + "mocha": "1", + "stream-to-array": "2" + }, + "scripts": { + "build": "node scripts/build.js", + "update": "node scripts/update.js", + "test": "mocha --reporter spec --bail --check-leaks", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks" + }, + "gitHead": "49e6ac7ae4c63ee8186f56cb52112a7eeda28ed7", + "bugs": { + "url": "https://github.com/jshttp/statuses/issues" + }, + "homepage": "https://github.com/jshttp/statuses", + "_id": "statuses@1.2.1", + "_shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "_from": "statuses@>=1.2.1 <1.3.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "tarball": "http://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/send/package.json b/5-1/service/node_modules/express/node_modules/send/package.json new file mode 100644 index 0000000..38fcf6f --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/send/package.json @@ -0,0 +1,89 @@ +{ + "name": "send", + "description": "Better streaming static file server with Range and conditional-GET support", + "version": "0.13.1", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/send.git" + }, + "keywords": [ + "static", + "file", + "server" + ], + "dependencies": { + "debug": "~2.2.0", + "depd": "~1.1.0", + "destroy": "~1.0.4", + "escape-html": "~1.0.3", + "etag": "~1.7.0", + "fresh": "0.3.0", + "http-errors": "~1.3.1", + "mime": "1.3.4", + "ms": "0.7.1", + "on-finished": "~2.3.0", + "range-parser": "~1.0.3", + "statuses": "~1.2.1" + }, + "devDependencies": { + "after": "0.8.1", + "istanbul": "0.4.2", + "mocha": "2.3.4", + "supertest": "1.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --check-leaks --reporter spec --bail", + "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": "dbce43fc7102c14b475c25cde918b726063cc991", + "bugs": { + "url": "https://github.com/pillarjs/send/issues" + }, + "homepage": "https://github.com/pillarjs/send", + "_id": "send@0.13.1", + "_shasum": "a30d5f4c82c8a9bae9ad00a1d9b1bdbe6f199ed7", + "_from": "send@0.13.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "a30d5f4c82c8a9bae9ad00a1d9b1bdbe6f199ed7", + "tarball": "http://registry.npmjs.org/send/-/send-0.13.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/send/-/send-0.13.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/serve-static/HISTORY.md b/5-1/service/node_modules/express/node_modules/serve-static/HISTORY.md new file mode 100644 index 0000000..da30741 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/serve-static/HISTORY.md @@ -0,0 +1,303 @@ +1.10.2 / 2016-01-19 +=================== + + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.10.1 / 2016-01-16 +=================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + +1.10.0 / 2015-06-17 +=================== + + * Add `fallthrough` option + - Allows declaring this middleware is the final destination + - Provides better integration with Express patterns + * Fix reading options from options prototype + * Improve the default redirect response headers + * deps: escape-html@1.0.2 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * Fix potential open redirect when mounted at root + +1.7.1 / 2014-10-22 +================== + + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +1.7.0 / 2014-10-15 +================== + + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - 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 +================== + + * Fix redirect loop when index file serving disabled + +1.6.3 / 2014-09-24 +================== + + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +1.6.2 / 2014-09-15 +================== + + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +1.6.1 / 2014-09-07 +================== + + * deps: send@0.9.1 + - deps: fresh@0.2.4 + +1.6.0 / 2014-09-07 +================== + + * deps: send@0.9.0 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + +1.5.4 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +1.5.3 / 2014-08-17 +================== + + * deps: send@0.8.3 + +1.5.2 / 2014-08-14 +================== + + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +1.5.1 / 2014-08-09 +================== + + * Fix parsing of weird `req.originalUrl` values + * deps: parseurl@~1.3.0 + * deps: utils-merge@1.0.0 + +1.5.0 / 2014-08-05 +================== + + * deps: send@0.8.1 + - Add `extensions` option + +1.4.4 / 2014-08-04 +================== + + * deps: send@0.7.4 + - Fix serving index files without root dir + +1.4.3 / 2014-07-29 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + +1.4.2 / 2014-07-27 +================== + + * deps: send@0.7.2 + - deps: depd@0.4.4 + +1.4.1 / 2014-07-26 +================== + + * deps: send@0.7.1 + - deps: depd@0.4.3 + +1.4.0 / 2014-07-21 +================== + + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +1.3.2 / 2014-07-11 +================== + + * deps: send@0.6.0 + - Cap `maxAge` value to 1 year + - deps: debug@1.0.3 + +1.3.1 / 2014-07-09 +================== + + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +1.3.0 / 2014-06-28 +================== + + * Add `setHeaders` option + * Include HTML link in redirect response + * deps: send@0.5.0 + - Accept string for `maxAge` (converted by `ms`) + +1.2.3 / 2014-06-11 +================== + + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +1.2.2 / 2014-06-09 +================== + + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + +1.2.1 / 2014-06-02 +================== + + * use `escape-html` for escaping + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +1.2.0 / 2014-05-29 +================== + + * deps: send@0.4.0 + - Calculate ETag with md5 for reduced collisions + - Fix wrong behavior when index file matches directory + - Ignore stream errors after request ends + - Skip directories in index file search + - deps: debug@0.8.1 + +1.1.0 / 2014-04-24 +================== + + * Accept options directly to `send` module + * deps: send@0.3.0 + +1.0.4 / 2014-04-07 +================== + + * Resolve relative paths at middleware setup + * Use parseurl to parse the URL from request + +1.0.3 / 2014-03-20 +================== + + * Do not rely on connect-like environments + +1.0.2 / 2014-03-06 +================== + + * deps: send@0.2.0 + +1.0.1 / 2014-03-05 +================== + + * Add mime export for back-compat + +1.0.0 / 2014-03-05 +================== + + * Genesis from `connect` diff --git a/5-1/service/node_modules/express/node_modules/serve-static/LICENSE b/5-1/service/node_modules/express/node_modules/serve-static/LICENSE new file mode 100644 index 0000000..d8cce67 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014-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: + +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/5-1/service/node_modules/express/node_modules/serve-static/README.md b/5-1/service/node_modules/express/node_modules/serve-static/README.md new file mode 100644 index 0000000..62104b1 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/serve-static/README.md @@ -0,0 +1,236 @@ +# serve-static + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +## Install + +```sh +$ npm install serve-static +``` + +## API + +```js +var serveStatic = require('serve-static') +``` + +### serveStatic(root, options) + +Create a new middleware function to serve files from within a given root +directory. The file to serve will be determined by combining `req.url` +with the provided root directory. When a file is not found, instead of +sending a 404 response, this module will instead call `next()` to move on +to the next middleware, allowing for stacking and fall-backs. + +#### 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 set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Deny a request for a dotfile and 403/`next()`. + - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. + +The default value is similar to `'ignore'`, with the exception that this +default will not ignore the files within a directory that begins with a dot. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +Set file extension fallbacks. When set, if a file is not found, the given +extensions will be added to the file name and search for. The first that +exists will be served. Example: `['html', 'htm']`. + +The default value is `false`. + +##### fallthrough + +Set the middleware to have client errors fall-through as just unhandled +requests, otherwise forward a client error. The difference is that client +errors like a bad request or a request to a non-existent file will cause +this middleware to simply `next()` to your next middleware when this value +is `true`. When this value is `false`, these errors (even 404s), will invoke +`next(err)`. + +Typically `true` is desired such that multiple physical directories can be +mapped to the same web address or for routes to fill in non-existent files. + +The value `false` can be used if this middleware is mounted at a path that +is designed to be strictly a single file system directory, which allows for +short-circuiting 404s for less overhead. This middleware will also reply to +all methods. + +The default value is `true`. + +##### index + +By default this module will send "index.html" files in response to a request +on a directory. 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. + +##### redirect + +Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. + +##### setHeaders + +Function to set custom headers on response. Alterations to the headers need to +occur synchronously. The function is called as `fn(res, path, stat)`, where +the arguments are: + + - `res` the response object + - `path` the file path that is being sent + - `stat` the stat object of the file that is being sent + +## Examples + +### Serve files with vanilla node.js http server + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', {'index': ['index.html', 'index.htm']}) + +// Create server +var server = http.createServer(function(req, res){ + var done = finalhandler(req, res) + serve(req, res, done) +}) + +// Listen +server.listen(3000) +``` + +### Serve all files as downloads + +```js +var contentDisposition = require('content-disposition') +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { + 'index': false, + 'setHeaders': setHeaders +}) + +// Set header to force download +function setHeaders(res, path) { + res.setHeader('Content-Disposition', contentDisposition(path)) +} + +// Create server +var server = http.createServer(function(req, res){ + var done = finalhandler(req, res) + serve(req, res, done) +}) + +// Listen +server.listen(3000) +``` + +### Serving using express + +#### Simple + +This is a simple example of using Express. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +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 +[npm-url]: https://npmjs.org/package/serve-static +[travis-image]: https://img.shields.io/travis/expressjs/serve-static/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/serve-static +[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 +[downloads-url]: https://npmjs.org/package/serve-static +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://gratipay.com/dougwilson/ diff --git a/5-1/service/node_modules/express/node_modules/serve-static/index.js b/5-1/service/node_modules/express/node_modules/serve-static/index.js new file mode 100644 index 0000000..0a9f494 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/serve-static/index.js @@ -0,0 +1,187 @@ +/*! + * serve-static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var escapeHtml = require('escape-html') +var parseUrl = require('parseurl') +var resolve = require('path').resolve +var send = require('send') +var url = require('url') + +/** + * Module exports. + * @public + */ + +module.exports = serveStatic +module.exports.mime = send.mime + +/** + * @param {string} root + * @param {object} [options] + * @return {function} + * @public + */ + +function serveStatic(root, options) { + if (!root) { + throw new TypeError('root path required') + } + + if (typeof root !== 'string') { + throw new TypeError('root path must be a string') + } + + // copy options object + var opts = Object.create(options || null) + + // fall-though + var fallthrough = opts.fallthrough !== false + + // default redirect + var redirect = opts.redirect !== false + + // headers listener + var setHeaders = opts.setHeaders + + if (setHeaders && typeof setHeaders !== 'function') { + throw new TypeError('option setHeaders must be function') + } + + // setup options for send + opts.maxage = opts.maxage || opts.maxAge || 0 + opts.root = resolve(root) + + // construct directory listener + var onDirectory = redirect + ? createRedirectDirectoryListener() + : createNotFoundDirectoryListener() + + return function serveStatic(req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + if (fallthrough) { + return next() + } + + // method not allowed + res.statusCode = 405 + res.setHeader('Allow', 'GET, HEAD') + res.setHeader('Content-Length', '0') + res.end() + return + } + + var forwardError = !fallthrough + var originalUrl = parseUrl.original(req) + var path = parseUrl(req).pathname + + // make sure redirect occurs at mount + if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { + path = '' + } + + // create send stream + var stream = send(req, path, opts) + + // add directory handler + stream.on('directory', onDirectory) + + // add headers listener + if (setHeaders) { + stream.on('headers', setHeaders) + } + + // add file listener for fallthrough + if (fallthrough) { + stream.on('file', function onFile() { + // once file is determined, always forward error + forwardError = true + }) + } + + // forward errors + stream.on('error', function error(err) { + if (forwardError || !(err.statusCode < 500)) { + next(err) + return + } + + next() + }) + + // pipe + stream.pipe(res) + } +} + +/** + * Collapse all leading slashes into a single slash + * @private + */ +function collapseLeadingSlashes(str) { + for (var i = 0; i < str.length; i++) { + if (str[i] !== '/') { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Create a directory listener that just 404s. + * @private + */ + +function createNotFoundDirectoryListener() { + return function notFound() { + this.error(404) + } +} + +/** + * Create a directory listener that performs a redirect. + * @private + */ + +function createRedirectDirectoryListener() { + return function redirect() { + if (this.hasTrailingSlash()) { + this.error(404) + return + } + + // get original URL + var originalUrl = parseUrl.original(this.req) + + // append trailing slash + originalUrl.path = null + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') + + // reformat the URL + var loc = url.format(originalUrl) + var msg = 'Redirecting to ' + escapeHtml(loc) + '\n' + var res = this.res + + // send redirect response + res.statusCode = 303 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(msg) + } +} diff --git a/5-1/service/node_modules/express/node_modules/serve-static/package.json b/5-1/service/node_modules/express/node_modules/serve-static/package.json new file mode 100644 index 0000000..b789b9a --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/serve-static/package.json @@ -0,0 +1,83 @@ +{ + "name": "serve-static", + "description": "Serve static files", + "version": "1.10.2", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/serve-static.git" + }, + "dependencies": { + "escape-html": "~1.0.3", + "parseurl": "~1.3.1", + "send": "0.13.1" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4", + "supertest": "1.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --reporter spec --bail --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": "aec36c897a33c6c2421fa41cc4947042d67332f6", + "bugs": { + "url": "https://github.com/expressjs/serve-static/issues" + }, + "homepage": "https://github.com/expressjs/serve-static", + "_id": "serve-static@1.10.2", + "_shasum": "feb800d0e722124dd0b00333160c16e9caa8bcb3", + "_from": "serve-static@>=1.10.2 <1.11.0", + "_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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "feb800d0e722124dd0b00333160c16e9caa8bcb3", + "tarball": "http://registry.npmjs.org/serve-static/-/serve-static-1.10.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.10.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/type-is/HISTORY.md b/5-1/service/node_modules/express/node_modules/type-is/HISTORY.md new file mode 100644 index 0000000..e10b426 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/HISTORY.md @@ -0,0 +1,192 @@ +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/5-1/service/node_modules/express/node_modules/type-is/LICENSE b/5-1/service/node_modules/express/node_modules/type-is/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +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: + +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/5-1/service/node_modules/express/node_modules/type-is/README.md b/5-1/service/node_modules/express/node_modules/type-is/README.md new file mode 100644 index 0000000..7a754be --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/README.md @@ -0,0 +1,136 @@ +# type-is + +[![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] + +Infer the content-type of a request. + +### Install + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var is = require('type-is') + +http.createServer(function (req, res) { + var istext = is(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### type = is(request, types) + +`request` is the node HTTP request. `types` is an array of types. + +```js +// req.headers.content-type = 'application/json' + +is(req, ['json']) // 'json' +is(req, ['html', 'json']) // 'json' +is(req, ['application/*']) // 'application/json' +is(req, ['application/json']) // 'application/json' + +is(req, ['html']) // false +``` + +### is.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existance works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + +```js +if (is.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### type = is.is(mediaType, types) + +`mediaType` is the [media type](https://tools.ietf.org/html/rfc6838) string. `types` is an array of types. + +```js +var mediaType = 'application/json' + +is.is(mediaType, ['json']) // 'json' +is.is(mediaType, ['html', 'json']) // 'json' +is.is(mediaType, ['application/*']) // 'application/json' +is.is(mediaType, ['application/json']) // 'application/json' + +is.is(mediaType, ['html']) // false +``` + +### Each type can be: + +- An extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` 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 or the content type is invalid. + +`null` will be returned if the request does not have a body. + +## Examples + +#### Example body parser + +```js +var is = require('type-is'); + +function bodyParser(req, res, next) { + if (!is.hasBody(req)) { + return next() + } + + switch (is(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + break + case 'json': + // parse json body + throw new Error('implement json body parsing') + break + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + break + default: + // 415 error code + res.statusCode = 415 + res.end() + return + } +} +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: https://nodejs.org/en/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[downloads-image]: https://img.shields.io/npm/dm/type-is.svg +[downloads-url]: https://npmjs.org/package/type-is diff --git a/5-1/service/node_modules/express/node_modules/type-is/index.js b/5-1/service/node_modules/express/node_modules/type-is/index.js new file mode 100644 index 0000000..ca2962e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/index.js @@ -0,0 +1,262 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var typer = require('media-typer') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis(value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody(req) { + return req.headers['transfer-encoding'] !== undefined + || !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +function typeofrequest(req, types_) { + var types = types_ + + // no body + if (!hasbody(req)) { + return null + } + + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @private + */ + +function normalize(type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @private + */ + +function mimeMatch(expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // 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) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +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 { + return normalizeType(value) + } catch (err) { + return null + } +} diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md b/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md new file mode 100644 index 0000000..62c2003 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md @@ -0,0 +1,22 @@ +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/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE b/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md b/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md new file mode 100644 index 0000000..d8df623 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md @@ -0,0 +1,81 @@ +# 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/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js b/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js new file mode 100644 index 0000000..07f7295 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js @@ -0,0 +1,270 @@ +/*! + * 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/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json b/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json new file mode 100644 index 0000000..e0f796d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json @@ -0,0 +1,58 @@ +{ + "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": "git+https://github.com/jshttp/media-typer.git" + }, + "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/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..61b54b4 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md @@ -0,0 +1,183 @@ +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +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 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md new file mode 100644 index 0000000..e26295d --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md @@ -0,0 +1,103 @@ +# mime-types + +[![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] + +The ultimate javascript content-type utility. + +Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, + so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db) +- No `.define()` functionality + +Otherwise, the API is compatible. + +## Install + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://github.com/jshttp/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[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/node/v/mime-types.svg +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js new file mode 100644 index 0000000..f7008b2 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js @@ -0,0 +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 + +/** + * 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) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..41a667a --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -0,0 +1,306 @@ +1.21.0 / 2016-01-06 +=================== + + * Add `application/emergencycalldata.comment+xml` + * Add `application/emergencycalldata.deviceinfo+xml` + * Add `application/emergencycalldata.providerinfo+xml` + * Add `application/emergencycalldata.serviceinfo+xml` + * Add `application/emergencycalldata.subscriberinfo+xml` + * Add `application/vnd.filmit.zfc` + * Add `application/vnd.google-apps.document` + * Add `application/vnd.google-apps.presentation` + * Add `application/vnd.google-apps.spreadsheet` + * Add `application/vnd.mapbox-vector-tile` + * Add `application/vnd.ms-printdevicecapabilities+xml` + * Add `application/vnd.ms-windows.devicepairing` + * Add `application/vnd.ms-windows.nwprinting.oob` + * Add `application/vnd.tml` + * Add `audio/evs` + +1.20.0 / 2015-11-10 +=================== + + * Add `application/cdni` + * Add `application/csvm+json` + * Add `application/rfc+xml` + * Add `application/vnd.3gpp.access-transfer-events+xml` + * Add `application/vnd.3gpp.srvcc-ext+xml` + * Add `application/vnd.ms-windows.wsd.oob` + * Add `application/vnd.oxli.countgraph` + * Add `application/vnd.pagerduty+json` + * Add `text/x-suse-ymp` + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.3gpp-prose-pc3ch+xml` + * Add `application/vnd.3gpp.srvcc-info+xml` + * Add `application/vnd.apple.pkpass` + * Add `application/vnd.drive+json` + +1.18.0 / 2015-09-03 +=================== + + * Add `application/pkcs12` + * Add `application/vnd.3gpp-prose+xml` + * Add `application/vnd.3gpp.mid-call+xml` + * Add `application/vnd.3gpp.state-and-event-info+xml` + * Add `application/vnd.anki` + * Add `application/vnd.firemonkeys.cloudcell` + * Add `application/vnd.openblox.game+xml` + * Add `application/vnd.openblox.game-binary` + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +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 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md new file mode 100644 index 0000000..7662440 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md @@ -0,0 +1,82 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +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 + +```bash +npm install mime-db +``` + +### 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 +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + 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 can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +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 +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[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 +[node-url]: http://nodejs.org/download/ diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json new file mode 100644 index 0000000..412ba9e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json @@ -0,0 +1,6552 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana" + }, + "application/3gpp-ims+xml": { + "source": "iana" + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana" + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana" + }, + "application/bacnet-xdd+zip": { + "source": "iana" + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana" + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana" + }, + "application/ccxml+xml": { + "source": "iana", + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana" + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana" + }, + "application/cellml+xml": { + "source": "iana" + }, + "application/cfw": { + "source": "iana" + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana" + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana" + }, + "application/cstadata+xml": { + "source": "iana" + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "extensions": ["mdp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana" + }, + "application/dicom": { + "source": "iana" + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana" + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/emergencycalldata.comment+xml": { + "source": "iana" + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana" + }, + "application/emma+xml": { + "source": "iana", + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana" + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana" + }, + "application/epub+zip": { + "source": "iana", + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana" + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false, + "extensions": ["woff"] + }, + "application/font-woff2": { + "compressible": false, + "extensions": ["woff2"] + }, + "application/framework-attributes+xml": { + "source": "iana" + }, + "application/gml+xml": { + "source": "apache", + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana" + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana" + }, + "application/ibe-pkg-reply+xml": { + "source": "iana" + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana" + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana" + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana" + }, + "application/kpml-response+xml": { + "source": "iana" + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana" + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana" + }, + "application/mathml-presentation+xml": { + "source": "iana" + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana" + }, + "application/mbms-deregister+xml": { + "source": "iana" + }, + "application/mbms-envelope+xml": { + "source": "iana" + }, + "application/mbms-msk+xml": { + "source": "iana" + }, + "application/mbms-msk-response+xml": { + "source": "iana" + }, + "application/mbms-protection-description+xml": { + "source": "iana" + }, + "application/mbms-reception-report+xml": { + "source": "iana" + }, + "application/mbms-register+xml": { + "source": "iana" + }, + "application/mbms-register-response+xml": { + "source": "iana" + }, + "application/mbms-schedule+xml": { + "source": "iana" + }, + "application/mbms-user-service-description+xml": { + "source": "iana" + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana" + }, + "application/media_control+xml": { + "source": "iana" + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mods+xml": { + "source": "iana", + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana" + }, + "application/mrb-publish+xml": { + "source": "iana" + }, + "application/msc-ivr+xml": { + "source": "iana" + }, + "application/msc-mixer+xml": { + "source": "iana" + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "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", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana" + }, + "application/parityfec": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana" + }, + "application/pidf-diff+xml": { + "source": "iana" + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana" + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/provenance+xml": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana" + }, + "application/pskc+xml": { + "source": "iana", + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf"] + }, + "application/reginfo+xml": { + "source": "iana", + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana" + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana" + }, + "application/rls-services+xml": { + "source": "iana", + "extensions": ["rs"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana" + }, + "application/samlmetadata+xml": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana" + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/sep+xml": { + "source": "iana" + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana" + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana" + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "extensions": ["ssml"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/ttml+xml": { + "source": "iana" + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana" + }, + "application/urc-ressheet+xml": { + "source": "iana" + }, + "application/urc-targetdesc+xml": { + "source": "iana" + }, + "application/urc-uisocketdesc+xml": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana" + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana" + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana" + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana" + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "extensions": ["mpkg"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avistar+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "extensions": ["cdxml"] + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana" + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana" + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana" + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume-movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana" + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana" + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana" + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana" + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana" + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana" + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana" + }, + "application/vnd.etsi.cug+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana" + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana" + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana" + }, + "application/vnd.etsi.sci+xml": { + "source": "iana" + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana" + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana" + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana" + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana" + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana" + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana" + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana" + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana" + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana" + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+xml": { + "source": "iana", + "extensions": ["lasxml"] + }, + "application/vnd.liberty-request+xml": { + "source": "iana" + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana" + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana" + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana" + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache" + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana" + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana" + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana" + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana" + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana" + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana" + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana" + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana" + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana" + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana" + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana" + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana" + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana" + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana" + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana" + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana" + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana" + }, + "application/vnd.omads-email+xml": { + "source": "iana" + }, + "application/vnd.omads-file+xml": { + "source": "iana" + }, + "application/vnd.omads-folder+xml": { + "source": "iana" + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana" + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "apache", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "apache", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "apache", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana" + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana" + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos+xml": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "apache" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana" + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana" + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana" + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana" + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana" + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana" + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana" + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana" + }, + "application/vnd.wv.ssp+xml": { + "source": "iana" + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana" + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "extensions": ["vxml"] + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/watcherinfo+xml": { + "source": "iana" + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-otf": { + "source": "apache", + "compressible": true, + "extensions": ["otf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-ttf": { + "source": "apache", + "compressible": true, + "extensions": ["ttf","ttc"] + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "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, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "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, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana" + }, + "application/xaml+xml": { + "source": "apache", + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana" + }, + "application/xcap-caps+xml": { + "source": "iana" + }, + "application/xcap-diff+xml": { + "source": "iana", + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana" + }, + "application/xcap-error+xml": { + "source": "iana" + }, + "application/xcap-ns+xml": { + "source": "iana" + }, + "application/xcon-conference-info+xml": { + "source": "iana" + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana" + }, + "application/xenc+xml": { + "source": "iana", + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache" + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana" + }, + "application/xmpp+xml": { + "source": "iana" + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yin+xml": { + "source": "iana", + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana" + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4a","m4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/opentype": { + "compressible": true, + "extensions": ["otf"] + }, + "image/bmp": { + "source": "apache", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/fits": { + "source": "iana" + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jp2": { + "source": "iana" + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana" + }, + "image/jpx": { + "source": "iana" + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana" + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana" + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tiff","tif"] + }, + "image/tiff-fx": { + "source": "iana" + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana" + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana" + }, + "image/vnd.valve.source.texture": { + "source": "iana" + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "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"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana" + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana" + }, + "message/global-delivery-status": { + "source": "iana" + }, + "message/global-disposition-notification": { + "source": "iana" + }, + "message/global-headers": { + "source": "iana" + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana" + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana" + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hjson": { + "extensions": ["hjson"] + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana" + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["markdown","md","mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "apache" + }, + "video/3gpp": { + "source": "apache", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "apache" + }, + "video/3gpp2": { + "source": "apache", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "apache" + }, + "video/bt656": { + "source": "apache" + }, + "video/celb": { + "source": "apache" + }, + "video/dv": { + "source": "apache" + }, + "video/h261": { + "source": "apache", + "extensions": ["h261"] + }, + "video/h263": { + "source": "apache", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "apache" + }, + "video/h263-2000": { + "source": "apache" + }, + "video/h264": { + "source": "apache", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "apache" + }, + "video/h264-svc": { + "source": "apache" + }, + "video/jpeg": { + "source": "apache", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "apache" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "apache", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "apache" + }, + "video/mp2p": { + "source": "apache" + }, + "video/mp2t": { + "source": "apache", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "apache", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "apache" + }, + "video/mpeg": { + "source": "apache", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "apache" + }, + "video/mpv": { + "source": "apache" + }, + "video/nv": { + "source": "apache" + }, + "video/ogg": { + "source": "apache", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "apache" + }, + "video/pointer": { + "source": "apache" + }, + "video/quicktime": { + "source": "apache", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raw": { + "source": "apache" + }, + "video/rtp-enc-aescm128": { + "source": "apache" + }, + "video/rtx": { + "source": "apache" + }, + "video/smpte292m": { + "source": "apache" + }, + "video/ulpfec": { + "source": "apache" + }, + "video/vc1": { + "source": "apache" + }, + "video/vnd.cctv": { + "source": "apache" + }, + "video/vnd.dece.hd": { + "source": "apache", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "apache", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "apache" + }, + "video/vnd.dece.pd": { + "source": "apache", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "apache", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "apache", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "apache" + }, + "video/vnd.directv.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dvb.file": { + "source": "apache", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "apache", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "apache" + }, + "video/vnd.motorola.video": { + "source": "apache" + }, + "video/vnd.motorola.videop": { + "source": "apache" + }, + "video/vnd.mpegurl": { + "source": "apache", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "apache", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "apache" + }, + "video/vnd.nokia.videovoip": { + "source": "apache" + }, + "video/vnd.objectvideo": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "apache" + }, + "video/vnd.sealed.mpeg4": { + "source": "apache" + }, + "video/vnd.sealed.swf": { + "source": "apache" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "apache" + }, + "video/vnd.uvvu.mp4": { + "source": "apache", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "apache", + "extensions": ["viv"] + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json new file mode 100644 index 0000000..e6c9732 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json @@ -0,0 +1,94 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.21.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "devDependencies": { + "bluebird": "3.1.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "1.0.1", + "gnode": "0.1.1", + "istanbul": "0.4.1", + "mocha": "1.21.5", + "raw-body": "2.1.5", + "stream-to-array": "2.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "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": "9ab92f0a912a602408a64db5741dfef6f82c597f", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "homepage": "https://github.com/jshttp/mime-db", + "_id": "mime-db@1.21.0", + "_shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "_from": "mime-db@>=1.21.0 <1.22.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" + } + ], + "dist": { + "shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json new file mode 100644 index 0000000..d1a5ffa --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json @@ -0,0 +1,84 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "dependencies": { + "mime-db": "~1.21.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec test/test.js", + "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": "329f1c77e1a77c8fac59b15038e3808e9e314d96", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "homepage": "https://github.com/jshttp/mime-types", + "_id": "mime-types@2.1.9", + "_shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "_from": "mime-types@>=2.1.6 <2.2.0", + "_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" + } + ], + "dist": { + "shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/type-is/package.json b/5-1/service/node_modules/express/node_modules/type-is/package.json new file mode 100644 index 0000000..26b6fae --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/type-is/package.json @@ -0,0 +1,81 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "1.6.11", + "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": "git+https://github.com/jshttp/type-is.git" + }, + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.9" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "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/" + }, + "keywords": [ + "content", + "type", + "checking" + ], + "gitHead": "8e60e3e78aef84928e0e6c09da950f6950adcdd2", + "bugs": { + "url": "https://github.com/jshttp/type-is/issues" + }, + "homepage": "https://github.com/jshttp/type-is", + "_id": "type-is@1.6.11", + "_shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "_from": "type-is@>=1.6.6 <1.7.0", + "_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": "ritch", + "email": "skawful@gmail.com" + } + ], + "dist": { + "shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "tarball": "http://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/node_modules/utils-merge/.travis.yml b/5-1/service/node_modules/express/node_modules/utils-merge/.travis.yml new file mode 100644 index 0000000..af92b02 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/utils-merge/.travis.yml @@ -0,0 +1,6 @@ +language: "node_js" +node_js: + - "0.4" + - "0.6" + - "0.8" + - "0.10" diff --git a/5-1/service/node_modules/express/node_modules/utils-merge/LICENSE b/5-1/service/node_modules/express/node_modules/utils-merge/LICENSE new file mode 100644 index 0000000..e33bd10 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/utils-merge/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2013 Jared Hanson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-1/service/node_modules/express/node_modules/utils-merge/README.md b/5-1/service/node_modules/express/node_modules/utils-merge/README.md new file mode 100644 index 0000000..2f94e9b --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/utils-merge/README.md @@ -0,0 +1,34 @@ +# utils-merge + +Merges the properties from a source object into a destination object. + +## Install + + $ npm install utils-merge + +## Usage + +```javascript +var a = { foo: 'bar' } + , b = { bar: 'baz' }; + +merge(a, b); +// => { foo: 'bar', bar: 'baz' } +``` + +## Tests + + $ npm install + $ npm test + +[![Build Status](https://secure.travis-ci.org/jaredhanson/utils-merge.png)](http://travis-ci.org/jaredhanson/utils-merge) + +## Credits + + - [Jared Hanson](http://github.com/jaredhanson) + +## License + +[The MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> diff --git a/5-1/service/node_modules/express/node_modules/utils-merge/index.js b/5-1/service/node_modules/express/node_modules/utils-merge/index.js new file mode 100644 index 0000000..4265c69 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/utils-merge/index.js @@ -0,0 +1,23 @@ +/** + * Merge object b with object a. + * + * var a = { foo: 'bar' } + * , b = { bar: 'baz' }; + * + * merge(a, b); + * // => { foo: 'bar', bar: 'baz' } + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api public + */ + +exports = module.exports = function(a, b){ + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; +}; diff --git a/5-1/service/node_modules/express/node_modules/utils-merge/package.json b/5-1/service/node_modules/express/node_modules/utils-merge/package.json new file mode 100644 index 0000000..2f9660e --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/utils-merge/package.json @@ -0,0 +1,60 @@ +{ + "name": "utils-merge", + "version": "1.0.0", + "description": "merge() utility function", + "keywords": [ + "util" + ], + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/utils-merge.git" + }, + "bugs": { + "url": "http://github.com/jaredhanson/utils-merge/issues" + }, + "author": { + "name": "Jared Hanson", + "email": "jaredhanson@gmail.com", + "url": "http://www.jaredhanson.net/" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://www.opensource.org/licenses/MIT" + } + ], + "main": "./index", + "dependencies": {}, + "devDependencies": { + "mocha": "1.x.x", + "chai": "1.x.x" + }, + "scripts": { + "test": "mocha --reporter spec --require test/bootstrap/node test/*.test.js" + }, + "engines": { + "node": ">= 0.4.0" + }, + "_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#readme" +} diff --git a/5-1/service/node_modules/express/node_modules/vary/HISTORY.md b/5-1/service/node_modules/express/node_modules/vary/HISTORY.md new file mode 100644 index 0000000..cddbcd4 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/vary/HISTORY.md @@ -0,0 +1,23 @@ +1.0.1 / 2015-07-08 +================== + + * Fix setting empty header from empty `field` + * perf: enable strict mode + * perf: remove argument reassignments + +1.0.0 / 2014-08-10 +================== + + * Accept valid `Vary` header string as `field` + * Add `vary.append` for low-level string manipulation + * Move to `jshttp` orgainzation + +0.1.0 / 2014-06-05 +================== + + * Support array of fields to set + +0.0.0 / 2014-06-04 +================== + + * Initial release diff --git a/5-1/service/node_modules/express/node_modules/vary/LICENSE b/5-1/service/node_modules/express/node_modules/vary/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/vary/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-1/service/node_modules/express/node_modules/vary/README.md b/5-1/service/node_modules/express/node_modules/vary/README.md new file mode 100644 index 0000000..5966542 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/vary/README.md @@ -0,0 +1,91 @@ +# vary + +[![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] + +Manipulate the HTTP Vary header + +## Installation + +```sh +$ npm install vary +``` + +## API + +```js +var vary = require('vary') +``` + +### vary(res, field) + +Adds the given header `field` to the `Vary` response header of `res`. +This can be a string of a single field, a string of a valid `Vary` +header, or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. + +```js +// Append "Origin" to the Vary header of the response +vary(res, 'Origin') +``` + +### vary.append(header, field) + +Adds the given header `field` to the `Vary` response header string `header`. +This can be a string of a single field, a string of a valid `Vary` header, +or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. The new header string is returned. + +```js +// Get header string appending "Origin" to "Accept, User-Agent" +vary.append('Accept, User-Agent', 'Origin') +``` + +## Examples + +### Updating the Vary header when content is based on it + +```js +var http = require('http') +var vary = require('vary') + +http.createServer(function onRequest(req, res) { + // about to user-agent sniff + vary(res, 'User-Agent') + + var ua = req.headers['user-agent'] || '' + var isMobile = /mobi|android|touch|mini/i.test(ua) + + // serve site, depending on isMobile + res.setHeader('Content-Type', 'text/html') + res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') +}) +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/vary.svg +[npm-url]: https://npmjs.org/package/vary +[node-version-image]: https://img.shields.io/node/v/vary.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg +[travis-url]: https://travis-ci.org/jshttp/vary +[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/vary +[downloads-image]: https://img.shields.io/npm/dm/vary.svg +[downloads-url]: https://npmjs.org/package/vary diff --git a/5-1/service/node_modules/express/node_modules/vary/index.js b/5-1/service/node_modules/express/node_modules/vary/index.js new file mode 100644 index 0000000..e818dbb --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/vary/index.js @@ -0,0 +1,117 @@ +/*! + * vary + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + */ + +module.exports = vary; +module.exports.append = append; + +/** + * Variables. + */ + +var separators = /[\(\)<>@,;:\\"\/\[\]\?=\{\}\u0020\u0009]/; + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @api public + */ + +function append(header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required'); + } + + if (!field) { + throw new TypeError('field argument is required'); + } + + // get fields array + var fields = !Array.isArray(field) + ? parse(String(field)) + : field; + + // assert on invalid fields + for (var i = 0; i < fields.length; i++) { + if (separators.test(fields[i])) { + throw new TypeError('field argument contains an invalid header'); + } + } + + // existing, unspecified vary + if (header === '*') { + return header; + } + + // enumerate current values + var val = header; + var vals = parse(header.toLowerCase()); + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*'; + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase(); + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld); + val = val + ? val + ', ' + fields[i] + : fields[i]; + } + } + + return val; +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @api private + */ + +function parse(header) { + return header.trim().split(/ *, */); +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @api public + */ + +function vary(res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required'); + } + + // get existing header + var val = res.getHeader('Vary') || '' + var header = Array.isArray(val) + ? val.join(', ') + : String(val); + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val); + } +} diff --git a/5-1/service/node_modules/express/node_modules/vary/package.json b/5-1/service/node_modules/express/node_modules/vary/package.json new file mode 100644 index 0000000..8e1bee4 --- /dev/null +++ b/5-1/service/node_modules/express/node_modules/vary/package.json @@ -0,0 +1,72 @@ +{ + "name": "vary", + "description": "Manipulate the HTTP Vary header", + "version": "1.0.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "http", + "res", + "vary" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/vary.git" + }, + "devDependencies": { + "istanbul": "0.3.17", + "mocha": "2.2.5", + "supertest": "1.0.1" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "650282ff8e614731837040a23e10f51c20728392", + "bugs": { + "url": "https://github.com/jshttp/vary/issues" + }, + "homepage": "https://github.com/jshttp/vary", + "_id": "vary@1.0.1", + "_shasum": "99e4981566a286118dfb2b817357df7993376d10", + "_from": "vary@>=1.0.1 <1.1.0", + "_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": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "99e4981566a286118dfb2b817357df7993376d10", + "tarball": "http://registry.npmjs.org/vary/-/vary-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/vary/-/vary-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/node_modules/express/package.json b/5-1/service/node_modules/express/package.json new file mode 100644 index 0000000..66d0e95 --- /dev/null +++ b/5-1/service/node_modules/express/package.json @@ -0,0 +1,143 @@ +{ + "name": "express", + "description": "Fast, unopinionated, minimalist web framework", + "version": "4.13.4", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "Ciaran Jessup", + "email": "ciaranj@gmail.com" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Guillermo Rauch", + "email": "rauchg@gmail.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com" + }, + { + "name": "Roman Shtylman", + "email": "shtylman+expressjs@gmail.com" + }, + { + "name": "Young Jae Sim", + "email": "hanul@hanul.me" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/express.git" + }, + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "rest", + "restful", + "router", + "app", + "api" + ], + "dependencies": { + "accepts": "~1.2.12", + "array-flatten": "1.1.1", + "content-disposition": "0.5.1", + "content-type": "~1.0.1", + "cookie": "0.1.5", + "cookie-signature": "1.0.6", + "debug": "~2.2.0", + "depd": "~1.1.0", + "escape-html": "~1.0.3", + "etag": "~1.7.0", + "finalhandler": "0.4.1", + "fresh": "0.3.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.1", + "path-to-regexp": "0.1.7", + "proxy-addr": "~1.0.10", + "qs": "4.0.0", + "range-parser": "~1.0.3", + "send": "0.13.1", + "serve-static": "~1.10.2", + "type-is": "~1.6.6", + "utils-merge": "1.0.0", + "vary": "~1.0.1" + }, + "devDependencies": { + "after": "0.8.1", + "ejs": "2.3.4", + "istanbul": "0.4.2", + "marked": "0.3.5", + "mocha": "2.3.4", + "should": "7.1.1", + "supertest": "1.1.0", + "body-parser": "~1.14.2", + "connect-redis": "~2.4.1", + "cookie-parser": "~1.4.1", + "cookie-session": "~1.2.0", + "express-session": "~1.13.0", + "jade": "~1.11.0", + "method-override": "~2.3.5", + "morgan": "~1.6.1", + "multiparty": "~4.1.2", + "vhost": "~3.0.1" + }, + "engines": { + "node": ">= 0.10.0" + }, + "files": [ + "LICENSE", + "History.md", + "Readme.md", + "index.js", + "lib/" + ], + "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/" + }, + "gitHead": "193bed2649c55c1fd362e46cd4702c773f3e7434", + "bugs": { + "url": "https://github.com/expressjs/express/issues" + }, + "homepage": "https://github.com/expressjs/express", + "_id": "express@4.13.4", + "_shasum": "3c0b76f3c77590c8345739061ec0bd3ba067ec24", + "_from": "express@*", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "3c0b76f3c77590c8345739061ec0bd3ba067ec24", + "tarball": "http://registry.npmjs.org/express/-/express-4.13.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/express/-/express-4.13.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-1/service/package.json b/5-1/service/package.json new file mode 100644 index 0000000..121e445 --- /dev/null +++ b/5-1/service/package.json @@ -0,0 +1,15 @@ +{ + "name": "service", + "version": "1.0.0", + "description": "", + "main": "server.js", + "directories": { + "example": "example" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "node server.js" + }, + "author": "", + "license": "ISC" +} diff --git a/5-1/service/server.js b/5-1/service/server.js new file mode 100644 index 0000000..ea7257f --- /dev/null +++ b/5-1/service/server.js @@ -0,0 +1,11 @@ +var express = require('express'); +var app = express(); + +app.get('/', functin(req, res) { + res.json({'msg': 'some message'}) +}); + +var port = process.env.port || 300; +app.listen(port, function() { + console.log('server started'); +}); \ No newline at end of file diff --git a/5-2.txt b/5-2.txt new file mode 100644 index 0000000..b7a59f0 --- /dev/null +++ b/5-2.txt @@ -0,0 +1,99 @@ +//terminal +// vi server.js + +/* server.js +var express = require('express'); +var bodyParser = require('body-parser'); +var mongoose = require('mongoose'); +var User = require('./models/User'); +var app = express(); +app.use(bodyParser.json()); + +mongoUri = process.env.mongoUri +mongoose.connect(mongoUri); + +app.get('/users', function(req, res) { + User.find({}, function(err, users) { + res.json(users); + }); +}); + +app.post('/users', function(req,res) { + console.log('post /users'); + var user = new User(req.body); + user.save(function(err, user) { + res.json(user); + }); +}); + +var port = process.env.port || 3000; +app.listen(port, function() { + console.log('server started'); +}); +*/ + +//terminal +// cd models/ +// vi User.js + +/* models/User.js +var mongoose = require('mongoose'); + +var userSchema = mongoose.Schema({ + name: String +}); + +module.exports = mongoose.model('User', userSchema); +*/ + +//terminal +// cd .. +// vi docker-compose.yml + +/* docker-compose.yml +database: + image: mongo + +api: + build: . + volumes: + - .:/usr/src/app + ports: + - "3000:80" + environment: + port: "80" + mongoUri: "mongodb://database/app-dev" + links: + - database +*/ + +//terminal +// docker-compose up -d +// curl http://localhost:3000/users +// curl -H "Content-Type: application/json" -X POST -d '{"name": "john"}' http://localhost:3000/users +// curl http://localhost:3000/users +// curl -H "Content-Type: application/json" -X POST -d '{"name": "mary"}' http://localhost:3000/users +// curl http://localhost:3000/users +// docker ps +// docker exec -it service_api_1 /bin/bash +// cat /etc/hosts +// exit +// docker-compose stop +// docker-compose up -d +// curl http://localhost:3000/users +// docker ps +// docker inspect service_database_1 | less +// /Volumes +// vi docker-compose.yml +// + + + + + + + + + + + diff --git a/5-2/service/docker-compose.yml b/5-2/service/docker-compose.yml new file mode 100644 index 0000000..3ce826d --- /dev/null +++ b/5-2/service/docker-compose.yml @@ -0,0 +1,14 @@ +database: + image: mongo + +api: + build: . + volumes: + - .:/usr/src/app + ports: + - "3000:80" + environment: + port: "80" + mongoUri: "mongodb://database/app-dev" + links: + - database \ No newline at end of file diff --git a/5-2/service/models/User.js b/5-2/service/models/User.js new file mode 100644 index 0000000..7f2fb4e --- /dev/null +++ b/5-2/service/models/User.js @@ -0,0 +1,7 @@ +var mongoose = require('mongoose'); + +var userSchema = mongoose.Schema({ + name: String +}); + +module.exports = mongoose.model('User', userSchema); \ No newline at end of file diff --git a/5-2/service/node_modules/body-parser/HISTORY.md b/5-2/service/node_modules/body-parser/HISTORY.md new file mode 100644 index 0000000..c9d5168 --- /dev/null +++ b/5-2/service/node_modules/body-parser/HISTORY.md @@ -0,0 +1,425 @@ +1.14.2 / 2015-12-16 +=================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + * deps: qs@5.2.0 + * deps: raw-body@~2.1.5 + - deps: bytes@2.2.0 + - deps: iconv-lite@0.4.13 + * deps: type-is@~1.6.10 + - deps: mime-types@~2.1.9 + +1.14.1 / 2015-09-27 +=================== + + * Fix issue where invalid charset results in 400 when `verify` used + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + * deps: raw-body@~2.1.4 + - Fix masking critical errors from `iconv-lite` + - deps: iconv-lite@0.4.12 + * deps: type-is@~1.6.9 + - deps: mime-types@~2.1.7 + +1.14.0 / 2015-09-16 +=================== + + * Fix JSON strict parse error to match syntax errors + * Provide static `require` analysis in `urlencoded` parser + * deps: depd@~1.1.0 + - Support web browser loading + * deps: qs@5.1.0 + * deps: raw-body@~2.1.3 + - Fix sync callback when attaching data listener causes sync read + * deps: type-is@~1.6.8 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.6 + +1.13.3 / 2015-07-31 +=================== + + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +1.13.2 / 2015-07-05 +=================== + + * deps: iconv-lite@0.4.11 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix user-visible incompatibilities from 3.1.0 + - Fix various parsing edge cases + * deps: raw-body@~2.1.2 + - Fix error stack traces to skip `makeError` + - deps: iconv-lite@0.4.11 + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +1.13.1 / 2015-06-16 +=================== + + * deps: qs@2.4.2 + - Downgraded from 3.1.0 because of user-visible incompatibilities + +1.13.0 / 2015-06-14 +=================== + + * Add `statusCode` property on `Error`s, in addition to `status` + * Change `type` default to `application/json` for JSON parser + * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser + * Provide static `require` analysis + * Use the `http-errors` module to generate errors + * deps: bytes@2.1.0 + - Slight optimizations + * deps: iconv-lite@0.4.10 + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + - Leading BOM is now removed when decoding + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: qs@3.1.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + - Parsed object now has `null` prototype + * deps: raw-body@~2.1.1 + - Use `unpipe` module for unpiping requests + - deps: iconv-lite@0.4.10 + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: remove argument reassignment + * perf: remove delete call + +1.12.4 / 2015-05-10 +=================== + + * deps: debug@~2.2.0 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: on-finished@~2.2.1 + * deps: raw-body@~2.0.1 + - Fix a false-positive when unpiping in Node.js 0.8 + - deps: bytes@2.0.1 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +1.12.3 / 2015-04-15 +=================== + + * Slight efficiency improvement when not debugging + * deps: depd@~1.0.1 + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + * deps: raw-body@1.3.4 + - Fix hanging callback if request aborts during read + - deps: iconv-lite@0.4.8 + +1.12.2 / 2015-03-16 +=================== + + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + +1.12.1 / 2015-03-15 +=================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +1.12.0 / 2015-02-13 +=================== + + * add `debug` messages + * accept a function for the `type` option + * use `content-type` to parse `Content-Type` headers + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + * deps: raw-body@1.3.3 + - deps: iconv-lite@0.4.7 + * 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 + +1.11.0 / 2015-01-30 +=================== + + * make internal `extended: true` depth limit infinity + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +1.10.2 / 2015-01-20 +=================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + * deps: raw-body@1.3.2 + - deps: iconv-lite@0.4.6 + +1.10.1 / 2015-01-01 +=================== + + * deps: on-finished@~2.2.0 + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +1.10.0 / 2014-12-02 +=================== + + * make internal `extended: true` array limit dynamic + +1.9.3 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + * deps: raw-body@1.3.1 + - deps: iconv-lite@0.4.5 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +1.9.2 / 2014-10-27 +================== + + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +1.9.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +1.9.0 / 2014-09-24 +================== + + * include the charset in "unsupported charset" error message + * include the encoding in "unsupported content encoding" error message + * deps: depd@~1.0.0 + +1.8.4 / 2014-09-23 +================== + + * fix content encoding to be case-insensitive + +1.8.3 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +1.8.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + +1.8.1 / 2014-09-07 +================== + + * deps: media-typer@0.3.0 + * deps: type-is@~1.5.1 + +1.8.0 / 2014-09-05 +================== + + * make empty-body-handling consistent between chunked requests + - empty `json` produces `{}` + - empty `raw` produces `new Buffer(0)` + - empty `text` produces `''` + - empty `urlencoded` produces `{}` + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: type-is@~1.5.0 + - fix `hasbody` to be true for `content-length: 0` + +1.7.0 / 2014-09-01 +================== + + * add `parameterLimit` option to `urlencoded` parser + * change `urlencoded` extended array limit to 100 + * respond with 413 when over `parameterLimit` in `urlencoded` + +1.6.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +1.6.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/5-2/service/node_modules/body-parser/LICENSE b/5-2/service/node_modules/body-parser/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/5-2/service/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +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: + +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/5-2/service/node_modules/body-parser/README.md b/5-2/service/node_modules/body-parser/README.md new file mode 100644 index 0000000..c819bb1 --- /dev/null +++ b/5-2/service/node_modules/body-parser/README.md @@ -0,0 +1,403 @@ +# body-parser + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Node.js body parsing middleware. + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.org/package/busboy#readme) and + [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.org/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.org/package/formidable#readme) + * [multer](https://www.npmjs.org/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + +```js +var bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body, or an +empty object (`{}`) if there was no body to parse (or an error was returned). + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json(options) + +Returns middleware that only parses `json`. This parser accepts any Unicode +encoding of the body and supports automatic inflation of `gzip` and `deflate` +encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an option `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `json`), a mime type (like +`application/json`), or a mime type with a wildcard (like `*/*` or `*/json`). +If a function, the `type` option is called as `fn(req)` and the request is +parsed if it returns a truthy value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw(options) + +Returns middleware that parses all bodies as a `Buffer`. This parser +supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an option `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text(options) + +Returns middleware that parses all bodies as a string. This parser supports +automatic inflation of `gzip` and `deflate` encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an option `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `txt`), a mime type (like +`text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`). +If a function, the `type` option is called as `fn(req)` and the request is +parsed if it returns a truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded(options) + +Returns middleware that only parses `urlencoded` bodies. This parser accepts +only UTF-8 encoding of the body and supports automatic inflation of `gzip` +and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an option `options` object that may contain +any of the following keys: + +##### extended + +The `extended` option allows to choose between parsing the URL-encoded data +with the `querystring` library (when `false`) or the `qs` library (when +`true`). The "extended" syntax allows for rich objects and arrays to be +encoded into the URL-encoded format, allowing for a JSON-like experience +with URL-encoded. For more information, please +[see the qs library](https://www.npmjs.org/package/qs#readme). + +Defaults to `true`, but using the default has been deprecated. Please +research into the difference between `qs` and `querystring` and choose the +appropriate setting. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +## Errors + +The middlewares provided by this module create errors depending on the error +condition during parsing. The errors will typically have a `status` property +that contains the suggested HTTP response code. + +The following are the common errors emitted, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`. + +## Examples + +### express/connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: false })) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(JSON.stringify(req.body, null, 2)) +}) +``` + +### express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommend way to use body-parser with +express. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// create application/json parser +var jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +var urlencodedParser = bodyParser.urlencoded({ extended: false }) + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + if (!req.body) return res.sendStatus(400) + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + if (!req.body) return res.sendStatus(400) + // create user in req.body +}) +``` + +### change content-type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/body-parser.svg +[npm-url]: https://npmjs.org/package/body-parser +[travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg +[travis-url]: https://travis-ci.org/expressjs/body-parser +[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg +[downloads-url]: https://npmjs.org/package/body-parser +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/5-2/service/node_modules/body-parser/index.js b/5-2/service/node_modules/body-parser/index.js new file mode 100644 index 0000000..f430387 --- /dev/null +++ b/5-2/service/node_modules/body-parser/index.js @@ -0,0 +1,157 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('body-parser') + +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + +/** + * Module exports. + * @type {Parsers} + */ + +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') + +/** + * JSON parser. + * @public + */ + +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: createParserGetter('json') +}) + +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: createParserGetter('raw') +}) + +/** + * Text parser. + * @public + */ + +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: createParserGetter('text') +}) + +/** + * URL-encoded parser. + * @public + */ + +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ + +function bodyParser(options){ + var opts = {} + + // exclude type option + if (options) { + for (var prop in options) { + if ('type' !== prop) { + opts[prop] = options[prop] + } + } + } + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser(req, res, next) { + _json(req, res, function(err){ + if (err) return next(err); + _urlencoded(req, res, next); + }); + } +} + +/** + * Create a getter for loading a parser. + * @private + */ + +function createParserGetter(name) { + return function get() { + return loadParser(name) + } +} + +/** + * Load a parser module. + * @private + */ + +function loadParser(parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser + } + + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = require('./lib/types/json') + break + case 'raw': + parser = require('./lib/types/raw') + break + case 'text': + parser = require('./lib/types/text') + break + case 'urlencoded': + parser = require('./lib/types/urlencoded') + break + } + + // store to prevent invoking require() + return parsers[parserName] = parser +} diff --git a/5-2/service/node_modules/body-parser/lib/read.js b/5-2/service/node_modules/body-parser/lib/read.js new file mode 100644 index 0000000..95af8a7 --- /dev/null +++ b/5-2/service/node_modules/body-parser/lib/read.js @@ -0,0 +1,188 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var zlib = require('zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} [options] + * @api private + */ + +function read(req, res, next, parse, debug, options) { + var length + var opts = options || {} + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding || 'utf-8' + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase() + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (err, body) { + if (err) { + // default to 400 + setErrorStatus(err, 400) + + // echo back charset + if (err.type === 'encoding.unsupported') { + err = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase() + }) + } + + // read off entire request + stream.resume() + onFinished(req, function onfinished() { + next(err) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + // default to 403 + setErrorStatus(err, 403) + next(err) + return + } + } + + // parse + var str + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + err.body = str === undefined + ? body + : str + + // default to 400 + setErrorStatus(err, 400) + + next(err) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream(req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported') + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding + }) + } + + return stream +} + +/** + * Set a status on an error object, if ones does not exist + * @private + */ + +function setErrorStatus(error, status) { + if (!error.status && !error.statusCode) { + error.status = status + error.statusCode = status + } +} diff --git a/5-2/service/node_modules/body-parser/lib/types/json.js b/5-2/service/node_modules/body-parser/lib/types/json.js new file mode 100644 index 0000000..1a70e37 --- /dev/null +++ b/5-2/service/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,170 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:json') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ + +var firstcharRegExp = /^[\x20\x09\x0a\x0d]*(.)/ + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function json(options) { + var opts = options || {} + + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse(body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw new SyntaxError('Unexpected token ' + first) + } + } + + debug('parse json') + return JSON.parse(body, reviver) + } + + return function jsonParser(req, res, next) { + if (req._body) { + return debug('body already parsed'), next() + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + return debug('skip empty body'), next() + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + return debug('skip parsing'), next() + } + + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.substr(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @api public + */ + + +function firstchar(str) { + var match = firstcharRegExp.exec(str) + return match ? match[1] : '' +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset(req) { + try { + return contentType.parse(req).parameters.charset.toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker(type) { + return function checkType(req) { + return Boolean(typeis(req, type)) + } +} diff --git a/5-2/service/node_modules/body-parser/lib/types/raw.js b/5-2/service/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 0000000..519146c --- /dev/null +++ b/5-2/service/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,95 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var debug = require('debug')('body-parser:raw') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw(options) { + var opts = options || {}; + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse(buf) { + return buf + } + + return function rawParser(req, res, next) { + if (req._body) { + return debug('body already parsed'), next() + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + return debug('skip empty body'), next() + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + return debug('skip parsing'), next() + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker(type) { + return function checkType(req) { + return Boolean(typeis(req, type)) + } +} diff --git a/5-2/service/node_modules/body-parser/lib/types/text.js b/5-2/service/node_modules/body-parser/lib/types/text.js new file mode 100644 index 0000000..caf7968 --- /dev/null +++ b/5-2/service/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,115 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var debug = require('debug')('body-parser:text') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text(options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse(buf) { + return buf + } + + return function textParser(req, res, next) { + if (req._body) { + return debug('body already parsed'), next() + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + return debug('skip empty body'), next() + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + return debug('skip parsing'), next() + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset(req) { + try { + return contentType.parse(req).parameters.charset.toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker(type) { + return function checkType(req) { + return Boolean(typeis(req, type)) + } +} diff --git a/5-2/service/node_modules/body-parser/lib/types/urlencoded.js b/5-2/service/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 0000000..76f5aa4 --- /dev/null +++ b/5-2/service/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,273 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var deprecate = require('depd')('body-parser') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function urlencoded(options) { + var opts = options || {} + + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse(body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser(req, res, next) { + if (req._body) { + return debug('body already parsed'), next() + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + return debug('skip empty body'), next() + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + return debug('skip parsing'), next() + } + + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset + })) + return + } + + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the extended query parser. + * + * @param {object} options + */ + +function extendedparser(options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse(body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters') + } + + var arrayLimit = Math.max(100, paramCount) + + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset(req) { + try { + return contentType.parse(req).parameters.charset.toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ + +function parameterCount(body, limit) { + var count = 0 + var index = 0 + + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } + } + + return count +} + +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ + +function parser(name) { + var mod = parsers[name] + + if (mod !== undefined) { + return mod.parse + } + + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = require('qs') + break + case 'querystring': + mod = require('querystring') + break + } + + // store to prevent invoking require() + parsers[name] = mod + + return mod.parse +} + +/** + * Get the simple query parser. + * + * @param {object} options + */ + +function simpleparser(options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse(body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters') + } + + debug('parse urlencoding') + return parse(body, undefined, undefined, {maxKeys: parameterLimit}) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker(type) { + return function checkType(req) { + return Boolean(typeis(req, type)) + } +} diff --git a/5-2/service/node_modules/body-parser/node_modules/bytes/History.md b/5-2/service/node_modules/body-parser/node_modules/bytes/History.md new file mode 100644 index 0000000..5bd5136 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/bytes/History.md @@ -0,0 +1,57 @@ +2.2.0 / 2015-11-13 +================== + + * add option "decimalPlaces" + * add option "fixedDecimals" + +2.1.0 / 2015-05-21 +================== + + * add `.format` export + * add `.parse` export + +2.0.2 / 2015-05-20 +================== + + * remove map recreation + * remove unnecessary object construction + +2.0.1 / 2015-05-07 +================== + + * fix browserify require + * remove node.extend dependency + +2.0.0 / 2015-04-12 +================== + + * add option "case" + * add option "thousandsSeparator" + * return "null" on invalid parse input + * support proper round-trip: bytes(bytes(num)) === num + * units no longer case sensitive when parsing + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/5-2/service/node_modules/body-parser/node_modules/bytes/LICENSE b/5-2/service/node_modules/body-parser/node_modules/bytes/LICENSE new file mode 100644 index 0000000..63e95a9 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/bytes/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015 Jed Watson + +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/5-2/service/node_modules/body-parser/node_modules/bytes/Readme.md b/5-2/service/node_modules/body-parser/node_modules/bytes/Readme.md new file mode 100644 index 0000000..fb4b3ea --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/bytes/Readme.md @@ -0,0 +1,99 @@ +# Bytes utility + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] + +Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. + +## Usage + +```js +var bytes = require('bytes'); +``` + +#### bytes.format(number value, [options]): string|null + +Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is + rounded. + +**Arguments** + +| Name | Type | Description | +|---------|--------|--------------------| +| value | `number` | Value in bytes | +| options | `Object` | Conversion options | + +**Options** + +| Property | Type | Description | +|-------------------|--------|-----------------------------------------------------------------------------------------| +| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | +| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | +| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `.`... Default value to `' '`. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `string`|`null` | Return null upon error. String value otherwise. | + +**Example** + +```js +bytes(1024); +// output: '1kB' + +bytes(1000); +// output: '1000B' + +bytes(1000, {thousandsSeparator: ' '}); +// output: '1 000B' + +bytes(1024 * 1.7, {decimalPlaces: 0}); +// output: '2kB' +``` + +#### bytes.parse(string value): number|null + +Parse the string value into an integer in bytes. If no unit is given, it is assumed the value is in bytes. + +**Arguments** + +| Name | Type | Description | +|---------------|--------|--------------------| +| value | `string` | String to parse. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | + +**Example** + +```js +bytes('1kB'); +// output: 1024 + +bytes('1024'); +// output: 1024 +``` + +## Installation + +```bash +npm install bytes --save +component install visionmedia/bytes.js +``` + +## License + +[![npm](https://img.shields.io/npm/l/express.svg)](https://github.com/visionmedia/bytes.js/blob/master/LICENSE) + +[downloads-image]: https://img.shields.io/npm/dm/bytes.svg +[downloads-url]: https://npmjs.org/package/bytes +[npm-image]: https://img.shields.io/npm/v/bytes.svg +[npm-url]: https://npmjs.org/package/bytes +[travis-image]: https://img.shields.io/travis/visionmedia/bytes.js/master.svg +[travis-url]: https://travis-ci.org/visionmedia/bytes.js diff --git a/5-2/service/node_modules/body-parser/node_modules/bytes/index.js b/5-2/service/node_modules/body-parser/node_modules/bytes/index.js new file mode 100644 index 0000000..02d5bee --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/bytes/index.js @@ -0,0 +1,141 @@ +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: ((1 << 30) * 1024) +}; + +/** + *Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @public + */ + +function format(value, options) { + if (typeof value !== 'number') { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = 'B'; + + if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'kB'; + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(/(?:\.0*|(\.[^0]+)0+)$/, '$1'); + } + + if (thousandsSeparator) { + str = str.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator); + } + + return str + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = val.match(/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + return map[unit] * floatValue; +} diff --git a/5-2/service/node_modules/body-parser/node_modules/bytes/package.json b/5-2/service/node_modules/body-parser/node_modules/bytes/package.json new file mode 100644 index 0000000..891f714 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/bytes/package.json @@ -0,0 +1,80 @@ +{ + "name": "bytes", + "description": "Utility to parse a string bytes to bytes and vice-versa", + "version": "2.2.0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "contributors": [ + { + "name": "Jed Watson", + "email": "jed.watson@me.com" + }, + { + "name": "Théo FIDRY", + "email": "theo.fidry@gmail.com" + } + ], + "license": "MIT", + "keywords": [ + "byte", + "bytes", + "utility", + "parse", + "parser", + "convert", + "converter" + ], + "repository": { + "type": "git", + "url": "https://github.com/visionmedia/bytes.js" + }, + "component": { + "scripts": { + "bytes/index.js": "index.js" + } + }, + "devDependencies": { + "mocha": "1.21.5" + }, + "files": [ + "History.md", + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "test": "mocha --check-leaks --reporter spec" + }, + "gitHead": "509a01a5472b9163ae5a7db41e2d6bd986fdf595", + "bugs": { + "url": "https://github.com/visionmedia/bytes.js/issues" + }, + "homepage": "https://github.com/visionmedia/bytes.js", + "_id": "bytes@2.2.0", + "_shasum": "fd35464a403f6f9117c2de3609ecff9cae000588", + "_from": "bytes@2.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "fd35464a403f6f9117c2de3609ecff9cae000588", + "tarball": "http://registry.npmjs.org/bytes/-/bytes-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/bytes/-/bytes-2.2.0.tgz" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/content-type/HISTORY.md b/5-2/service/node_modules/body-parser/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..8a623a2 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/content-type/HISTORY.md @@ -0,0 +1,9 @@ +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/5-2/service/node_modules/body-parser/node_modules/content-type/LICENSE b/5-2/service/node_modules/body-parser/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/5-2/service/node_modules/body-parser/node_modules/content-type/README.md b/5-2/service/node_modules/body-parser/node_modules/content-type/README.md new file mode 100644 index 0000000..3ed6741 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/content-type/README.md @@ -0,0 +1,92 @@ +# content-type + +[![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] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a content 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 media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({type: 'image/svg+xml'}) +``` + +Format an object into a content type string. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-type.svg +[npm-url]: https://npmjs.org/package/content-type +[node-version-image]: https://img.shields.io/node/v/content-type.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg +[travis-url]: https://travis-ci.org/jshttp/content-type +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-type +[downloads-image]: https://img.shields.io/npm/dm/content-type.svg +[downloads-url]: https://npmjs.org/package/content-type diff --git a/5-2/service/node_modules/body-parser/node_modules/content-type/index.js b/5-2/service/node_modules/body-parser/node_modules/content-type/index.js new file mode 100644 index 0000000..6a2ea9f --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/content-type/index.js @@ -0,0 +1,214 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) */g +var textRegExp = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var qescRegExp = /\\([\u000b\u0020-\u00ff])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var quoteRegExp = /([\\"])/g + +/** + * RegExp to match type in RFC 6838 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+\/[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !typeRegExp.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // 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} + * @public + */ + +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string === 'object') { + // support req/res-like objects as argument + string = getcontenttype(string) + + if (typeof string !== 'string') { + throw new TypeError('content-type header is missing from object'); + } + } + + 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).trim() + : string.trim() + + if (!typeRegExp.test(type)) { + throw new TypeError('invalid media type') + } + + var key + var match + var obj = new ContentType(type.toLowerCase()) + 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') + } + + obj.parameters[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @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} + * @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') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType(type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/5-2/service/node_modules/body-parser/node_modules/content-type/package.json b/5-2/service/node_modules/body-parser/node_modules/content-type/package.json new file mode 100644 index 0000000..e23403c --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/content-type/package.json @@ -0,0 +1,65 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-type.git" + }, + "devDependencies": { + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail 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": "3aa58f9c5a358a3634b8601602177888b4a477d8", + "bugs": { + "url": "https://github.com/jshttp/content-type/issues" + }, + "homepage": "https://github.com/jshttp/content-type", + "_id": "content-type@1.0.1", + "_shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "_from": "content-type@>=1.0.1 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "tarball": "http://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/debug/.jshintrc b/5-2/service/node_modules/body-parser/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/5-2/service/node_modules/body-parser/node_modules/debug/.npmignore b/5-2/service/node_modules/body-parser/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/5-2/service/node_modules/body-parser/node_modules/debug/History.md b/5-2/service/node_modules/body-parser/node_modules/debug/History.md new file mode 100644 index 0000000..854c971 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/History.md @@ -0,0 +1,195 @@ + +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 +================== + + * 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/5-2/service/node_modules/body-parser/node_modules/debug/Makefile b/5-2/service/node_modules/body-parser/node_modules/debug/Makefile new file mode 100644 index 0000000..5cf4a59 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/Makefile @@ -0,0 +1,36 @@ + +# 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 dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +distclean: clean + @rm -rf node_modules + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean distclean diff --git a/5-2/service/node_modules/body-parser/node_modules/debug/Readme.md b/5-2/service/node_modules/body-parser/node_modules/debug/Readme.md new file mode 100644 index 0000000..b4f45e3 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/Readme.md @@ -0,0 +1,188 @@ +# 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'); +``` + +### 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 + - 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/5-2/service/node_modules/body-parser/node_modules/debug/bower.json b/5-2/service/node_modules/body-parser/node_modules/debug/bower.json new file mode 100644 index 0000000..6af573f --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/bower.json @@ -0,0 +1,28 @@ +{ + "name": "visionmedia-debug", + "main": "dist/debug.js", + "version": "2.2.0", + "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/5-2/service/node_modules/body-parser/node_modules/debug/browser.js b/5-2/service/node_modules/body-parser/node_modules/debug/browser.js new file mode 100644 index 0000000..7c76452 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/browser.js @@ -0,0 +1,168 @@ + +/** + * 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; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : 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) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.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/5-2/service/node_modules/body-parser/node_modules/debug/component.json b/5-2/service/node_modules/body-parser/node_modules/debug/component.json new file mode 100644 index 0000000..ca10637 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.2.0", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/5-2/service/node_modules/body-parser/node_modules/debug/debug.js b/5-2/service/node_modules/body-parser/node_modules/debug/debug.js new file mode 100644 index 0000000..7571a86 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * 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/5-2/service/node_modules/body-parser/node_modules/debug/node.js b/5-2/service/node_modules/body-parser/node_modules/debug/node.js new file mode 100644 index 0000000..1d392a8 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/node.js @@ -0,0 +1,209 @@ + +/** + * 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/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/.npmignore b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/History.md b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/LICENSE b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/README.md b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/index.js b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/package.json b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/debug/package.json b/5-2/service/node_modules/body-parser/node_modules/debug/package.json new file mode 100644 index 0000000..24bb9c9 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/debug/package.json @@ -0,0 +1,73 @@ +{ + "name": "debug", + "version": "2.2.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "license": "MIT", + "dependencies": { + "ms": "0.7.1" + }, + "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": "b38458422b5aa8aa6d286b10dfe427e8a67e2b35", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@2.2.0", + "scripts": {}, + "_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "_from": "debug@>=2.2.0 <2.3.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "tarball": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/depd/History.md b/5-2/service/node_modules/body-parser/node_modules/depd/History.md new file mode 100644 index 0000000..ace1171 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/depd/History.md @@ -0,0 +1,84 @@ +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/5-2/service/node_modules/body-parser/node_modules/depd/LICENSE b/5-2/service/node_modules/body-parser/node_modules/depd/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-2/service/node_modules/body-parser/node_modules/depd/Readme.md b/5-2/service/node_modules/body-parser/node_modules/depd/Readme.md new file mode 100644 index 0000000..09bb979 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/depd/Readme.md @@ -0,0 +1,281 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction() { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: http://nodejs.org/download/ +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/5-2/service/node_modules/body-parser/node_modules/depd/index.js b/5-2/service/node_modules/body-parser/node_modules/depd/index.js new file mode 100644 index 0000000..fddcae8 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/depd/index.js @@ -0,0 +1,521 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace(str, namespace) { + var val = str.split(/[ ,]+/) + + namespace = String(namespace).toLowerCase() + + for (var i = 0 ; i < val.length; i++) { + if (!(str = val[i])) continue; + + // namespace contained + if (str === '*' || str.toLowerCase() === namespace) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor(obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter() { return value } + + if (descriptor.writable) { + descriptor.set = function setter(val) { return value = val } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString(arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString(stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate(message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log(message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + callSite = callSiteLocation(stack[1]) + callSite.name = site.name + file = callSite[0] + } else { + // get call site + i = 2 + site = callSiteLocation(stack[i]) + callSite = site + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? site.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + if (!message) { + message = callSite === site || !callSite.name + ? defaultMessage(site) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, message, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var msg = format.call(this, message, caller, stack.slice(i)) + process.stderr.write(msg + '\n', 'utf8') + + return +} + +/** + * Get call site location as array. + */ + +function callSiteLocation(callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage(site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain(msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor(msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' // bold cyan + + ' \x1b[33;1mdeprecated\x1b[22;39m' // bold yellow + + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation(callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace(obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter() { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter() { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError(namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return stackString = createStackString.call(this, stack) + }, + set: function setter(val) { + stackString = val + } + }) + + return error +} diff --git a/5-2/service/node_modules/body-parser/node_modules/depd/lib/browser/index.js b/5-2/service/node_modules/body-parser/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..f464e05 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/depd/lib/browser/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate(message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + return +} diff --git a/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/buffer-concat.js b/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/buffer-concat.js new file mode 100644 index 0000000..4b73381 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/buffer-concat.js @@ -0,0 +1,35 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = bufferConcat + +/** + * Concatenate an array of Buffers. + */ + +function bufferConcat(bufs) { + var length = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + length += bufs[i].length + } + + var buf = new Buffer(length) + var pos = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + bufs[i].copy(buf, pos) + pos += bufs[i].length + } + + return buf +} diff --git a/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/callsite-tostring.js b/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 0000000..9ecef34 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation(callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString(callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName(obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/event-listener-count.js b/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 0000000..a05fceb --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount(emitter, type) { + return emitter.listeners(type).length +} diff --git a/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/index.js b/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/index.js new file mode 100644 index 0000000..aa3c1de --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/depd/lib/compat/index.js @@ -0,0 +1,84 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('buffer') +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'bufferConcat', function bufferConcat() { + return Buffer.concat || require('./buffer-concat') +}) + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace(obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount() { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty(obj, prop, getter) { + function get() { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString(obj) { + return obj.toString() +} diff --git a/5-2/service/node_modules/body-parser/node_modules/depd/package.json b/5-2/service/node_modules/body-parser/node_modules/depd/package.json new file mode 100644 index 0000000..9da460a --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/depd/package.json @@ -0,0 +1,67 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "1.1.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/dougwilson/nodejs-depd.git" + }, + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail test/", + "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": "78c659de20283e3a6bee92bda455e6daff01686a", + "bugs": { + "url": "https://github.com/dougwilson/nodejs-depd/issues" + }, + "homepage": "https://github.com/dougwilson/nodejs-depd", + "_id": "depd@1.1.0", + "_shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "_from": "depd@>=1.1.0 <1.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "tarball": "http://registry.npmjs.org/depd/-/depd-1.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/depd/-/depd-1.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/HISTORY.md b/5-2/service/node_modules/body-parser/node_modules/http-errors/HISTORY.md new file mode 100644 index 0000000..4c7087d --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/HISTORY.md @@ -0,0 +1,76 @@ +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/LICENSE b/5-2/service/node_modules/body-parser/node_modules/http-errors/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/README.md b/5-2/service/node_modules/body-parser/node_modules/http-errors/README.md new file mode 100644 index 0000000..520271e --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/README.md @@ -0,0 +1,63 @@ +# http-errors + +[![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] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Example + +```js +var createError = require('http-errors'); + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')); + next(); +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +### Error Properties + +- `message` +- `status` and `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + +```js +var err = createError(404, 'This video does not exist!'); +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### new createError\[code || name\](\[msg]\)) + +```js +var err = new createError.NotFound(); +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/http-errors.svg?style=flat +[npm-url]: https://npmjs.org/package/http-errors +[node-version-image]: https://img.shields.io/node/v/http-errors.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/http-errors.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/http-errors +[coveralls-image]: https://img.shields.io/coveralls/jshttp/http-errors.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors +[downloads-image]: https://img.shields.io/npm/dm/http-errors.svg?style=flat +[downloads-url]: https://npmjs.org/package/http-errors diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/index.js b/5-2/service/node_modules/body-parser/node_modules/http-errors/index.js new file mode 100644 index 0000000..d84b114 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/index.js @@ -0,0 +1,120 @@ + +var statuses = require('statuses'); +var inherits = require('inherits'); + +function toIdentifier(str) { + return str.split(' ').map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }).join('').replace(/[^ _0-9a-z]/gi, '') +} + +exports = module.exports = function httpError() { + // so much arity going on ~_~ + var err; + var msg; + var status = 500; + var props = {}; + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (arg instanceof Error) { + err = arg; + status = err.status || err.statusCode || status; + continue; + } + switch (typeof arg) { + case 'string': + msg = arg; + break; + case 'number': + status = arg; + break; + case 'object': + props = arg; + break; + } + } + + if (typeof status !== 'number' || !statuses[status]) { + status = 500 + } + + // constructor + var HttpError = exports[status] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, httpError) + } + + if (!HttpError || !(err instanceof HttpError)) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err; +}; + +// create generic error objects +var codes = statuses.codes.filter(function (num) { + return num >= 400; +}); + +codes.forEach(function (code) { + var name = toIdentifier(statuses[code]) + var className = name.match(/Error$/) ? name : name + 'Error' + + if (code >= 500) { + var ServerError = function ServerError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ServerError) + self.__proto__ = ServerError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ServerError, Error); + ServerError.prototype.status = + ServerError.prototype.statusCode = code; + ServerError.prototype.expose = false; + exports[code] = + exports[name] = ServerError + return; + } + + var ClientError = function ClientError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ClientError) + self.__proto__ = ClientError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ClientError, Error); + ClientError.prototype.status = + ClientError.prototype.statusCode = code; + ClientError.prototype.expose = true; + exports[code] = + exports[name] = ClientError + return; +}); + +// backwards-compatibility +exports["I'mateapot"] = exports.ImATeapot diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/LICENSE b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +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/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/README.md b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +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/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits.js b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits_browser.js b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +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/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/package.json b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/package.json new file mode 100644 index 0000000..93d5078 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/package.json @@ -0,0 +1,50 @@ +{ + "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.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "_id": "inherits@2.0.1", + "dist": { + "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/inherits#readme" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/test.js b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +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/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/LICENSE b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/README.md b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/README.md new file mode 100644 index 0000000..f6ae24c --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/README.md @@ -0,0 +1,114 @@ +# Statuses + +[![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] + +HTTP status utility for node. + +## API + +```js +var status = require('statuses'); +``` + +### var code = status(Integer || String) + +If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown. + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status('forbidden') // => 403 +status('Forbidden') // => 403 +status(306) // throws, as it's not supported by node.js +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### var msg = status[code] + +Map of `code` to `status message`. `undefined` for invalid `code`s. + +```js +status[404] // => 'Not Found' +``` + +### var code = status[msg] + +Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s. + +```js +status['not found'] // => 404 +status['Not Found'] // => 404 +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +### statuses/codes.json + +```js +var codes = require('statuses/codes.json'); +``` + +This is a JSON file of the status codes +taken from `require('http').STATUS_CODES`. +This is saved so that codes are consistent even in older node.js versions. +For example, `308` will be added in v0.12. + +## Adding Status Codes + +The status codes are primarily sourced from http://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv. +Additionally, custom codes are added from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes. +These are added manually in the `lib/*.json` files. +If you would like to add a status code, add it to the appropriate JSON file. + +To rebuild `codes.json`, run the following: + +```bash +# update src/iana.json +npm run update +# build codes.json +npm run build +``` + +[npm-image]: https://img.shields.io/npm/v/statuses.svg?style=flat +[npm-url]: https://npmjs.org/package/statuses +[node-version-image]: http://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/statuses.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/statuses +[coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[downloads-image]: http://img.shields.io/npm/dm/statuses.svg?style=flat +[downloads-url]: https://npmjs.org/package/statuses diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/codes.json b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/codes.json new file mode 100644 index 0000000..4c45a88 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/codes.json @@ -0,0 +1,64 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "(Unused)", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} \ No newline at end of file diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/index.js b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/index.js new file mode 100644 index 0000000..b06182d --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/index.js @@ -0,0 +1,60 @@ + +var codes = require('./codes.json'); + +module.exports = status; + +// [Integer...] +status.codes = Object.keys(codes).map(function (code) { + code = ~~code; + var msg = codes[code]; + status[code] = msg; + status[msg] = status[msg.toLowerCase()] = code; + return code; +}); + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true, +}; + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true, +}; + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true, +}; + +function status(code) { + if (typeof code === 'number') { + if (!status[code]) throw new Error('invalid status code: ' + code); + return code; + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string'); + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n); + return n; + } + + n = status[code.toLowerCase()]; + if (!n) throw new Error('invalid status message: "' + code + '"'); + return n; +} diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/package.json b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/package.json new file mode 100644 index 0000000..748e6ca --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/package.json @@ -0,0 +1,84 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "1.2.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/statuses.git" + }, + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "0.0.6", + "istanbul": "0", + "mocha": "1", + "stream-to-array": "2" + }, + "scripts": { + "build": "node scripts/build.js", + "update": "node scripts/update.js", + "test": "mocha --reporter spec --bail --check-leaks", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks" + }, + "gitHead": "49e6ac7ae4c63ee8186f56cb52112a7eeda28ed7", + "bugs": { + "url": "https://github.com/jshttp/statuses/issues" + }, + "homepage": "https://github.com/jshttp/statuses", + "_id": "statuses@1.2.1", + "_shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "_from": "statuses@>=1.0.0 <2.0.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "tarball": "http://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/http-errors/package.json b/5-2/service/node_modules/body-parser/node_modules/http-errors/package.json new file mode 100644 index 0000000..41f845d --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/http-errors/package.json @@ -0,0 +1,85 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "1.3.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Alan Plum", + "email": "me@pluma.io" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/http-errors.git" + }, + "dependencies": { + "inherits": "~2.0.1", + "statuses": "1" + }, + "devDependencies": { + "istanbul": "0", + "mocha": "1" + }, + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ], + "gitHead": "89a8502b40d5dd42da2908f265275e2eeb8d0699", + "bugs": { + "url": "https://github.com/jshttp/http-errors/issues" + }, + "homepage": "https://github.com/jshttp/http-errors", + "_id": "http-errors@1.3.1", + "_shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "_from": "http-errors@>=1.3.1 <1.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "egeste", + "email": "npm@egeste.net" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "tarball": "http://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/.npmignore b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/.npmignore new file mode 100644 index 0000000..5cd2673 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/.npmignore @@ -0,0 +1,6 @@ +*~ +*sublime-* +generation +test +wiki +coverage diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/.travis.yml b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/.travis.yml new file mode 100644 index 0000000..f5343f1 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/.travis.yml @@ -0,0 +1,20 @@ + sudo: false + env: + - CXX=g++-4.8 + language: node_js + node_js: + - "0.8" + - "0.10" + - "0.11" + - "0.12" + - "iojs" + - "4.0" + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - gcc-4.8 + - g++-4.8 + before_install: + - "test $TRAVIS_NODE_VERSION != '0.8' || npm install -g npm@1.2.8000" diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/Changelog.md b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/Changelog.md new file mode 100644 index 0000000..421b1e2 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/Changelog.md @@ -0,0 +1,93 @@ + +# 0.4.13 / 2015-10-01 + + * Fix silly mistake in deprecation notice. + + +# 0.4.12 / 2015-09-26 + + * Node v4 support: + * Added CESU-8 decoding (#106) + * Added deprecation notice for `extendNodeEncodings` + * Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol) + + +# 0.4.11 / 2015-07-03 + + * Added CESU-8 encoding. + + +# 0.4.10 / 2015-05-26 + + * Changed UTF-16 endianness heuristic to take into account any ASCII chars, not + just spaces. This should minimize the importance of "default" endianness. + + +# 0.4.9 / 2015-05-24 + + * Streamlined BOM handling: strip BOM by default, add BOM when encoding if + addBOM: true. Added docs to Readme. + * UTF16 now uses UTF16-LE by default. + * Fixed minor issue with big5 encoding. + * Added io.js testing on Travis; updated node-iconv version to test against. + Now we just skip testing SBCS encodings that node-iconv doesn't support. + * (internal refactoring) Updated codec interface to use classes. + * Use strict mode in all files. + + +# 0.4.8 / 2015-04-14 + + * added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94) + + +# 0.4.7 / 2015-02-05 + + * stop official support of Node.js v0.8. Should still work, but no guarantees. + reason: Packages needed for testing are hard to get on Travis CI. + * work in environment where Object.prototype is monkey patched with enumerable + props (#89). + + +# 0.4.6 / 2015-01-12 + + * fix rare aliases of single-byte encodings (thanks @mscdex) + * double the timeout for dbcs tests to make them less flaky on travis + + +# 0.4.5 / 2014-11-20 + + * fix windows-31j and x-sjis encoding support (@nleush) + * minor fix: undefined variable reference when internal error happens + + +# 0.4.4 / 2014-07-16 + + * added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3) + * fixed streaming base64 encoding + + +# 0.4.3 / 2014-06-14 + + * added encodings UTF-16BE and UTF-16 with BOM + + +# 0.4.2 / 2014-06-12 + + * don't throw exception if `extendNodeEncodings()` is called more than once + + +# 0.4.1 / 2014-06-11 + + * codepage 808 added + + +# 0.4.0 / 2014-06-10 + + * code is rewritten from scratch + * all widespread encodings are supported + * streaming interface added + * browserify compatibility added + * (optional) extend core primitive encodings to make usage even simpler + * moved from vows to mocha as the testing framework + + diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/LICENSE b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/LICENSE new file mode 100644 index 0000000..d518d83 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Alexander Shtuchkin + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/README.md b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/README.md new file mode 100644 index 0000000..160b7cf --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/README.md @@ -0,0 +1,157 @@ +## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) + + * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). + * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), + [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. + * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). + * Intuitive encode/decode API + * Streaming support for Node v0.10+ + * [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. + * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). + * License: MIT. + +[![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/) + +## Usage +### Basic API +```javascript +var iconv = require('iconv-lite'); + +// Convert from an encoded buffer to js string. +str = iconv.decode(new Buffer([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); + +// Convert from js string to an encoded buffer. +buf = iconv.encode("Sample input string", 'win1251'); + +// Check if encoding is supported +iconv.encodingExists("us-ascii") +``` + +### Streaming API (Node v0.10+) +```javascript + +// Decode stream (from binary stream to js strings) +http.createServer(function(req, res) { + var converterStream = iconv.decodeStream('win1251'); + req.pipe(converterStream); + + converterStream.on('data', function(str) { + console.log(str); // Do something with decoded strings, chunk-by-chunk. + }); +}); + +// Convert encoding streaming example +fs.createReadStream('file-in-win1251.txt') + .pipe(iconv.decodeStream('win1251')) + .pipe(iconv.encodeStream('ucs2')) + .pipe(fs.createWriteStream('file-in-ucs2.txt')); + +// Sugar: all encode/decode streams have .collect(cb) method to accumulate data. +http.createServer(function(req, res) { + req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { + assert(typeof body == 'string'); + console.log(body); // full request body string + }); +}); +``` + +### [Deprecated] Extend Node.js own encodings +> NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility). + +```javascript +// After this call all Node basic primitives will understand iconv-lite encodings. +iconv.extendNodeEncodings(); + +// Examples: +buf = new Buffer(str, 'win1251'); +buf.write(str, 'gbk'); +str = buf.toString('latin1'); +assert(Buffer.isEncoding('iso-8859-15')); +Buffer.byteLength(str, 'us-ascii'); + +http.createServer(function(req, res) { + req.setEncoding('big5'); + req.collect(function(err, body) { + console.log(body); + }); +}); + +fs.createReadStream("file.txt", "shift_jis"); + +// External modules are also supported (if they use Node primitives, which they probably do). +request = require('request'); +request({ + url: "http://github.com/", + encoding: "cp932" +}); + +// To remove extensions +iconv.undoExtendNodeEncodings(); +``` + +## Supported encodings + + * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. + * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. + * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, + IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. + Aliases like 'latin1', 'us-ascii' also supported. + * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2313, GBK, GB18030, Big5, Shift_JIS, EUC-JP. + +See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). + +Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! + +Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! + + +## Encoding/decoding speed + +Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). +Note: your results may vary, so please always check on your hardware. + + operation iconv@2.1.4 iconv-lite@0.4.7 + ---------------------------------------------------------- + encode('win1251') ~96 Mb/s ~320 Mb/s + decode('win1251') ~95 Mb/s ~246 Mb/s + +## BOM handling + + * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options + (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). + A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. + * Encoding: No BOM added, unless overridden by `addBOM: true` option. + +## UTF-16 Encodings + +This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be +smart about endianness in the following ways: + * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be + overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. + * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. + +## Other notes + +When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). +Untranslatable characters are set to � or ?. No transliteration is currently supported. +Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). + +## Testing + +```bash +$ git clone git@github.com:ashtuchkin/iconv-lite.git +$ cd iconv-lite +$ npm install +$ npm test + +$ # To view performance: +$ node test/performance.js + +$ # To view test coverage: +$ npm run coverage +$ open coverage/lcov-report/index.html +``` + +## Adoption +[![NPM](https://nodei.co/npm-dl/iconv-lite.png)](https://nodei.co/npm/iconv-lite/) +[![Codeship Status for ashtuchkin/iconv-lite](https://www.codeship.io/projects/81670840-fa72-0131-4520-4a01a6c01acc/status)](https://www.codeship.io/projects/29053) diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-codec.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-codec.js new file mode 100644 index 0000000..366809e --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-codec.js @@ -0,0 +1,554 @@ +"use strict" + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = DBCSCodec; + +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; + +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; + + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); + + // Load tables. + var mappingTable = codecOptions.table(); + + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); + + this.defaultCharUnicode = iconv.defaultCharUnicode; + + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); + + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + } + + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); + + + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} + +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); + + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} + + +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} + +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} + +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} + +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} + + + +// == Encoder ================================================================== + +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} + +DBCSEncoder.prototype.write = function(str) { + var newBuf = new Buffer(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } + + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } + + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; + + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; + + } else if (resCode == undefined) { // Current character is not part of the sequence. + + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. + + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } + + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } + + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } + + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} + +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. + + var newBuf = new Buffer(10), j = 0; + + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} + +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; + + +// == Decoder ================================================================== + +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = new Buffer(0); + + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} + +DBCSDecoder.prototype.write = function(buf) { + var newBuf = new Buffer(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; + + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } + + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} + +DBCSDecoder.prototype.end = function() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); + + // Parse remaining as usual. + this.prevBuf = new Buffer(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); + } + + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; + } + return l; +} + diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-data.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-data.js new file mode 100644 index 0000000..2bf7415 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-data.js @@ -0,0 +1,170 @@ +"use strict" + +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. + +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + + + 'shiftjis': { + type: '_dbcs', + table: function() { return require('./tables/shiftjis.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', + + 'eucjp': { + type: '_dbcs', + table: function() { return require('./tables/eucjp.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, + + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + 'isoir58': 'gbk', + + // Microsoft's CP936 is a subset and approximation of GBK. + // TODO: Euro = 0x80 in cp936, but not in GBK (where it's valid but undefined) + 'windows936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json') }, + }, + + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + }, + 'xgbk': 'gbk', + + // GB18030 is an algorithmic extension of GBK. + 'gb18030': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + gb18030: function() { return require('./tables/gb18030-ranges.json') }, + }, + + 'chinese': 'gb18030', + + // TODO: Support GB18030 (~27000 chars + whole unicode mapping, cp54936) + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return require('./tables/cp949.json') }, + }, + + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', + + + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + + 'windows950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json') }, + }, + + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, + encodeSkipVals: [0xa2cc], + }, + + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', + +}; diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/index.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/index.js new file mode 100644 index 0000000..f7892fa --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/index.js @@ -0,0 +1,22 @@ +"use strict" + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + require("./internal"), + require("./utf16"), + require("./utf7"), + require("./sbcs-codec"), + require("./sbcs-data"), + require("./sbcs-data-generated"), + require("./dbcs-codec"), + require("./dbcs-data"), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; +} diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/internal.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/internal.js new file mode 100644 index 0000000..a8ae512 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/internal.js @@ -0,0 +1,187 @@ +"use strict" + +// Export Node.js internal encodings. + +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", + + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", + + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + + // Codec. + _internal: InternalCodec, +}; + +//------------------------------------------------------------------------------ + +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (new Buffer("eda080", 'hex').toString().length == 3) { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } +} + +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; + +//------------------------------------------------------------------------------ + +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = require('string_decoder').StringDecoder; + +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; + + +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); +} + +InternalDecoder.prototype = StringDecoder.prototype; + + +//------------------------------------------------------------------------------ +// Encoder is mostly trivial + +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} + +InternalEncoder.prototype.write = function(str) { + return new Buffer(str, this.enc); +} + +InternalEncoder.prototype.end = function() { +} + + +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. + +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} + +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + + return new Buffer(str, "base64"); +} + +InternalEncoderBase64.prototype.end = function() { + return new Buffer(this.prevStr, "base64"); +} + + +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8(options, codec) { +} + +InternalEncoderCesu8.prototype.write = function(str) { + var buf = new Buffer(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + } + return buf.slice(0, bufIdx); +} + +InternalEncoderCesu8.prototype.end = function() { +} + +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} + +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; + } + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; + } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; + } + } + } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; +} + +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; +} diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-codec.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-codec.js new file mode 100644 index 0000000..ca00171 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-codec.js @@ -0,0 +1,72 @@ +"use strict" + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; + } + + this.decodeBuf = new Buffer(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = new Buffer(65536); + encodeBuf.fill(iconv.defaultCharSingleByte.charCodeAt(0)); + + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + + this.encodeBuf = encodeBuf; +} + +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; + + +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} + +SBCSEncoder.prototype.write = function(str) { + var buf = new Buffer(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} + +SBCSEncoder.prototype.end = function() { +} + + +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} + +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = new Buffer(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; + } + return newBuf.toString('ucs2'); +} + +SBCSDecoder.prototype.end = function() { +} diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data-generated.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data-generated.js new file mode 100644 index 0000000..2308c91 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data-generated.js @@ -0,0 +1,451 @@ +"use strict" + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹ�ֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } +} \ No newline at end of file diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data.js new file mode 100644 index 0000000..2058a71 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data.js @@ -0,0 +1,169 @@ +"use strict" + +// Manually added data to be used by sbcs codec in addition to generated one. + +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", + + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", + + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", + + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + + "cp819": "iso88591", + "ibm819": "iso88591", + + "cyrillic": "iso88595", + + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", + + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", + + "hebrew": "iso88598", + "hebrew8": "iso88598", + + "turkish": "iso88599", + "turkish8": "iso88599", + + "thai": "iso885911", + "thai8": "iso885911", + + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", + + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", + + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", +}; + diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/big5-added.json b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/big5-added.json new file mode 100644 index 0000000..3c3d3c2 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/big5-added.json @@ -0,0 +1,122 @@ +[ +["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], +["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], +["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], +["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], +["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], +["8940","𪎩𡅅"], +["8943","攊"], +["8946","丽滝鵎釟"], +["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], +["89a1","琑糼緍楆竉刧"], +["89ab","醌碸酞肼"], +["89b0","贋胶𠧧"], +["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], +["89c1","溚舾甙"], +["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], +["8a40","𧶄唥"], +["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], +["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], +["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], +["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], +["8aac","䠋𠆩㿺塳𢶍"], +["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], +["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], +["8ac9","𪘁𠸉𢫏𢳉"], +["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], +["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], +["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], +["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], +["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], +["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], +["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], +["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], +["8ca1","𣏹椙橃𣱣泿"], +["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], +["8cc9","顨杫䉶圽"], +["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], +["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], +["8d40","𠮟"], +["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], +["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], +["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], +["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], +["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], +["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], +["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], +["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], +["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], +["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], +["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], +["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], +["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], +["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], +["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], +["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], +["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], +["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], +["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], +["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], +["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], +["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], +["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], +["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], +["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], +["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], +["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], +["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], +["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], +["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], +["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], +["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], +["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], +["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], +["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], +["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], +["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], +["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], +["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], +["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], +["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], +["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], +["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], +["9fae","酙隁酜"], +["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], +["9fc1","𤤙盖鮝个𠳔莾衂"], +["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], +["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], +["9fe7","毺蠘罸"], +["9feb","嘠𪙊蹷齓"], +["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], +["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], +["a055","𡠻𦸅"], +["a058","詾𢔛"], +["a05b","惽癧髗鵄鍮鮏蟵"], +["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], +["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], +["a0a1","嵗𨯂迚𨸹"], +["a0a6","僙𡵆礆匲阸𠼻䁥"], +["a0ae","矾"], +["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], +["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], +["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], +["a3c0","␀",31,"␡"], +["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], +["c740","す",58,"ァアィイ"], +["c7a1","ゥ",81,"А",5,"ЁЖ",4], +["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], +["c8a1","龰冈龱𧘇"], +["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], +["c8f5","ʃɐɛɔɵœøŋʊɪ"], +["f9fe","■"], +["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], +["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], +["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], +["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], +["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], +["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], +["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], +["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], +["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], +["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] +] diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp936.json b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp936.json new file mode 100644 index 0000000..49ddb9a --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp936.json @@ -0,0 +1,264 @@ +[ +["0","\u0000",127,"€"], +["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], +["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], +["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], +["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], +["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], +["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], +["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], +["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], +["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], +["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], +["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], +["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], +["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], +["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], +["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], +["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], +["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], +["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], +["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], +["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], +["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], +["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], +["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], +["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], +["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], +["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], +["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], +["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], +["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], +["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], +["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], +["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], +["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], +["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], +["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], +["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], +["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], +["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], +["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], +["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], +["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], +["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], +["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], +["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], +["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], +["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], +["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], +["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], +["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], +["9980","檧檨檪檭",114,"欥欦欨",6], +["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], +["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], +["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], +["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], +["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], +["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], +["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], +["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], +["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], +["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], +["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], +["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], +["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], +["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], +["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], +["a2a1","ⅰ",9], +["a2b1","⒈",19,"⑴",19,"①",9], +["a2e5","㈠",9], +["a2f1","Ⅰ",11], +["a3a1","!"#¥%",88," ̄"], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], +["a6ee","︻︼︷︸︱"], +["a6f4","︳︴"], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], +["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], +["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], +["a8bd","ńň"], +["a8c0","ɡ"], +["a8c5","ㄅ",36], +["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], +["a959","℡㈱"], +["a95c","‐"], +["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], +["a980","﹢",4,"﹨﹩﹪﹫"], +["a996","〇"], +["a9a4","─",75], +["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], +["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], +["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], +["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], +["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], +["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], +["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], +["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], +["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], +["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], +["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], +["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], +["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], +["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], +["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], +["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], +["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], +["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], +["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], +["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], +["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], +["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], +["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], +["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], +["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], +["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], +["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], +["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], +["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], +["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], +["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], +["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], +["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], +["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], +["bb40","籃",9,"籎",36,"籵",5,"籾",9], +["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], +["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], +["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], +["bd40","紷",54,"絯",7], +["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], +["be40","継",12,"綧",6,"綯",42], +["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], +["bf40","緻",62], +["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], +["c040","繞",35,"纃",23,"纜纝纞"], +["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], +["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], +["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], +["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], +["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], +["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], +["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], +["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], +["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], +["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], +["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], +["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], +["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], +["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], +["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], +["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], +["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], +["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], +["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], +["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], +["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], +["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], +["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], +["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], +["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], +["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], +["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], +["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], +["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], +["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], +["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], +["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], +["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], +["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], +["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], +["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], +["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], +["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], +["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], +["d440","訞",31,"訿",8,"詉",21], +["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], +["d540","誁",7,"誋",7,"誔",46], +["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], +["d640","諤",34,"謈",27], +["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], +["d740","譆",31,"譧",4,"譭",25], +["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], +["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], +["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], +["d940","貮",62], +["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], +["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], +["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], +["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], +["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], +["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], +["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], +["dd40","軥",62], +["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], +["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], +["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], +["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], +["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], +["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], +["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], +["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], +["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], +["e240","釦",62], +["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], +["e340","鉆",45,"鉵",16], +["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], +["e440","銨",5,"銯",24,"鋉",31], +["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], +["e540","錊",51,"錿",10], +["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], +["e640","鍬",34,"鎐",27], +["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], +["e740","鏎",7,"鏗",54], +["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], +["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], +["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], +["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], +["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], +["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], +["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], +["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], +["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], +["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], +["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], +["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], +["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], +["ee40","頏",62], +["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], +["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], +["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], +["f040","餈",4,"餎餏餑",28,"餯",26], +["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], +["f140","馌馎馚",10,"馦馧馩",47], +["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], +["f240","駺",62], +["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], +["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], +["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], +["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], +["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], +["f540","魼",62], +["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], +["f640","鯜",62], +["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], +["f740","鰼",62], +["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], +["f840","鳣",62], +["f880","鴢",32], +["f940","鵃",62], +["f980","鶂",32], +["fa40","鶣",62], +["fa80","鷢",32], +["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], +["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], +["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], +["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], +["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], +["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], +["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] +] diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp949.json b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp949.json new file mode 100644 index 0000000..2022a00 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp949.json @@ -0,0 +1,273 @@ +[ +["0","\u0000",127], +["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], +["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], +["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], +["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], +["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], +["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], +["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], +["8361","긝",18,"긲긳긵긶긹긻긼"], +["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], +["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], +["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], +["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], +["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], +["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], +["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], +["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], +["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], +["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], +["8741","놞",9,"놩",15], +["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], +["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], +["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], +["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], +["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], +["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], +["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], +["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], +["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], +["8a61","둧",4,"둭",18,"뒁뒂"], +["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], +["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], +["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], +["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], +["8c41","똀",15,"똒똓똕똖똗똙",4], +["8c61","똞",6,"똦",5,"똭",6,"똵",5], +["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], +["8d41","뛃",16,"뛕",8], +["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], +["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], +["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], +["8e61","럂",4,"럈럊",19], +["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], +["8f41","뢅",7,"뢎",17], +["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], +["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], +["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], +["9061","륾",5,"릆릈릋릌릏",15], +["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], +["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], +["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], +["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], +["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], +["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], +["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], +["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], +["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], +["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], +["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], +["9461","봞",5,"봥",6,"봭",12], +["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], +["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], +["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], +["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], +["9641","뺸",23,"뻒뻓"], +["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], +["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], +["9741","뾃",16,"뾕",8], +["9761","뾞",17,"뾱",7], +["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], +["9841","쁀",16,"쁒",5,"쁙쁚쁛"], +["9861","쁝쁞쁟쁡",6,"쁪",15], +["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], +["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], +["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], +["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], +["9a41","숤숥숦숧숪숬숮숰숳숵",16], +["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], +["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], +["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], +["9b61","쌳",17,"썆",7], +["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], +["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], +["9c61","쏿",8,"쐉",6,"쐑",9], +["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], +["9d41","쒪",13,"쒹쒺쒻쒽",8], +["9d61","쓆",25], +["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], +["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], +["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], +["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], +["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], +["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], +["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], +["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], +["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], +["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], +["a141","좥좦좧좩",18,"좾좿죀죁"], +["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], +["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], +["a241","줐줒",5,"줙",18], +["a261","줭",6,"줵",18], +["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], +["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], +["a361","즑",6,"즚즜즞",16], +["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], +["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], +["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], +["a481","쨦쨧쨨쨪",28,"ㄱ",93], +["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], +["a561","쩫",17,"쩾",5,"쪅쪆"], +["a581","쪇",16,"쪙",14,"ⅰ",9], +["a5b0","Ⅰ",9], +["a5c1","Α",16,"Σ",6], +["a5e1","α",16,"σ",6], +["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], +["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], +["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], +["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], +["a761","쬪",22,"쭂쭃쭄"], +["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], +["a841","쭭",10,"쭺",14], +["a861","쮉",18,"쮝",6], +["a881","쮤",19,"쮹",11,"ÆЪĦ"], +["a8a6","IJ"], +["a8a8","ĿŁØŒºÞŦŊ"], +["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], +["a941","쯅",14,"쯕",10], +["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], +["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], +["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], +["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], +["aa81","챳챴챶",29,"ぁ",82], +["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], +["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], +["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], +["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], +["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], +["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], +["acd1","а",5,"ёж",25], +["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], +["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], +["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], +["ae41","췆",5,"췍췎췏췑",16], +["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], +["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], +["af41","츬츭츮츯츲츴츶",19], +["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], +["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], +["b041","캚",5,"캢캦",5,"캮",12], +["b061","캻",5,"컂",19], +["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], +["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], +["b161","켥",6,"켮켲",5,"켹",11], +["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], +["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], +["b261","쾎",18,"쾢",5,"쾩"], +["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], +["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], +["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], +["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], +["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], +["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], +["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], +["b541","킕",14,"킦킧킩킪킫킭",5], +["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], +["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], +["b641","턅",7,"턎",17], +["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], +["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], +["b741","텮",13,"텽",6,"톅톆톇톉톊"], +["b761","톋",20,"톢톣톥톦톧"], +["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], +["b841","퇐",7,"퇙",17], +["b861","퇫",8,"퇵퇶퇷퇹",13], +["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], +["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], +["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], +["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], +["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], +["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], +["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], +["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], +["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], +["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], +["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], +["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], +["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], +["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], +["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], +["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], +["be41","퐸",7,"푁푂푃푅",14], +["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], +["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], +["bf41","풞",10,"풪",14], +["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], +["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], +["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], +["c061","픞",25], +["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], +["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], +["c161","햌햍햎햏햑",19,"햦햧"], +["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], +["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], +["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], +["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], +["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], +["c361","홢",4,"홨홪",5,"홲홳홵",11], +["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], +["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], +["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], +["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], +["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], +["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], +["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], +["c641","힍힎힏힑",6,"힚힜힞",5], +["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], +["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], +["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], +["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], +["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], +["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], +["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], +["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], +["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], +["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], +["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], +["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], +["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], +["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], +["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], +["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], +["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], +["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], +["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], +["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], +["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], +["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], +["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], +["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], +["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], +["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], +["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], +["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], +["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], +["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], +["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], +["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], +["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], +["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], +["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], +["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], +["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], +["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], +["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], +["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], +["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], +["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], +["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], +["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], +["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], +["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], +["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], +["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], +["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], +["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], +["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], +["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], +["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], +["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], +["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] +] diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp950.json b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp950.json new file mode 100644 index 0000000..d8bc871 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp950.json @@ -0,0 +1,177 @@ +[ +["0","\u0000",127], +["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], +["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], +["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], +["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], +["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], +["a3a1","ㄐ",25,"˙ˉˊˇˋ"], +["a3e1","€"], +["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], +["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], +["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], +["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], +["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], +["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], +["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], +["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], +["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], +["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], +["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], +["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], +["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], +["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], +["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], +["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], +["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], +["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], +["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], +["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], +["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], +["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], +["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], +["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], +["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], +["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], +["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], +["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], +["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], +["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], +["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], +["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], +["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], +["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], +["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], +["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], +["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], +["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], +["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], +["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], +["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], +["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], +["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], +["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], +["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], +["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], +["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], +["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], +["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], +["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], +["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], +["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], +["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], +["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], +["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], +["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], +["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], +["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], +["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], +["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], +["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], +["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], +["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], +["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], +["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], +["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], +["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], +["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], +["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], +["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], +["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], +["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], +["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], +["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], +["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], +["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], +["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], +["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], +["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], +["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], +["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], +["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], +["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], +["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], +["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], +["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], +["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], +["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], +["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], +["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], +["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], +["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], +["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], +["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], +["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], +["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], +["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], +["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], +["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], +["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], +["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], +["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], +["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], +["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], +["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], +["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], +["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], +["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], +["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], +["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], +["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], +["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], +["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], +["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], +["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], +["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], +["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], +["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], +["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], +["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], +["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], +["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], +["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], +["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], +["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], +["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], +["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], +["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], +["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], +["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], +["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], +["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], +["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], +["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], +["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], +["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], +["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], +["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], +["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], +["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], +["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], +["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], +["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], +["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], +["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], +["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], +["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], +["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], +["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], +["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], +["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], +["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], +["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], +["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], +["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], +["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], +["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], +["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], +["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], +["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], +["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], +["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], +["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], +["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], +["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], +["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], +["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] +] diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/eucjp.json b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/eucjp.json new file mode 100644 index 0000000..4fa61ca --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/eucjp.json @@ -0,0 +1,182 @@ +[ +["0","\u0000",127], +["8ea1","。",62], +["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], +["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], +["a2ba","∈∋⊆⊇⊂⊃∪∩"], +["a2ca","∧∨¬⇒⇔∀∃"], +["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["a2f2","ʼn♯♭♪†‡¶"], +["a2fe","◯"], +["a3b0","0",9], +["a3c1","A",25], +["a3e1","a",25], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["ada1","①",19,"Ⅰ",9], +["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], +["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], +["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], +["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], +["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], +["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], +["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], +["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], +["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], +["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], +["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], +["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], +["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], +["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], +["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], +["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], +["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], +["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], +["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], +["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], +["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], +["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], +["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], +["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], +["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], +["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], +["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], +["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], +["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], +["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], +["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], +["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], +["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], +["f4a1","堯槇遙瑤凜熙"], +["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], +["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], +["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["fcf1","ⅰ",9,"¬¦'""], +["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], +["8fa2c2","¡¦¿"], +["8fa2eb","ºª©®™¤№"], +["8fa6e1","ΆΈΉΊΪ"], +["8fa6e7","Ό"], +["8fa6e9","ΎΫ"], +["8fa6ec","Ώ"], +["8fa6f1","άέήίϊΐόςύϋΰώ"], +["8fa7c2","Ђ",10,"ЎЏ"], +["8fa7f2","ђ",10,"ўџ"], +["8fa9a1","ÆĐ"], +["8fa9a4","Ħ"], +["8fa9a6","IJ"], +["8fa9a8","ŁĿ"], +["8fa9ab","ŊØŒ"], +["8fa9af","ŦÞ"], +["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], +["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], +["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], +["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], +["8fabbd","ġĥíìïîǐ"], +["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], +["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], +["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], +["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], +["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], +["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], +["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], +["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], +["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], +["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], +["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], +["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], +["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], +["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], +["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], +["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], +["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], +["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], +["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], +["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], +["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], +["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], +["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], +["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], +["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], +["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], +["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], +["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], +["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], +["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], +["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], +["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], +["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], +["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], +["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], +["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], +["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], +["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], +["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], +["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], +["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], +["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], +["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], +["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], +["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], +["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], +["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], +["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], +["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], +["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], +["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], +["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], +["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], +["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], +["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], +["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], +["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], +["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], +["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], +["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], +["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], +["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], +["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] +] diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json new file mode 100644 index 0000000..85c6934 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json @@ -0,0 +1 @@ +{"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} \ No newline at end of file diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gbk-added.json b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gbk-added.json new file mode 100644 index 0000000..8abfa9f --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gbk-added.json @@ -0,0 +1,55 @@ +[ +["a140","",62], +["a180","",32], +["a240","",62], +["a280","",32], +["a2ab","",5], +["a2e3","€"], +["a2ef",""], +["a2fd",""], +["a340","",62], +["a380","",31," "], +["a440","",62], +["a480","",32], +["a4f4","",10], +["a540","",62], +["a580","",32], +["a5f7","",7], +["a640","",62], +["a680","",32], +["a6b9","",7], +["a6d9","",6], +["a6ec",""], +["a6f3",""], +["a6f6","",8], +["a740","",62], +["a780","",32], +["a7c2","",14], +["a7f2","",12], +["a896","",10], +["a8bc",""], +["a8bf","ǹ"], +["a8c1",""], +["a8ea","",20], +["a958",""], +["a95b",""], +["a95d",""], +["a989","〾⿰",11], +["a997","",12], +["a9f0","",14], +["aaa1","",93], +["aba1","",93], +["aca1","",93], +["ada1","",93], +["aea1","",93], +["afa1","",93], +["d7fa","",4], +["f8a1","",93], +["f9a1","",93], +["faa1","",93], +["fba1","",93], +["fca1","",93], +["fda1","",93], +["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], +["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93] +] diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/shiftjis.json b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/shiftjis.json new file mode 100644 index 0000000..5a3a43c --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/shiftjis.json @@ -0,0 +1,125 @@ +[ +["0","\u0000",128], +["a1","。",62], +["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], +["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], +["81b8","∈∋⊆⊇⊂⊃∪∩"], +["81c8","∧∨¬⇒⇔∀∃"], +["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["81f0","ʼn♯♭♪†‡¶"], +["81fc","◯"], +["824f","0",9], +["8260","A",25], +["8281","a",25], +["829f","ぁ",82], +["8340","ァ",62], +["8380","ム",22], +["839f","Α",16,"Σ",6], +["83bf","α",16,"σ",6], +["8440","А",5,"ЁЖ",25], +["8470","а",5,"ёж",7], +["8480","о",17], +["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["8740","①",19,"Ⅰ",9], +["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["877e","㍻"], +["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], +["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], +["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], +["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], +["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], +["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], +["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], +["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], +["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], +["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], +["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], +["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], +["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], +["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], +["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], +["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], +["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], +["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], +["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], +["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], +["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], +["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], +["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], +["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], +["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], +["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], +["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], +["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], +["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], +["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], +["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], +["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], +["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], +["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], +["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], +["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], +["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["eeef","ⅰ",9,"¬¦'""], +["f040","",62], +["f080","",124], +["f140","",62], +["f180","",124], +["f240","",62], +["f280","",124], +["f340","",62], +["f380","",124], +["f440","",62], +["f480","",124], +["f540","",62], +["f580","",124], +["f640","",62], +["f680","",124], +["f740","",62], +["f780","",124], +["f840","",62], +["f880","",124], +["f940",""], +["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], +["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], +["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], +["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], +["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] +] diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/utf16.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/utf16.js new file mode 100644 index 0000000..399f551 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/utf16.js @@ -0,0 +1,174 @@ +"use strict" + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { +} + +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf16BEEncoder() { +} + +Utf16BEEncoder.prototype.write = function(str) { + var buf = new Buffer(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; + } + return buf; +} + +Utf16BEEncoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf16BEDecoder() { + this.overflowByte = -1; +} + +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; + + var buf2 = new Buffer(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); +} + +Utf16BEDecoder.prototype.end = function() { +} + + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} + +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} + +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} + +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} + + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; + } + + return this.decoder.write(buf); +} + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var res = this.decoder.write(buf), + trail = this.decoder.end(); + + return trail ? (res + trail) : res; + } + return this.decoder.end(); +} + +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; + + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be'; + else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le'; + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; + } + + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; + } + } + + return enc; +} + + diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/utf7.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/utf7.js new file mode 100644 index 0000000..bab5099 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/encodings/utf7.js @@ -0,0 +1,289 @@ +"use strict" + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} + +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return new Buffer(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + +Utf7Encoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(new Buffer(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = new Buffer(6); + this.base64AccumIdx = 0; +} + +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = new Buffer(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } + } + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +Utf7IMAPEncoder.prototype.end = function() { + var buf = new Buffer(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; + } + + return buf.slice(0, bufIdx); +} + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(new Buffer(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/bom-handling.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/bom-handling.js new file mode 100644 index 0000000..3f0ed93 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/bom-handling.js @@ -0,0 +1,52 @@ +"use strict" + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; + } + + return this.encoder.write(str); +} + +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} + + +//------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} + +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); + } + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} + diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/extend-node.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/extend-node.js new file mode 100644 index 0000000..1d8c953 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/extend-node.js @@ -0,0 +1,214 @@ +"use strict" + +// == Extend Node primitives to use iconv-lite ================================= + +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + iconv.supportsNodeEncodingsExtension = !(new Buffer(0) instanceof Uint8Array); + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; + } + + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, + }; + + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; + } + + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = require('buffer').SlowBuffer; + + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + } + + // -- Buffer --------------------------------------------------------------- + + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); + } + + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); + + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; + } + + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + + // TODO: Set _charsWritten. + } + + + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; + } + + Readable.prototype.collect = iconv._collect; + } + } + + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) + return; + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + + delete Buffer.isNativeEncoding; + + var SlowBuffer = require('buffer').SlowBuffer; + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } +} diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/index.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/index.js new file mode 100644 index 0000000..ac1403c --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/index.js @@ -0,0 +1,141 @@ +"use strict" + +var bomHandling = require('./bom-handling'), + iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = new Buffer("" + (buf || ""), "binary"); // Ensure buffer. + } + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; + } +} + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = (''+encoding).toLowerCase().replace(/[^0-9a-z]|:\d{4}$/g, ""); + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; + + var codecDef = iconv.encodings[enc]; + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; + + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); + + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} + +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); + + return encoder; +} + +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; +} + + +// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; +if (nodeVer) { + + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + require("./streams")(iconv); + } + + // Load Node primitive extensions. + require("./extend-node")(iconv); +} + diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/streams.js b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/streams.js new file mode 100644 index 0000000..c95b26c --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/lib/streams.js @@ -0,0 +1,120 @@ +"use strict" + +var Transform = require("stream").Transform; + + +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + } + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + } + + iconv.supportsStreams = true; + + + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; + + +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); +} + +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; +} + + +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); +} + +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); + +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; +} + diff --git a/5-2/service/node_modules/body-parser/node_modules/iconv-lite/package.json b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/package.json new file mode 100644 index 0000000..22c80f3 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/iconv-lite/package.json @@ -0,0 +1,118 @@ +{ + "name": "iconv-lite", + "description": "Convert character encodings in pure javascript.", + "version": "0.4.13", + "license": "MIT", + "keywords": [ + "iconv", + "convert", + "charset", + "icu" + ], + "author": { + "name": "Alexander Shtuchkin", + "email": "ashtuchkin@gmail.com" + }, + "contributors": [ + { + "name": "Jinwu Zhan", + "url": "https://github.com/jenkinv" + }, + { + "name": "Adamansky Anton", + "url": "https://github.com/adamansky" + }, + { + "name": "George Stagas", + "url": "https://github.com/stagas" + }, + { + "name": "Mike D Pilsbury", + "url": "https://github.com/pekim" + }, + { + "name": "Niggler", + "url": "https://github.com/Niggler" + }, + { + "name": "wychi", + "url": "https://github.com/wychi" + }, + { + "name": "David Kuo", + "url": "https://github.com/david50407" + }, + { + "name": "ChangZhuo Chen", + "url": "https://github.com/czchen" + }, + { + "name": "Lee Treveil", + "url": "https://github.com/leetreveil" + }, + { + "name": "Brian White", + "url": "https://github.com/mscdex" + }, + { + "name": "Mithgol", + "url": "https://github.com/Mithgol" + }, + { + "name": "Nazar Leush", + "url": "https://github.com/nleush" + } + ], + "main": "./lib/index.js", + "homepage": "https://github.com/ashtuchkin/iconv-lite", + "bugs": { + "url": "https://github.com/ashtuchkin/iconv-lite/issues" + }, + "repository": { + "type": "git", + "url": "git://github.com/ashtuchkin/iconv-lite.git" + }, + "engines": { + "node": ">=0.8.0" + }, + "scripts": { + "coverage": "istanbul cover _mocha -- --grep .", + "coverage-open": "open coverage/lcov-report/index.html", + "test": "mocha --reporter spec --grep ." + }, + "browser": { + "./extend-node": false, + "./streams": false + }, + "devDependencies": { + "mocha": "*", + "request": "2.47", + "unorm": "*", + "errto": "*", + "async": "*", + "istanbul": "*", + "iconv": "2.1" + }, + "gitHead": "f5ec51b1e7dd1477a3570824960641eebdc5fbc6", + "_id": "iconv-lite@0.4.13", + "_shasum": "1f88aba4ab0b1508e8312acc39345f36e992e2f2", + "_from": "iconv-lite@0.4.13", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.1", + "_npmUser": { + "name": "ashtuchkin", + "email": "ashtuchkin@gmail.com" + }, + "maintainers": [ + { + "name": "ashtuchkin", + "email": "ashtuchkin@gmail.com" + } + ], + "dist": { + "shasum": "1f88aba4ab0b1508e8312acc39345f36e992e2f2", + "tarball": "http://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.13.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.13.tgz" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/on-finished/HISTORY.md b/5-2/service/node_modules/body-parser/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000..98ff0e9 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/on-finished/HISTORY.md @@ -0,0 +1,88 @@ +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +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 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/5-2/service/node_modules/body-parser/node_modules/on-finished/LICENSE b/5-2/service/node_modules/body-parser/node_modules/on-finished/LICENSE new file mode 100644 index 0000000..5931fd2 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/body-parser/node_modules/on-finished/README.md b/5-2/service/node_modules/body-parser/node_modules/on-finished/README.md new file mode 100644 index 0000000..a0e1157 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/on-finished/README.md @@ -0,0 +1,154 @@ +# on-finished + +[![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] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to 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, res) { + // clean up open fds, etc. + // err contains the error is request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to 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 = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg +[downloads-url]: https://npmjs.org/package/on-finished diff --git a/5-2/service/node_modules/body-parser/node_modules/on-finished/index.js b/5-2/service/node_modules/body-parser/node_modules/on-finished/index.js new file mode 100644 index 0000000..9abd98f --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/on-finished/index.js @@ -0,0 +1,196 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener(msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish(error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket) + callback(socket) + } +} diff --git a/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/LICENSE b/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/README.md b/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/index.js b/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/package.json b/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/package.json new file mode 100644 index 0000000..1d223fb --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/package.json @@ -0,0 +1,64 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jonathanong/ee-first.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "512e0ce4cc3643f603708f965a97b61b1a9c0441", + "bugs": { + "url": "https://github.com/jonathanong/ee-first/issues" + }, + "homepage": "https://github.com/jonathanong/ee-first", + "_id": "ee-first@1.1.1", + "_shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "_from": "ee-first@1.1.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/on-finished/package.json b/5-2/service/node_modules/body-parser/node_modules/on-finished/package.json new file mode 100644 index 0000000..7b2ebdd --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/on-finished/package.json @@ -0,0 +1,71 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.3.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/on-finished.git" + }, + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "34babcb58126a416fcf5205768204f2e12699dda", + "bugs": { + "url": "https://github.com/jshttp/on-finished/issues" + }, + "homepage": "https://github.com/jshttp/on-finished", + "_id": "on-finished@2.3.0", + "_shasum": "20f1336481b083cd75337992a16971aa2d906947", + "_from": "on-finished@>=2.3.0 <2.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "20f1336481b083cd75337992a16971aa2d906947", + "tarball": "http://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/.eslintignore b/5-2/service/node_modules/body-parser/node_modules/qs/.eslintignore new file mode 100644 index 0000000..1521c8b --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/.eslintignore @@ -0,0 +1 @@ +dist diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/.npmignore b/5-2/service/node_modules/body-parser/node_modules/qs/.npmignore new file mode 100644 index 0000000..7e1574d --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/.npmignore @@ -0,0 +1,18 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov +complexity.md diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/.travis.yml b/5-2/service/node_modules/body-parser/node_modules/qs/.travis.yml new file mode 100644 index 0000000..335fded --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/.travis.yml @@ -0,0 +1,8 @@ +language: node_js + +node_js: + - 0.10 + - 4.0 + - 4 + +sudo: false diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/CHANGELOG.md b/5-2/service/node_modules/body-parser/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000..e43b1ac --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/CHANGELOG.md @@ -0,0 +1,99 @@ + +## [**5.1.0**](https://github.com/hapijs/qs/issues?milestone=29&state=open) +- [**#117**](https://github.com/hapijs/qs/issues/117) make URI encoding stringified results optional +- [**#106**](https://github.com/hapijs/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify + +## [**5.0.0**](https://github.com/hapijs/qs/issues?milestone=28&state=closed) +- [**#114**](https://github.com/hapijs/qs/issues/114) default allowDots to false +- [**#100**](https://github.com/hapijs/qs/issues/100) include dist to npm + +## [**4.0.0**](https://github.com/hapijs/qs/issues?milestone=26&state=closed) +- [**#98**](https://github.com/hapijs/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional + +## [**3.1.0**](https://github.com/hapijs/qs/issues?milestone=24&state=closed) +- [**#89**](https://github.com/hapijs/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/hapijs/qs/issues?milestone=23&state=closed) +- [**#80**](https://github.com/hapijs/qs/issues/80) qs.parse silently drops properties +- [**#77**](https://github.com/hapijs/qs/issues/77) Perf boost +- [**#60**](https://github.com/hapijs/qs/issues/60) Add explicit option to disable array parsing +- [**#74**](https://github.com/hapijs/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/hapijs/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/hapijs/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/hapijs/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/hapijs/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/hapijs/qs/issues/85) No equal sign +- [**#84**](https://github.com/hapijs/qs/issues/84) update license attribute + +## [**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". + +## [**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 + +## [**2.2.5**](https://github.com/hapijs/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/hapijs/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/hapijs/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/hapijs/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/hapijs/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/hapijs/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/hapijs/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/hapijs/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/hapijs/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/hapijs/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/hapijs/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/hapijs/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/hapijs/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/hapijs/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/hapijs/qs/issues/32) account for circular references properly, closes #31 +- [**#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 +- [**#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 +- [**#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) +- [**#22**](https://github.com/hapijs/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/hapijs/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/hapijs/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/hapijs/qs/issues/20) Configurable parametersLimit +- [**#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 + +## [**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 +- [**#15**](https://github.com/hapijs/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/hapijs/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/hapijs/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/hapijs/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/hapijs/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/hapijs/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/hapijs/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/hapijs/qs/issues/6) Minor grammar fix in README + +## [**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/5-2/service/node_modules/body-parser/node_modules/qs/CONTRIBUTING.md b/5-2/service/node_modules/body-parser/node_modules/qs/CONTRIBUTING.md new file mode 100644 index 0000000..8928361 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/CONTRIBUTING.md @@ -0,0 +1 @@ +Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md). diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/LICENSE b/5-2/service/node_modules/body-parser/node_modules/qs/LICENSE new file mode 100644 index 0000000..d456948 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/README.md b/5-2/service/node_modules/body-parser/node_modules/qs/README.md new file mode 100644 index 0000000..3c61db3 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/README.md @@ -0,0 +1,331 @@ +# qs + +A querystring parsing and stringifying library with some added security. + +[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs) + +Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var Qs = require('qs'); + +var obj = Qs.parse('a=c'); // { a: 'c' } +var str = Qs.stringify(obj); // 'a=c' +``` + +### Parsing Objects + +```javascript +Qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +{ + foo: { + bar: 'baz' + } +} +``` + +When using the `plainObjects` option the parsed value is returned as a plain object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +Qs.parse('a.hasOwnProperty=b', { plainObjects: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. + +```javascript +Qs.parse('a.hasOwnProperty=b', { allowPrototypes: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +URI encoded strings work too: + +```javascript +Qs.parse('a%5Bb%5D=c'); +// { a: { b: 'c' } } +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +{ + foo: { + bar: { + baz: 'foobarbaz' + } + } +} +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +{ + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +} +``` + +This depth can be overridden by passing a `depth` option to `Qs.parse(string, [options])`: + +```javascript +Qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } } +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +Qs.parse('a=b&c=d', { parameterLimit: 1 }); +// { a: 'b' } +``` + +An optional delimiter can also be passed: + +```javascript +Qs.parse('a=b;c=d', { delimiter: ';' }); +// { a: 'b', c: 'd' } +``` + +Delimiters can be a regular expression too: + +```javascript +Qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +// { a: 'b', c: 'd', e: 'f' } +``` + +Option `allowDots` can be used to enable dot notation: + +```javascript +Qs.parse('a.b=c', { allowDots: true }); +// { a: { b: 'c' } } +``` + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +Qs.parse('a[]=b&a[]=c'); +// { a: ['b', 'c'] } +``` + +You may specify an index as well: + +```javascript +Qs.parse('a[1]=c&a[0]=b'); +// { a: ['b', 'c'] } +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +Qs.parse('a[1]=b&a[15]=c'); +// { a: ['b', 'c'] } +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +Qs.parse('a[]=&a[]=b'); +// { a: ['', 'b'] } +Qs.parse('a[0]=b&a[1]=&a[2]=c'); +// { a: ['b', '', 'c'] } +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key: + +```javascript +Qs.parse('a[100]=b'); +// { a: { '100': 'b' } } +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +Qs.parse('a[1]=b', { arrayLimit: 0 }); +// { a: { '1': 'b' } } +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +Qs.parse('a[]=b', { parseArrays: false }); +// { a: { '0': 'b' } } +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +Qs.parse('a[0]=b&a[b]=c'); +// { a: { '0': 'b', b: 'c' } } +``` + +You can also create arrays of objects: + +```javascript +Qs.parse('a[][b]=c'); +// { a: [{ b: 'c' }] } +``` + +### Stringifying + +```javascript +Qs.stringify(object, [options]); +``` + +When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: + +```javascript +Qs.stringify({ a: 'b' }); +// 'a=b' +Qs.stringify({ a: { b: 'c' } }); +// 'a%5Bb%5D=c' +``` + +This encoding can be disabled by setting the `encode` option to `false`: + +```javascript +Qs.stringify({ a: { b: 'c' } }, { encode: false }); +// 'a[b]=c' +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +Qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +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 +Qs.stringify({ a: '' }); +// 'a=' +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +Qs.stringify({ a: null, b: undefined }); +// 'a=' +``` + +The delimiter may be overridden with stringify as well: + +```javascript +Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }); +// 'a=b;c=d' +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +Qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }) +// 'a=b&c=d&e[f]=123&e[g][0]=4' +Qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }) +// 'a=b&e=f' +Qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }) +// 'a[0]=b&a[2]=d' +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +Qs.stringify({ a: null, b: '' }); +// 'a=&b=' +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +Qs.parse('a&b=') +// { a: '', b: '' } +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +Qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +// 'a&b=' +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +Qs.parse('a&b=', { strictNullHandling: true }); +// { a: null, b: '' } + +``` + +To completely skip rendering keys with `null` values, use the `skipNulls` flag: + +```javascript +qs.stringify({ a: 'b', c: null}, { skipNulls: true }) +// 'a=b' +``` diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/bower.json b/5-2/service/node_modules/body-parser/node_modules/qs/bower.json new file mode 100644 index 0000000..53a70d0 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/bower.json @@ -0,0 +1,22 @@ +{ + "name": "qs", + "main": "dist/qs.js", + "version": "5.1.0", + "homepage": "https://github.com/hapijs/qs", + "authors": [ + "Nathan LaFreniere " + ], + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/component.json b/5-2/service/node_modules/body-parser/node_modules/qs/component.json new file mode 100644 index 0000000..1a1f72c --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/component.json @@ -0,0 +1,15 @@ +{ + "name": "qs", + "repository": "hapijs/qs", + "description": "query-string parser / stringifier with nesting support", + "version": "5.1.0", + "keywords": ["querystring", "query", "parser"], + "main": "lib/index.js", + "scripts": [ + "lib/index.js", + "lib/parse.js", + "lib/stringify.js", + "lib/utils.js" + ], + "license": "BSD-3-Clause" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/dist/qs.js b/5-2/service/node_modules/body-parser/node_modules/qs/dist/qs.js new file mode 100644 index 0000000..b72e976 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/dist/qs.js @@ -0,0 +1,544 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= 0 && + (options.parseArrays && + index <= options.arrayLimit)) { + + obj = []; + obj[index] = internals.parseObject(chain, val, options); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val, options); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, options) { + + if (!key) { + return; + } + + // Transform dot notation to bracket notation + + if (options.allowDots) { + key = key.replace(/\.([^\.\[]+)/g, '[$1]'); + } + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1])) { + + if (!options.allowPrototypes) { + return; + } + } + + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + + ++i; + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { + + if (!options.allowPrototypes) { + continue; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val, options); +}; + + +module.exports = function (str, options) { + + options = options || {}; + options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : internals.allowDots; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : internals.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : internals.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var newObj = internals.parseKeys(key, tempObj[key], options); + obj = Utils.merge(obj, newObj, options); + } + + return Utils.compact(obj); +}; + +},{"./utils":4}],3:[function(require,module,exports){ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + arrayPrefixGenerators: { + brackets: function (prefix, key) { + + return prefix + '[]'; + }, + indices: function (prefix, key) { + + return prefix + '[' + key + ']'; + }, + repeat: function (prefix, key) { + + return prefix; + } + }, + strictNullHandling: false, + skipNulls: false, + encode: true +}; + + +internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter) { + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } + else if (Utils.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + else if (obj === null) { + if (strictNullHandling) { + return encode ? Utils.encode(prefix) : prefix; + } + + obj = ''; + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + if (encode) { + return [Utils.encode(prefix) + '=' + Utils.encode(obj)]; + } + return [prefix + '=' + obj]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys = Array.isArray(filter) ? filter : Object.keys(obj); + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (skipNulls && + obj[key] === null) { + + continue; + } + + if (Array.isArray(obj)) { + values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encode, filter)); + } + else { + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, skipNulls, encode, filter)); + } + } + + return values; +}; + + +module.exports = function (obj, options) { + + options = options || {}; + var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : internals.skipNulls; + var encode = typeof options.encode === 'boolean' ? options.encode : internals.encode; + var objKeys; + var filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } + else if (Array.isArray(options.filter)) { + objKeys = filter = options.filter; + } + + var keys = []; + + if (typeof obj !== 'object' || + obj === null) { + + 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]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (skipNulls && + obj[key] === null) { + + continue; + } + + keys = keys.concat(internals.stringify(obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter)); + } + + return keys.join(delimiter); +}; + +},{"./utils":4}],4:[function(require,module,exports){ +// Load modules + + +// Declare internals + +var internals = {}; +internals.hexTable = new Array(256); +for (var h = 0; h < 256; ++h) { + internals.hexTable[h] = '%' + ((h < 16 ? '0' : '') + h.toString(16)).toUpperCase(); +} + + +exports.arrayToObject = function (source, options) { + + var obj = options.plainObjects ? Object.create(null) : {}; + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.merge = function (target, source, options) { + + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } + else if (typeof target === 'object') { + target[source] = true; + } + else { + target = [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + target = [target].concat(source); + return target; + } + + if (Array.isArray(target) && + !Array.isArray(source)) { + + target = exports.arrayToObject(target, options); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = value; + } + else { + target[key] = exports.merge(target[key], value, options); + } + } + + return target; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function (str) { + + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + if (typeof str !== 'string') { + str = '' + str; + } + + var out = ''; + for (var i = 0, il = str.length; i < il; ++i) { + var c = str.charCodeAt(i); + + if (c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A)) { // A-Z + + out += str[i]; + continue; + } + + if (c < 0x80) { + out += internals.hexTable[c]; + continue; + } + + if (c < 0x800) { + out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + ++i; + c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF)); + out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function (obj, refs) { + + if (typeof obj !== 'object' || + obj === null) { + + return obj; + } + + refs = refs || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } + + refs.push(obj); + + if (Array.isArray(obj)) { + var compacted = []; + + for (var i = 0, il = obj.length; i < il; ++i) { + if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } + + return compacted; + } + + var keys = Object.keys(obj); + for (i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + obj[key] = exports.compact(obj[key], refs); + } + + return obj; +}; + + +exports.isRegExp = function (obj) { + + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + + +exports.isBuffer = function (obj) { + + if (obj === null || + typeof obj === 'undefined') { + + return false; + } + + return !!(obj.constructor && + obj.constructor.isBuffer && + obj.constructor.isBuffer(obj)); +}; + +},{}]},{},[1])(1) +}); \ No newline at end of file diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/lib/index.js b/5-2/service/node_modules/body-parser/node_modules/qs/lib/index.js new file mode 100644 index 0000000..0e09493 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/lib/index.js @@ -0,0 +1,15 @@ +// Load modules + +var Stringify = require('./stringify'); +var Parse = require('./parse'); + + +// Declare internals + +var internals = {}; + + +module.exports = { + stringify: Stringify, + parse: Parse +}; diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/lib/parse.js b/5-2/service/node_modules/body-parser/node_modules/qs/lib/parse.js new file mode 100644 index 0000000..4a2137e --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/lib/parse.js @@ -0,0 +1,187 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + depth: 5, + arrayLimit: 20, + parameterLimit: 1000, + strictNullHandling: false, + plainObjects: false, + allowPrototypes: false, + allowDots: false +}; + + +internals.parseValues = function (str, options) { + + var obj = {}; + var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); + + for (var i = 0, il = parts.length; i < il; ++i) { + var part = parts[i]; + var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; + + if (pos === -1) { + obj[Utils.decode(part)] = ''; + + if (options.strictNullHandling) { + obj[Utils.decode(part)] = null; + } + } + else { + var key = Utils.decode(part.slice(0, pos)); + var val = Utils.decode(part.slice(pos + 1)); + + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + obj[key] = val; + } + else { + obj[key] = [].concat(obj[key]).concat(val); + } + } + } + + return obj; +}; + + +internals.parseObject = function (chain, val, options) { + + if (!chain.length) { + return val; + } + + var root = chain.shift(); + + var obj; + if (root === '[]') { + obj = []; + obj = obj.concat(internals.parseObject(chain, val, options)); + } + else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; + var index = parseInt(cleanRoot, 10); + var indexString = '' + index; + if (!isNaN(index) && + root !== cleanRoot && + indexString === cleanRoot && + index >= 0 && + (options.parseArrays && + index <= options.arrayLimit)) { + + obj = []; + obj[index] = internals.parseObject(chain, val, options); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val, options); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, options) { + + if (!key) { + return; + } + + // Transform dot notation to bracket notation + + if (options.allowDots) { + key = key.replace(/\.([^\.\[]+)/g, '[$1]'); + } + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1])) { + + if (!options.allowPrototypes) { + return; + } + } + + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + + ++i; + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { + + if (!options.allowPrototypes) { + continue; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val, options); +}; + + +module.exports = function (str, options) { + + options = options || {}; + options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : internals.allowDots; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : internals.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : internals.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var newObj = internals.parseKeys(key, tempObj[key], options); + obj = Utils.merge(obj, newObj, options); + } + + return Utils.compact(obj); +}; diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/lib/stringify.js b/5-2/service/node_modules/body-parser/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000..d05aa87 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/lib/stringify.js @@ -0,0 +1,154 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + arrayPrefixGenerators: { + brackets: function (prefix, key) { + + return prefix + '[]'; + }, + indices: function (prefix, key) { + + return prefix + '[' + key + ']'; + }, + repeat: function (prefix, key) { + + return prefix; + } + }, + strictNullHandling: false, + skipNulls: false, + encode: true +}; + + +internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter, sort) { + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } + else if (Utils.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + else if (obj === null) { + if (strictNullHandling) { + return encode ? Utils.encode(prefix) : prefix; + } + + obj = ''; + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + if (encode) { + return [Utils.encode(prefix) + '=' + Utils.encode(obj)]; + } + return [prefix + '=' + obj]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (Array.isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (skipNulls && + obj[key] === null) { + + continue; + } + + if (Array.isArray(obj)) { + values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encode, filter)); + } + else { + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, skipNulls, encode, filter)); + } + } + + return values; +}; + + +module.exports = function (obj, options) { + + options = options || {}; + var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : internals.skipNulls; + var encode = typeof options.encode === 'boolean' ? options.encode : internals.encode; + var sort = typeof options.sort === 'function' ? options.sort : null; + var objKeys; + var filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } + else if (Array.isArray(options.filter)) { + objKeys = filter = options.filter; + } + + var keys = []; + + if (typeof obj !== 'object' || + obj === null) { + + 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]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (sort) { + objKeys.sort(sort); + } + + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (skipNulls && + obj[key] === null) { + + continue; + } + + keys = keys.concat(internals.stringify(obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter, sort)); + } + + return keys.join(delimiter); +}; diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/lib/utils.js b/5-2/service/node_modules/body-parser/node_modules/qs/lib/utils.js new file mode 100644 index 0000000..88f3147 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/lib/utils.js @@ -0,0 +1,190 @@ +// Load modules + + +// Declare internals + +var internals = {}; +internals.hexTable = new Array(256); +for (var h = 0; h < 256; ++h) { + internals.hexTable[h] = '%' + ((h < 16 ? '0' : '') + h.toString(16)).toUpperCase(); +} + + +exports.arrayToObject = function (source, options) { + + var obj = options.plainObjects ? Object.create(null) : {}; + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.merge = function (target, source, options) { + + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } + else if (typeof target === 'object') { + target[source] = true; + } + else { + target = [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + target = [target].concat(source); + return target; + } + + if (Array.isArray(target) && + !Array.isArray(source)) { + + target = exports.arrayToObject(target, options); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = value; + } + else { + target[key] = exports.merge(target[key], value, options); + } + } + + return target; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function (str) { + + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + if (typeof str !== 'string') { + str = '' + str; + } + + var out = ''; + for (var i = 0, il = str.length; i < il; ++i) { + var c = str.charCodeAt(i); + + if (c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A)) { // A-Z + + out += str[i]; + continue; + } + + if (c < 0x80) { + out += internals.hexTable[c]; + continue; + } + + if (c < 0x800) { + out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + ++i; + c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF)); + out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function (obj, refs) { + + if (typeof obj !== 'object' || + obj === null) { + + return obj; + } + + refs = refs || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } + + refs.push(obj); + + if (Array.isArray(obj)) { + var compacted = []; + + for (var i = 0, il = obj.length; i < il; ++i) { + if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } + + return compacted; + } + + var keys = Object.keys(obj); + for (i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + obj[key] = exports.compact(obj[key], refs); + } + + return obj; +}; + + +exports.isRegExp = function (obj) { + + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + + +exports.isBuffer = function (obj) { + + if (obj === null || + typeof obj === 'undefined') { + + return false; + } + + return !!(obj.constructor && + obj.constructor.isBuffer && + obj.constructor.isBuffer(obj)); +}; diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/package.json b/5-2/service/node_modules/body-parser/node_modules/qs/package.json new file mode 100644 index 0000000..0a9e015 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/package.json @@ -0,0 +1,58 @@ +{ + "name": "qs", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/hapijs/qs", + "version": "5.2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/hapijs/qs.git" + }, + "main": "lib/index.js", + "keywords": [ + "querystring", + "qs" + ], + "engines": ">=0.10.40", + "dependencies": {}, + "devDependencies": { + "browserify": "^10.2.1", + "code": "1.x.x", + "lab": "5.x.x" + }, + "scripts": { + "test": "lab -a code -t 100 -L", + "test-tap": "lab -a code -r tap -o tests.tap", + "test-cov-html": "lab -a code -r html -o coverage.html", + "dist": "browserify --standalone Qs lib/index.js > dist/qs.js" + }, + "license": "BSD-3-Clause", + "gitHead": "a341cdf2fadba5ede1ce6c95c7051f6f31f37b81", + "bugs": { + "url": "https://github.com/hapijs/qs/issues" + }, + "_id": "qs@5.2.0", + "_shasum": "a9f31142af468cb72b25b30136ba2456834916be", + "_from": "qs@5.2.0", + "_npmVersion": "3.3.5", + "_nodeVersion": "0.10.40", + "_npmUser": { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + "dist": { + "shasum": "a9f31142af468cb72b25b30136ba2456834916be", + "tarball": "http://registry.npmjs.org/qs/-/qs-5.2.0.tgz" + }, + "maintainers": [ + { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/qs/-/qs-5.2.0.tgz" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/test/parse.js b/5-2/service/node_modules/body-parser/node_modules/qs/test/parse.js new file mode 100644 index 0000000..679f197 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/test/parse.js @@ -0,0 +1,478 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('parse()', function () { + + it('parses a simple string', function (done) { + + expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' }); + expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' }); + expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } }); + expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } }); + expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } }); + expect(Qs.parse('foo', { strictNullHandling: true })).to.deep.equal({ foo: null }); + expect(Qs.parse('foo' )).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=')).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' }); + expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' }); + expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' }); + expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' }); + expect(Qs.parse('foo2=bar2&baz2=')).to.deep.equal({ foo2: 'bar2', baz2: '' }); + expect(Qs.parse('foo=bar&baz', { strictNullHandling: true })).to.deep.equal({ foo: 'bar', baz: null }); + expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' }); + expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({ + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + done(); + }); + + it('allows enabling dot notation', function (done) { + + expect(Qs.parse('a.b=c')).to.deep.equal({ 'a.b': 'c' }); + expect(Qs.parse('a.b=c', { allowDots: true })).to.deep.equal({ a: { b: 'c' } }); + done(); + }); + + it('parses a single nested string', function (done) { + + expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } }); + done(); + }); + + it('parses a double nested string', function (done) { + + expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } }); + done(); + }); + + it('defaults to a depth of 5', function (done) { + + expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }); + done(); + }); + + it('only parses one level when depth = 1', function (done) { + + expect(Qs.parse('a[b][c]=d', { depth: 1 })).to.deep.equal({ a: { b: { '[c]': 'd' } } }); + expect(Qs.parse('a[b][c][d]=e', { depth: 1 })).to.deep.equal({ a: { b: { '[c][d]': 'e' } } }); + done(); + }); + + it('parses a simple array', function (done) { + + expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses an explicit array', function (done) { + + expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] }); + expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + done(); + }); + + it('parses a mix of simple and explicit arrays', function (done) { + + expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses a nested array', function (done) { + + expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } }); + expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } }); + done(); + }); + + it('allows to specify array indices', function (done) { + + expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] }); + done(); + }); + + it('limits specific array indices to 20', function (done) { + + expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] }); + expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } }); + done(); + }); + + it('supports keys that begin with a number', function (done) { + + expect(Qs.parse('a[12b]=c')).to.deep.equal({ a: { '12b': 'c' } }); + done(); + }); + + it('supports encoded = signs', function (done) { + + expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' }); + done(); + }); + + it('is ok with url encoded strings', function (done) { + + expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } }); + expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } }); + done(); + }); + + it('allows brackets in the value', function (done) { + + expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' }); + expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' }); + done(); + }); + + it('allows empty values', function (done) { + + expect(Qs.parse('')).to.deep.equal({}); + expect(Qs.parse(null)).to.deep.equal({}); + expect(Qs.parse(undefined)).to.deep.equal({}); + done(); + }); + + it('transforms arrays to objects', function (done) { + + expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + expect(Qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c')).to.deep.equal({ a: { '0': 'b', t: 'u', c: true } }); + expect(Qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y')).to.deep.equal({ a: { '0': 'b', '1': 'c', x: 'y' } }); + done(); + }); + + it('transforms arrays to objects (dot notation)', function (done) { + + expect(Qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true })).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true })).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + expect(Qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true })).to.deep.equal({ foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true })).to.deep.equal({ foo: [{ baz: ['15'], bar: '2' }] }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true })).to.deep.equal({ foo: [{ baz: ['15', '16'], bar: '2' }] }); + expect(Qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true })).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true })).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + done(); + }); + + it('can add keys to objects', function (done) { + + expect(Qs.parse('a[b]=c&a=d')).to.deep.equal({ a: { b: 'c', d: true } }); + done(); + }); + + it('correctly prunes undefined values when converting an array to an object', function (done) { + + expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } }); + done(); + }); + + it('supports malformed uri characters', function (done) { + + expect(Qs.parse('{%:%}', { strictNullHandling: true })).to.deep.equal({ '{%:%}': null }); + expect(Qs.parse('{%:%}=')).to.deep.equal({ '{%:%}': '' }); + expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' }); + done(); + }); + + it('doesn\'t produce empty keys', function (done) { + + expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' }); + done(); + }); + + it('cannot access Object prototype', function (done) { + + Qs.parse('constructor[prototype][bad]=bad'); + Qs.parse('bad[constructor][prototype][bad]=bad'); + expect(typeof Object.prototype.bad).to.equal('undefined'); + done(); + }); + + it('parses arrays of objects', function (done) { + + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + done(); + }); + + it('allows for empty strings in arrays', function (done) { + + expect(Qs.parse('a[]=b&a[]=&a[]=c')).to.deep.equal({ a: ['b', '', 'c'] }); + expect(Qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true })).to.deep.equal({ a: ['b', null, 'c', ''] }); + expect(Qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true })).to.deep.equal({ a: ['b', '', 'c', null] }); + expect(Qs.parse('a[]=&a[]=b&a[]=c')).to.deep.equal({ a: ['', 'b', 'c'] }); + done(); + }); + + it('compacts sparse arrays', function (done) { + + expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] }); + done(); + }); + + it('parses semi-parsed strings', function (done) { + + expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } }); + done(); + }); + + it('parses buffers correctly', function (done) { + + var b = new Buffer('test'); + expect(Qs.parse({ a: b })).to.deep.equal({ a: b }); + done(); + }); + + it('continues parsing when no parent is found', function (done) { + + expect(Qs.parse('[]=&a=b')).to.deep.equal({ '0': '', a: 'b' }); + expect(Qs.parse('[]&a=b', { strictNullHandling: true })).to.deep.equal({ '0': null, a: 'b' }); + expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' }); + done(); + }); + + it('does not error when parsing a very long array', function (done) { + + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str += '&' + str; + } + + expect(function () { + + Qs.parse(str); + }).to.not.throw(); + + done(); + }); + + it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) { + + Object.prototype.crash = ''; + Array.prototype.crash = ''; + expect(Qs.parse.bind(null, 'a=b')).to.not.throw(); + expect(Qs.parse('a=b')).to.deep.equal({ a: 'b' }); + expect(Qs.parse.bind(null, 'a[][b]=c')).to.not.throw(); + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + done(); + }); + + it('parses a string with an alternative string delimiter', function (done) { + + expect(Qs.parse('a=b;c=d', { delimiter: ';' })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('parses a string with an alternative RegExp delimiter', function (done) { + + expect(Qs.parse('a=b; c=d', { delimiter: /[;,] */ })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not use non-splittable objects as delimiters', function (done) { + + expect(Qs.parse('a=b&c=d', { delimiter: true })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('allows overriding parameter limit', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: 1 })).to.deep.equal({ a: 'b' }); + done(); + }); + + it('allows setting the parameter limit to Infinity', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: Infinity })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + 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(); + }); + + it('allows disabling array parsing', function (done) { + + expect(Qs.parse('a[0]=b&a[1]=c', { parseArrays: false })).to.deep.equal({ a: { '0': 'b', '1': 'c' } }); + done(); + }); + + it('parses an object', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object in dot notation', function (done) { + + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input, { allowDots: true }); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object and not child values', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': { 'test': 3 } }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': { 'test': 3 } }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('does not blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = Qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + expect(result).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not crash when parsing circular references', function (done) { + + var a = {}; + a.b = a; + + var parsed; + + expect(function () { + + parsed = Qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }).to.not.throw(); + + 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(); + }); + + it('parses plain objects correctly', function (done) { + + var a = Object.create(null); + a.b = 'c'; + + expect(Qs.parse(a)).to.deep.equal({ b: 'c' }); + var result = Qs.parse({ a: a }); + expect(result).to.contain('a'); + expect(result.a).to.deep.equal(a); + done(); + }); + + it('parses dates correctly', function (done) { + + var now = new Date(); + expect(Qs.parse({ a: now })).to.deep.equal({ a: now }); + done(); + }); + + it('parses regular expressions correctly', function (done) { + + var re = /^test$/; + expect(Qs.parse({ a: re })).to.deep.equal({ a: re }); + done(); + }); + + it('can allow overwriting prototype properties', function (done) { + + expect(Qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true })).to.deep.equal({ a: { hasOwnProperty: 'b' } }, { prototype: false }); + expect(Qs.parse('hasOwnProperty=b', { allowPrototypes: true })).to.deep.equal({ hasOwnProperty: 'b' }, { prototype: false }); + done(); + }); + + it('can return plain objects', function (done) { + + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + expect(Qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true })).to.deep.equal(expected); + expect(Qs.parse(null, { plainObjects: true })).to.deep.equal(Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a['0'] = 'b'; + expectedArray.a.c = 'd'; + expect(Qs.parse('a[]=b&a[c]=d', { plainObjects: true })).to.deep.equal(expectedArray); + done(); + }); +}); diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/test/stringify.js b/5-2/service/node_modules/body-parser/node_modules/qs/test/stringify.js new file mode 100644 index 0000000..53139ff --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/test/stringify.js @@ -0,0 +1,293 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('stringify()', function () { + + it('stringifies a querystring object', function (done) { + + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 })).to.equal('a=1'); + expect(Qs.stringify({ a: 1, b: 2 })).to.equal('a=1&b=2'); + expect(Qs.stringify({ a: 'A_Z' })).to.equal('a=A_Z'); + expect(Qs.stringify({ a: '€' })).to.equal('a=%E2%82%AC'); + expect(Qs.stringify({ a: '' })).to.equal('a=%EE%80%80'); + expect(Qs.stringify({ a: 'א' })).to.equal('a=%D7%90'); + expect(Qs.stringify({ a: '𐐷' })).to.equal('a=%F0%90%90%B7'); + done(); + }); + + it('stringifies a nested object', function (done) { + + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + expect(Qs.stringify({ a: { b: { c: { d: 'e' } } } })).to.equal('a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + done(); + }); + + it('stringifies an array value', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d'); + done(); + }); + + it('omits nulls when asked', function (done) { + + expect(Qs.stringify({ a: 'b', c: null }, { skipNulls: true })).to.equal('a=b'); + done(); + }); + + + it('omits nested nulls when asked', function (done) { + + expect(Qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true })).to.equal('a%5Bb%5D=c'); + done(); + }); + + it('omits array indices when asked', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false })).to.equal('a=b&a=c&a=d'); + done(); + }); + + it('stringifies a nested array value', function (done) { + + expect(Qs.stringify({ a: { b: ['c', 'd'] } })).to.equal('a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + done(); + }); + + it('stringifies an object inside an array', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] })).to.equal('a%5B0%5D%5Bb%5D=c'); + expect(Qs.stringify({ a: [{ b: { c: [1] } }] })).to.equal('a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1'); + done(); + }); + + it('does not omit object keys when indices = false', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] }, { indices: false })).to.equal('a%5Bb%5D=c'); + 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'); + done(); + }); + + it('stringifies an empty value', function (done) { + + expect(Qs.stringify({ a: '' })).to.equal('a='); + expect(Qs.stringify({ a: null }, { strictNullHandling: true })).to.equal('a'); + + expect(Qs.stringify({ a: '', b: '' })).to.equal('a=&b='); + expect(Qs.stringify({ a: null, b: '' }, { strictNullHandling: true })).to.equal('a&b='); + + expect(Qs.stringify({ a: { b: '' } })).to.equal('a%5Bb%5D='); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: true })).to.equal('a%5Bb%5D'); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: false })).to.equal('a%5Bb%5D='); + + done(); + }); + + it('stringifies an empty object', function (done) { + + var obj = Object.create(null); + obj.a = 'b'; + expect(Qs.stringify(obj)).to.equal('a=b'); + done(); + }); + + it('returns an empty string for invalid input', function (done) { + + expect(Qs.stringify(undefined)).to.equal(''); + expect(Qs.stringify(false)).to.equal(''); + expect(Qs.stringify(null)).to.equal(''); + expect(Qs.stringify('')).to.equal(''); + done(); + }); + + it('stringifies an object with an empty object as a child', function (done) { + + var obj = { + a: Object.create(null) + }; + + obj.a.b = 'c'; + expect(Qs.stringify(obj)).to.equal('a%5Bb%5D=c'); + done(); + }); + + it('drops keys with a value of undefined', function (done) { + + expect(Qs.stringify({ a: undefined })).to.equal(''); + + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true })).to.equal('a%5Bc%5D'); + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false })).to.equal('a%5Bc%5D='); + expect(Qs.stringify({ a: { b: undefined, c: '' } })).to.equal('a%5Bc%5D='); + done(); + }); + + it('url encodes values', function (done) { + + expect(Qs.stringify({ a: 'b c' })).to.equal('a=b%20c'); + done(); + }); + + it('stringifies a date', function (done) { + + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + expect(Qs.stringify({ a: now })).to.equal(str); + done(); + }); + + it('stringifies the weird object from qs', function (done) { + + expect(Qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' })).to.equal('my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + done(); + }); + + it('skips properties that are part of the object prototype', function (done) { + + Object.prototype.crash = 'test'; + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + delete Object.prototype.crash; + done(); + }); + + it('stringifies boolean values', function (done) { + + expect(Qs.stringify({ a: true })).to.equal('a=true'); + expect(Qs.stringify({ a: { b: true } })).to.equal('a%5Bb%5D=true'); + expect(Qs.stringify({ b: false })).to.equal('b=false'); + expect(Qs.stringify({ b: { c: false } })).to.equal('b%5Bc%5D=false'); + done(); + }); + + it('stringifies buffer values', function (done) { + + expect(Qs.stringify({ a: new Buffer('test') })).to.equal('a=test'); + expect(Qs.stringify({ a: { b: new Buffer('test') } })).to.equal('a%5Bb%5D=test'); + done(); + }); + + it('stringifies an object using an alternative delimiter', function (done) { + + expect(Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' })).to.equal('a=b;c=d'); + done(); + }); + + it('doesn\'t blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = Qs.stringify({ a: 'b', c: 'd' }); + global.Buffer = tempBuffer; + expect(result).to.equal('a=b&c=d'); + done(); + }); + + it('selects properties when filter=array', function (done) { + + expect(Qs.stringify({ a: 'b' }, { filter: ['a'] })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 }, { filter: [] })).to.equal(''); + expect(Qs.stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] })).to.equal('a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3'); + done(); + + }); + + it('supports custom representations when filter=function', function (done) { + + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + + calls++; + if (calls === 1) { + expect(prefix).to.be.empty(); + expect(value).to.equal(obj); + } + else if (prefix === 'c') { + return; + } + else if (value instanceof Date) { + expect(prefix).to.equal('e[f]'); + return value.getTime(); + } + return value; + }; + + expect(Qs.stringify(obj, { filter: filterFunc })).to.equal('a=b&e%5Bf%5D=1257894000000'); + expect(calls).to.equal(5); + done(); + + }); + + it('can disable uri encoding', function (done) { + + expect(Qs.stringify({ a: 'b' }, { encode: false })).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } }, { encode: false })).to.equal('a[b]=c'); + expect(Qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false })).to.equal('a=b&c'); + done(); + }); + + it('can sort the keys', function (done) { + + var sort = function alphabeticalSort (a, b) { + + return a.localeCompare(b); + }; + + expect(Qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort : sort })).to.equal('a=c&b=f&z=y'); + expect(Qs.stringify({ a: 'c', z: { j: 'a', i:'b' }, b : 'f' }, { sort : sort })).to.equal('a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a'); + done(); + }); +}); diff --git a/5-2/service/node_modules/body-parser/node_modules/qs/test/utils.js b/5-2/service/node_modules/body-parser/node_modules/qs/test/utils.js new file mode 100644 index 0000000..a9a6b52 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/qs/test/utils.js @@ -0,0 +1,28 @@ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Utils = require('../lib/utils'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('merge()', function () { + + it('can merge two objects with the same key', function (done) { + + expect(Utils.merge({ a: 'b' }, { a: 'c' })).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); +}); diff --git a/5-2/service/node_modules/body-parser/node_modules/raw-body/HISTORY.md b/5-2/service/node_modules/body-parser/node_modules/raw-body/HISTORY.md new file mode 100644 index 0000000..afca001 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/raw-body/HISTORY.md @@ -0,0 +1,196 @@ +2.1.5 / 2015-11-30 +================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + +2.1.4 / 2015-09-27 +================== + + * Fix masking critical errors from `iconv-lite` + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + +2.1.3 / 2015-09-12 +================== + + * Fix sync callback when attaching data listener causes sync read + - Node.js 0.10 compatibility issue + +2.1.2 / 2015-07-05 +================== + + * Fix error stack traces to skip `makeError` + * deps: iconv-lite@0.4.11 + - Add encoding CESU-8 + +2.1.1 / 2015-06-14 +================== + + * Use `unpipe` module for unpiping requests + +2.1.0 / 2015-05-28 +================== + + * deps: iconv-lite@0.4.10 + - Improved UTF-16 endianness detection + - Leading BOM is now removed when decoding + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + +2.0.2 / 2015-05-21 +================== + + * deps: bytes@2.1.0 + - Slight optimizations + +2.0.1 / 2015-05-10 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + +2.0.0 / 2015-05-08 +================== + + * Return a promise without callback instead of thunk + * deps: bytes@2.0.1 + - units no longer case sensitive when parsing + +1.3.4 / 2015-04-15 +================== + + * Fix hanging callback if request aborts during read + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + +1.3.3 / 2015-02-08 +================== + + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + +1.3.2 / 2015-01-20 +================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + +1.3.1 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + +1.3.0 / 2014-07-20 +================== + + * Fully unpipe the stream on error + - Fixes `Cannot switch to old mode now` error on Node.js 0.10+ + +1.2.3 / 2014-07-20 +================== + + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + +1.2.2 / 2014-06-19 +================== + + * Send invalid encoding error to callback + +1.2.1 / 2014-06-15 +================== + + * deps: iconv-lite@0.4.3 + - Added encodings UTF-16BE and UTF-16 with BOM + +1.2.0 / 2014-06-13 +================== + + * Passing string as `options` interpreted as encoding + * Support all encodings from `iconv-lite` + +1.1.7 / 2014-06-12 +================== + + * use `string_decoder` module from npm + +1.1.6 / 2014-05-27 +================== + + * check encoding for old streams1 + * support node.js < 0.10.6 + +1.1.5 / 2014-05-14 +================== + + * bump bytes + +1.1.4 / 2014-04-19 +================== + + * allow true as an option + * bump bytes + +1.1.3 / 2014-03-02 +================== + + * fix case when length=null + +1.1.2 / 2013-12-01 +================== + + * be less strict on state.encoding check + +1.1.1 / 2013-11-27 +================== + + * add engines + +1.1.0 / 2013-11-27 +================== + + * add err.statusCode and err.type + * allow for encoding option to be true + * pause the stream instead of dumping on error + * throw if the stream's encoding is set + +1.0.1 / 2013-11-19 +================== + + * dont support streams1, throw if dev set encoding + +1.0.0 / 2013-11-17 +================== + + * rename `expected` option to `length` + +0.2.0 / 2013-11-15 +================== + + * republish + +0.1.1 / 2013-11-15 +================== + + * use bytes + +0.1.0 / 2013-11-11 +================== + + * generator support + +0.0.3 / 2013-10-10 +================== + + * update repo + +0.0.2 / 2013-09-14 +================== + + * dump stream on bad headers + * listen to events after defining received and buffers + +0.0.1 / 2013-09-14 +================== + + * Initial release diff --git a/5-2/service/node_modules/body-parser/node_modules/raw-body/LICENSE b/5-2/service/node_modules/body-parser/node_modules/raw-body/LICENSE new file mode 100644 index 0000000..86dc7b9 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/raw-body/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2013-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: + +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/5-2/service/node_modules/body-parser/node_modules/raw-body/README.md b/5-2/service/node_modules/body-parser/node_modules/raw-body/README.md new file mode 100644 index 0000000..c0e972a --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/raw-body/README.md @@ -0,0 +1,126 @@ +# raw-body + +[![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] + +Gets the entire buffer of a stream either as a `Buffer` or a string. +Validates the stream's length against an expected length and maximum limit. +Ideal for parsing request bodies. + +## API + +```js +var getRawBody = require('raw-body') +``` + +### getRawBody(stream, [options], [callback]) + +**Returns a promise if no callback specified and global `Promise` exists.** + +Options: + +- `length` - The length length of the stream. + If the contents of the stream do not add up to this length, + an `400` error code is returned. +- `limit` - The byte limit of the body. + If the body ends up being larger than this limit, + a `413` error code is returned. +- `encoding` - The requested encoding. + By default, a `Buffer` instance will be returned. + Most likely, you want `utf8`. + You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme). + +You can also pass a string in place of options to just specify the encoding. + +`callback(err, res)`: + +- `err` - the following attributes will be defined if applicable: + + - `limit` - the limit in bytes + - `length` and `expected` - the expected length of the stream + - `received` - the received bytes + - `encoding` - the invalid encoding + - `status` and `statusCode` - the corresponding status code for the error + - `type` - either `entity.too.large`, `request.aborted`, `request.size.invalid`, `stream.encoding.set`, or `encoding.unsupported` + +- `res` - the result, either as a `String` if an encoding was set or a `Buffer` otherwise. + +If an error occurs, the stream will be paused, everything unpiped, +and you are responsible for correctly disposing the stream. +For HTTP requests, no handling is required if you send a response. +For streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks. + +## Examples + +### Simple Express example + +```js +var getRawBody = require('raw-body') +var typer = require('media-typer') + +app.use(function (req, res, next) { + getRawBody(req, { + length: req.headers['content-length'], + limit: '1mb', + encoding: typer.parse(req.headers['content-type']).parameters.charset + }, function (err, string) { + if (err) return next(err) + req.text = string + next() + }) +}) +``` + +### Simple Koa example + +```js +app.use(function* (next) { + var string = yield getRawBody(this.req, { + length: this.length, + limit: '1mb', + encoding: this.charset + }) +}) +``` + +### Using as a promise + +To use this library as a promise, simply omit the `callback` and a promise is +returned, provided that a global `Promise` is defined. + +```js +var getRawBody = require('raw-body') +var http = require('http') + +var server = http.createServer(function (req, res) { + getRawBody(req) + .then(function (buf) { + res.statusCode = 200 + res.end(buf.length + ' bytes submitted') + }) + .catch(function (err) { + res.statusCode = 500 + res.end(err.message) + }) +}) + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/raw-body.svg +[npm-url]: https://npmjs.org/package/raw-body +[node-version-image]: https://img.shields.io/node/v/raw-body.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/raw-body/master.svg +[travis-url]: https://travis-ci.org/stream-utils/raw-body +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master +[downloads-image]: https://img.shields.io/npm/dm/raw-body.svg +[downloads-url]: https://npmjs.org/package/raw-body diff --git a/5-2/service/node_modules/body-parser/node_modules/raw-body/index.js b/5-2/service/node_modules/body-parser/node_modules/raw-body/index.js new file mode 100644 index 0000000..e0c85bb --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/raw-body/index.js @@ -0,0 +1,321 @@ +/*! + * raw-body + * Copyright(c) 2013-2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var iconv = require('iconv-lite') +var unpipe = require('unpipe') + +/** + * Module exports. + * @public + */ + +module.exports = getRawBody + +/** + * Module variables. + * @private + */ + +var iconvEncodingMessageRegExp = /^Encoding not recognized: / + +/** + * Get the decoder for a given encoding. + * + * @param {string} encoding + * @private + */ + +function getDecoder(encoding) { + if (!encoding) return null + + try { + return iconv.getDecoder(encoding) + } catch (e) { + // error getting decoder + if (!iconvEncodingMessageRegExp.test(e.message)) throw e + + // the encoding was not found + throw createError(415, 'specified encoding unsupported', 'encoding.unsupported', { + encoding: encoding + }) + } +} + +/** + * Get the raw body of a stream (typically HTTP). + * + * @param {object} stream + * @param {object|string|function} [options] + * @param {function} [callback] + * @public + */ + +function getRawBody(stream, options, callback) { + var done = callback + var opts = options || {} + + if (options === true || typeof options === 'string') { + // short cut for encoding + opts = { + encoding: options + } + } + + if (typeof options === 'function') { + done = options + opts = {} + } + + // validate callback is a function, if provided + if (done !== undefined && typeof done !== 'function') { + throw new TypeError('argument callback must be a function') + } + + // require the callback without promises + if (!done && !global.Promise) { + throw new TypeError('argument callback is required') + } + + // get encoding + var encoding = opts.encoding !== true + ? opts.encoding + : 'utf-8' + + // convert the limit to an integer + var limit = bytes.parse(opts.limit) + + // convert the expected length to an integer + var length = opts.length != null && !isNaN(opts.length) + ? parseInt(opts.length, 10) + : null + + if (done) { + // classic callback style + return readStream(stream, encoding, length, limit, done) + } + + return new Promise(function executor(resolve, reject) { + readStream(stream, encoding, length, limit, function onRead(err, buf) { + if (err) return reject(err) + resolve(buf) + }) + }) +} + +/** + * Halt a stream. + * + * @param {Object} stream + * @private + */ + +function halt(stream) { + // unpipe everything from the stream + unpipe(stream) + + // pause stream + if (typeof stream.pause === 'function') { + stream.pause() + } +} + +/** + * Make a serializable error object. + * + * To create serializable errors you must re-set message so + * that it is enumerable and you must re configure the type + * property so that is writable and enumerable. + * + * @param {number} status + * @param {string} message + * @param {string} type + * @param {object} props + * @private + */ + +function createError(status, message, type, props) { + var error = new Error() + + // capture stack trace + Error.captureStackTrace(error, createError) + + // set free-form properties + for (var prop in props) { + error[prop] = props[prop] + } + + // set message + error.message = message + + // set status + error.status = status + error.statusCode = status + + // set type + Object.defineProperty(error, 'type', { + value: type, + enumerable: true, + writable: true, + configurable: true + }) + + return error +} + +/** + * Read the data from the stream. + * + * @param {object} stream + * @param {string} encoding + * @param {number} length + * @param {number} limit + * @param {function} callback + * @public + */ + +function readStream(stream, encoding, length, limit, callback) { + var complete = false + var sync = true + + // check the length and limit options. + // note: we intentionally leave the stream paused, + // so users should handle the stream themselves. + if (limit !== null && length !== null && length > limit) { + return done(createError(413, 'request entity too large', 'entity.too.large', { + expected: length, + length: length, + limit: limit + })) + } + + // streams1: assert request encoding is buffer. + // streams2+: assert the stream encoding is buffer. + // stream._decoder: streams1 + // state.encoding: streams2 + // state.decoder: streams2, specifically < 0.10.6 + var state = stream._readableState + if (stream._decoder || (state && (state.encoding || state.decoder))) { + // developer error + return done(createError(500, 'stream encoding should not be set', 'stream.encoding.set')) + } + + var received = 0 + var decoder + + try { + decoder = getDecoder(encoding) + } catch (err) { + return done(err) + } + + var buffer = decoder + ? '' + : [] + + // attach listeners + stream.on('aborted', onAborted) + stream.on('close', cleanup) + stream.on('data', onData) + stream.on('end', onEnd) + stream.on('error', onEnd) + + // mark sync section complete + sync = false + + function done() { + var args = new Array(arguments.length) + + // copy arguments + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + // mark complete + complete = true + + if (sync) { + process.nextTick(invokeCallback) + } else { + invokeCallback() + } + + function invokeCallback() { + cleanup() + + if (args[0]) { + // halt the stream on error + halt(stream) + } + + callback.apply(null, args) + } + } + + function onAborted() { + if (complete) return + + done(createError(400, 'request aborted', 'request.aborted', { + code: 'ECONNABORTED', + expected: length, + length: length, + received: received + })) + } + + function onData(chunk) { + if (complete) return + + received += chunk.length + decoder + ? buffer += decoder.write(chunk) + : buffer.push(chunk) + + if (limit !== null && received > limit) { + done(createError(413, 'request entity too large', 'entity.too.large', { + limit: limit, + received: received + })) + } + } + + function onEnd(err) { + if (complete) return + if (err) return done(err) + + if (length !== null && received !== length) { + done(createError(400, 'request size did not match content length', 'request.size.invalid', { + expected: length, + length: length, + received: received + })) + } else { + var string = decoder + ? buffer + (decoder.end() || '') + : Buffer.concat(buffer) + cleanup() + done(null, string) + } + } + + function cleanup() { + buffer = null + + stream.removeListener('aborted', onAborted) + stream.removeListener('data', onData) + stream.removeListener('end', onEnd) + stream.removeListener('error', onEnd) + stream.removeListener('close', cleanup) + } +} diff --git a/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/HISTORY.md b/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/HISTORY.md new file mode 100644 index 0000000..85e0f8d --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/LICENSE b/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/LICENSE new file mode 100644 index 0000000..aed0138 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/README.md b/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/README.md new file mode 100644 index 0000000..e536ad2 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/index.js b/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/index.js new file mode 100644 index 0000000..15c3d97 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/package.json b/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/package.json new file mode 100644 index 0000000..5381079 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/package.json @@ -0,0 +1,59 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/unpipe.git" + }, + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "d2df901c06487430e78dca62b6edb8bb2fc5e99d", + "bugs": { + "url": "https://github.com/stream-utils/unpipe/issues" + }, + "homepage": "https://github.com/stream-utils/unpipe", + "_id": "unpipe@1.0.0", + "_shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "_from": "unpipe@1.0.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "tarball": "http://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/raw-body/package.json b/5-2/service/node_modules/body-parser/node_modules/raw-body/package.json new file mode 100644 index 0000000..dc97a1a --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/raw-body/package.json @@ -0,0 +1,81 @@ +{ + "name": "raw-body", + "description": "Get and validate the raw body of a readable stream.", + "version": "2.1.5", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Raynos", + "email": "raynos2@gmail.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/raw-body.git" + }, + "dependencies": { + "bytes": "2.2.0", + "iconv-lite": "0.4.13", + "unpipe": "1.0.0" + }, + "devDependencies": { + "bluebird": "3.0.5", + "istanbul": "0.4.1", + "mocha": "2.3.4", + "readable-stream": "2.0.4", + "through2": "2.0.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "mocha --trace-deprecation --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --trace-deprecation --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --trace-deprecation --reporter spec --check-leaks test/" + }, + "gitHead": "0467d63d4e66c212ec08bfc826ba565be15c523a", + "bugs": { + "url": "https://github.com/stream-utils/raw-body/issues" + }, + "homepage": "https://github.com/stream-utils/raw-body", + "_id": "raw-body@2.1.5", + "_shasum": "8be8f09ddefd0d72ad99d883ab7f0cc350420956", + "_from": "raw-body@>=2.1.5 <2.2.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" + } + ], + "dist": { + "shasum": "8be8f09ddefd0d72ad99d883ab7f0cc350420956", + "tarball": "http://registry.npmjs.org/raw-body/-/raw-body-2.1.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.1.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/HISTORY.md b/5-2/service/node_modules/body-parser/node_modules/type-is/HISTORY.md new file mode 100644 index 0000000..e10b426 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/HISTORY.md @@ -0,0 +1,192 @@ +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/LICENSE b/5-2/service/node_modules/body-parser/node_modules/type-is/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +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: + +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/5-2/service/node_modules/body-parser/node_modules/type-is/README.md b/5-2/service/node_modules/body-parser/node_modules/type-is/README.md new file mode 100644 index 0000000..7a754be --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/README.md @@ -0,0 +1,136 @@ +# type-is + +[![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] + +Infer the content-type of a request. + +### Install + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var is = require('type-is') + +http.createServer(function (req, res) { + var istext = is(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### type = is(request, types) + +`request` is the node HTTP request. `types` is an array of types. + +```js +// req.headers.content-type = 'application/json' + +is(req, ['json']) // 'json' +is(req, ['html', 'json']) // 'json' +is(req, ['application/*']) // 'application/json' +is(req, ['application/json']) // 'application/json' + +is(req, ['html']) // false +``` + +### is.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existance works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + +```js +if (is.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### type = is.is(mediaType, types) + +`mediaType` is the [media type](https://tools.ietf.org/html/rfc6838) string. `types` is an array of types. + +```js +var mediaType = 'application/json' + +is.is(mediaType, ['json']) // 'json' +is.is(mediaType, ['html', 'json']) // 'json' +is.is(mediaType, ['application/*']) // 'application/json' +is.is(mediaType, ['application/json']) // 'application/json' + +is.is(mediaType, ['html']) // false +``` + +### Each type can be: + +- An extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` 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 or the content type is invalid. + +`null` will be returned if the request does not have a body. + +## Examples + +#### Example body parser + +```js +var is = require('type-is'); + +function bodyParser(req, res, next) { + if (!is.hasBody(req)) { + return next() + } + + switch (is(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + break + case 'json': + // parse json body + throw new Error('implement json body parsing') + break + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + break + default: + // 415 error code + res.statusCode = 415 + res.end() + return + } +} +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: https://nodejs.org/en/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[downloads-image]: https://img.shields.io/npm/dm/type-is.svg +[downloads-url]: https://npmjs.org/package/type-is diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/index.js b/5-2/service/node_modules/body-parser/node_modules/type-is/index.js new file mode 100644 index 0000000..ca2962e --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/index.js @@ -0,0 +1,262 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var typer = require('media-typer') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis(value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody(req) { + return req.headers['transfer-encoding'] !== undefined + || !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +function typeofrequest(req, types_) { + var types = types_ + + // no body + if (!hasbody(req)) { + return null + } + + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @private + */ + +function normalize(type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @private + */ + +function mimeMatch(expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // 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) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +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 { + return normalizeType(value) + } catch (err) { + return null + } +} diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/HISTORY.md b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/HISTORY.md new file mode 100644 index 0000000..62c2003 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/HISTORY.md @@ -0,0 +1,22 @@ +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/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/LICENSE b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/README.md b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/README.md new file mode 100644 index 0000000..d8df623 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/README.md @@ -0,0 +1,81 @@ +# 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/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/index.js b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/index.js new file mode 100644 index 0000000..07f7295 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/index.js @@ -0,0 +1,270 @@ +/*! + * 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/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/package.json b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/package.json new file mode 100644 index 0000000..e0f796d --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/package.json @@ -0,0 +1,58 @@ +{ + "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": "git+https://github.com/jshttp/media-typer.git" + }, + "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/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/HISTORY.md b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..61b54b4 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/HISTORY.md @@ -0,0 +1,183 @@ +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +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 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/LICENSE b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/README.md b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/README.md new file mode 100644 index 0000000..e26295d --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/README.md @@ -0,0 +1,103 @@ +# mime-types + +[![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] + +The ultimate javascript content-type utility. + +Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, + so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db) +- No `.define()` functionality + +Otherwise, the API is compatible. + +## Install + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://github.com/jshttp/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[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/node/v/mime-types.svg +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/index.js b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/index.js new file mode 100644 index 0000000..f7008b2 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/index.js @@ -0,0 +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 + +/** + * 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) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..41a667a --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -0,0 +1,306 @@ +1.21.0 / 2016-01-06 +=================== + + * Add `application/emergencycalldata.comment+xml` + * Add `application/emergencycalldata.deviceinfo+xml` + * Add `application/emergencycalldata.providerinfo+xml` + * Add `application/emergencycalldata.serviceinfo+xml` + * Add `application/emergencycalldata.subscriberinfo+xml` + * Add `application/vnd.filmit.zfc` + * Add `application/vnd.google-apps.document` + * Add `application/vnd.google-apps.presentation` + * Add `application/vnd.google-apps.spreadsheet` + * Add `application/vnd.mapbox-vector-tile` + * Add `application/vnd.ms-printdevicecapabilities+xml` + * Add `application/vnd.ms-windows.devicepairing` + * Add `application/vnd.ms-windows.nwprinting.oob` + * Add `application/vnd.tml` + * Add `audio/evs` + +1.20.0 / 2015-11-10 +=================== + + * Add `application/cdni` + * Add `application/csvm+json` + * Add `application/rfc+xml` + * Add `application/vnd.3gpp.access-transfer-events+xml` + * Add `application/vnd.3gpp.srvcc-ext+xml` + * Add `application/vnd.ms-windows.wsd.oob` + * Add `application/vnd.oxli.countgraph` + * Add `application/vnd.pagerduty+json` + * Add `text/x-suse-ymp` + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.3gpp-prose-pc3ch+xml` + * Add `application/vnd.3gpp.srvcc-info+xml` + * Add `application/vnd.apple.pkpass` + * Add `application/vnd.drive+json` + +1.18.0 / 2015-09-03 +=================== + + * Add `application/pkcs12` + * Add `application/vnd.3gpp-prose+xml` + * Add `application/vnd.3gpp.mid-call+xml` + * Add `application/vnd.3gpp.state-and-event-info+xml` + * Add `application/vnd.anki` + * Add `application/vnd.firemonkeys.cloudcell` + * Add `application/vnd.openblox.game+xml` + * Add `application/vnd.openblox.game-binary` + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +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 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md new file mode 100644 index 0000000..7662440 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md @@ -0,0 +1,82 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +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 + +```bash +npm install mime-db +``` + +### 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 +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + 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 can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +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 +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[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 +[node-url]: http://nodejs.org/download/ diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json new file mode 100644 index 0000000..412ba9e --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json @@ -0,0 +1,6552 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana" + }, + "application/3gpp-ims+xml": { + "source": "iana" + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana" + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana" + }, + "application/bacnet-xdd+zip": { + "source": "iana" + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana" + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana" + }, + "application/ccxml+xml": { + "source": "iana", + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana" + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana" + }, + "application/cellml+xml": { + "source": "iana" + }, + "application/cfw": { + "source": "iana" + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana" + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana" + }, + "application/cstadata+xml": { + "source": "iana" + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "extensions": ["mdp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana" + }, + "application/dicom": { + "source": "iana" + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana" + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/emergencycalldata.comment+xml": { + "source": "iana" + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana" + }, + "application/emma+xml": { + "source": "iana", + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana" + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana" + }, + "application/epub+zip": { + "source": "iana", + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana" + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false, + "extensions": ["woff"] + }, + "application/font-woff2": { + "compressible": false, + "extensions": ["woff2"] + }, + "application/framework-attributes+xml": { + "source": "iana" + }, + "application/gml+xml": { + "source": "apache", + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana" + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana" + }, + "application/ibe-pkg-reply+xml": { + "source": "iana" + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana" + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana" + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana" + }, + "application/kpml-response+xml": { + "source": "iana" + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana" + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana" + }, + "application/mathml-presentation+xml": { + "source": "iana" + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana" + }, + "application/mbms-deregister+xml": { + "source": "iana" + }, + "application/mbms-envelope+xml": { + "source": "iana" + }, + "application/mbms-msk+xml": { + "source": "iana" + }, + "application/mbms-msk-response+xml": { + "source": "iana" + }, + "application/mbms-protection-description+xml": { + "source": "iana" + }, + "application/mbms-reception-report+xml": { + "source": "iana" + }, + "application/mbms-register+xml": { + "source": "iana" + }, + "application/mbms-register-response+xml": { + "source": "iana" + }, + "application/mbms-schedule+xml": { + "source": "iana" + }, + "application/mbms-user-service-description+xml": { + "source": "iana" + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana" + }, + "application/media_control+xml": { + "source": "iana" + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mods+xml": { + "source": "iana", + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana" + }, + "application/mrb-publish+xml": { + "source": "iana" + }, + "application/msc-ivr+xml": { + "source": "iana" + }, + "application/msc-mixer+xml": { + "source": "iana" + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "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", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana" + }, + "application/parityfec": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana" + }, + "application/pidf-diff+xml": { + "source": "iana" + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana" + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/provenance+xml": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana" + }, + "application/pskc+xml": { + "source": "iana", + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf"] + }, + "application/reginfo+xml": { + "source": "iana", + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana" + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana" + }, + "application/rls-services+xml": { + "source": "iana", + "extensions": ["rs"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana" + }, + "application/samlmetadata+xml": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana" + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/sep+xml": { + "source": "iana" + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana" + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana" + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "extensions": ["ssml"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/ttml+xml": { + "source": "iana" + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana" + }, + "application/urc-ressheet+xml": { + "source": "iana" + }, + "application/urc-targetdesc+xml": { + "source": "iana" + }, + "application/urc-uisocketdesc+xml": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana" + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana" + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana" + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana" + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "extensions": ["mpkg"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avistar+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "extensions": ["cdxml"] + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana" + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana" + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana" + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume-movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana" + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana" + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana" + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana" + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana" + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana" + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana" + }, + "application/vnd.etsi.cug+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana" + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana" + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana" + }, + "application/vnd.etsi.sci+xml": { + "source": "iana" + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana" + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana" + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana" + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana" + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana" + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana" + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana" + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana" + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana" + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+xml": { + "source": "iana", + "extensions": ["lasxml"] + }, + "application/vnd.liberty-request+xml": { + "source": "iana" + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana" + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana" + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana" + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache" + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana" + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana" + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana" + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana" + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana" + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana" + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana" + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana" + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana" + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana" + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana" + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana" + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana" + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana" + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana" + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana" + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana" + }, + "application/vnd.omads-email+xml": { + "source": "iana" + }, + "application/vnd.omads-file+xml": { + "source": "iana" + }, + "application/vnd.omads-folder+xml": { + "source": "iana" + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana" + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "apache", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "apache", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "apache", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana" + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana" + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos+xml": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "apache" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana" + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana" + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana" + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana" + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana" + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana" + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana" + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana" + }, + "application/vnd.wv.ssp+xml": { + "source": "iana" + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana" + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "extensions": ["vxml"] + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/watcherinfo+xml": { + "source": "iana" + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-otf": { + "source": "apache", + "compressible": true, + "extensions": ["otf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-ttf": { + "source": "apache", + "compressible": true, + "extensions": ["ttf","ttc"] + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "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, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "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, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana" + }, + "application/xaml+xml": { + "source": "apache", + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana" + }, + "application/xcap-caps+xml": { + "source": "iana" + }, + "application/xcap-diff+xml": { + "source": "iana", + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana" + }, + "application/xcap-error+xml": { + "source": "iana" + }, + "application/xcap-ns+xml": { + "source": "iana" + }, + "application/xcon-conference-info+xml": { + "source": "iana" + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana" + }, + "application/xenc+xml": { + "source": "iana", + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache" + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana" + }, + "application/xmpp+xml": { + "source": "iana" + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yin+xml": { + "source": "iana", + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana" + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4a","m4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/opentype": { + "compressible": true, + "extensions": ["otf"] + }, + "image/bmp": { + "source": "apache", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/fits": { + "source": "iana" + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jp2": { + "source": "iana" + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana" + }, + "image/jpx": { + "source": "iana" + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana" + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana" + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tiff","tif"] + }, + "image/tiff-fx": { + "source": "iana" + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana" + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana" + }, + "image/vnd.valve.source.texture": { + "source": "iana" + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "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"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana" + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana" + }, + "message/global-delivery-status": { + "source": "iana" + }, + "message/global-disposition-notification": { + "source": "iana" + }, + "message/global-headers": { + "source": "iana" + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana" + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana" + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hjson": { + "extensions": ["hjson"] + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana" + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["markdown","md","mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "apache" + }, + "video/3gpp": { + "source": "apache", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "apache" + }, + "video/3gpp2": { + "source": "apache", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "apache" + }, + "video/bt656": { + "source": "apache" + }, + "video/celb": { + "source": "apache" + }, + "video/dv": { + "source": "apache" + }, + "video/h261": { + "source": "apache", + "extensions": ["h261"] + }, + "video/h263": { + "source": "apache", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "apache" + }, + "video/h263-2000": { + "source": "apache" + }, + "video/h264": { + "source": "apache", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "apache" + }, + "video/h264-svc": { + "source": "apache" + }, + "video/jpeg": { + "source": "apache", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "apache" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "apache", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "apache" + }, + "video/mp2p": { + "source": "apache" + }, + "video/mp2t": { + "source": "apache", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "apache", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "apache" + }, + "video/mpeg": { + "source": "apache", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "apache" + }, + "video/mpv": { + "source": "apache" + }, + "video/nv": { + "source": "apache" + }, + "video/ogg": { + "source": "apache", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "apache" + }, + "video/pointer": { + "source": "apache" + }, + "video/quicktime": { + "source": "apache", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raw": { + "source": "apache" + }, + "video/rtp-enc-aescm128": { + "source": "apache" + }, + "video/rtx": { + "source": "apache" + }, + "video/smpte292m": { + "source": "apache" + }, + "video/ulpfec": { + "source": "apache" + }, + "video/vc1": { + "source": "apache" + }, + "video/vnd.cctv": { + "source": "apache" + }, + "video/vnd.dece.hd": { + "source": "apache", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "apache", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "apache" + }, + "video/vnd.dece.pd": { + "source": "apache", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "apache", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "apache", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "apache" + }, + "video/vnd.directv.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dvb.file": { + "source": "apache", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "apache", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "apache" + }, + "video/vnd.motorola.video": { + "source": "apache" + }, + "video/vnd.motorola.videop": { + "source": "apache" + }, + "video/vnd.mpegurl": { + "source": "apache", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "apache", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "apache" + }, + "video/vnd.nokia.videovoip": { + "source": "apache" + }, + "video/vnd.objectvideo": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "apache" + }, + "video/vnd.sealed.mpeg4": { + "source": "apache" + }, + "video/vnd.sealed.swf": { + "source": "apache" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "apache" + }, + "video/vnd.uvvu.mp4": { + "source": "apache", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "apache", + "extensions": ["viv"] + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json new file mode 100644 index 0000000..e6c9732 --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json @@ -0,0 +1,94 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.21.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "devDependencies": { + "bluebird": "3.1.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "1.0.1", + "gnode": "0.1.1", + "istanbul": "0.4.1", + "mocha": "1.21.5", + "raw-body": "2.1.5", + "stream-to-array": "2.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "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": "9ab92f0a912a602408a64db5741dfef6f82c597f", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "homepage": "https://github.com/jshttp/mime-db", + "_id": "mime-db@1.21.0", + "_shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "_from": "mime-db@>=1.21.0 <1.22.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" + } + ], + "dist": { + "shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/package.json b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/package.json new file mode 100644 index 0000000..2e4d38a --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/package.json @@ -0,0 +1,84 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "dependencies": { + "mime-db": "~1.21.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec test/test.js", + "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": "329f1c77e1a77c8fac59b15038e3808e9e314d96", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "homepage": "https://github.com/jshttp/mime-types", + "_id": "mime-types@2.1.9", + "_shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "_from": "mime-types@>=2.1.9 <2.2.0", + "_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" + } + ], + "dist": { + "shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/node_modules/type-is/package.json b/5-2/service/node_modules/body-parser/node_modules/type-is/package.json new file mode 100644 index 0000000..26b6fae --- /dev/null +++ b/5-2/service/node_modules/body-parser/node_modules/type-is/package.json @@ -0,0 +1,81 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "1.6.11", + "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": "git+https://github.com/jshttp/type-is.git" + }, + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.9" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "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/" + }, + "keywords": [ + "content", + "type", + "checking" + ], + "gitHead": "8e60e3e78aef84928e0e6c09da950f6950adcdd2", + "bugs": { + "url": "https://github.com/jshttp/type-is/issues" + }, + "homepage": "https://github.com/jshttp/type-is", + "_id": "type-is@1.6.11", + "_shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "_from": "type-is@>=1.6.6 <1.7.0", + "_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": "ritch", + "email": "skawful@gmail.com" + } + ], + "dist": { + "shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "tarball": "http://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/body-parser/package.json b/5-2/service/node_modules/body-parser/package.json new file mode 100644 index 0000000..799c41e --- /dev/null +++ b/5-2/service/node_modules/body-parser/package.json @@ -0,0 +1,98 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "1.14.2", + "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/expressjs/body-parser" + }, + "dependencies": { + "bytes": "2.2.0", + "content-type": "~1.0.1", + "debug": "~2.2.0", + "depd": "~1.1.0", + "http-errors": "~1.3.1", + "iconv-lite": "0.4.13", + "on-finished": "~2.3.0", + "qs": "5.2.0", + "raw-body": "~2.1.5", + "type-is": "~1.6.10" + }, + "devDependencies": { + "istanbul": "0.4.1", + "methods": "~1.1.1", + "mocha": "2.3.4", + "supertest": "1.1.0" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/" + }, + "gitHead": "ef5d85d8344f08b21f70a7d90082e7eea3ccdf99", + "bugs": { + "url": "https://github.com/expressjs/body-parser/issues" + }, + "homepage": "https://github.com/expressjs/body-parser", + "_id": "body-parser@1.14.2", + "_shasum": "1015cb1fe2c443858259581db53332f8d0cf50f9", + "_from": "body-parser@*", + "_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": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "1015cb1fe2c443858259581db53332f8d0cf50f9", + "tarball": "http://registry.npmjs.org/body-parser/-/body-parser-1.14.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.14.2.tgz" +} diff --git a/5-2/service/node_modules/express/History.md b/5-2/service/node_modules/express/History.md new file mode 100644 index 0000000..c72241b --- /dev/null +++ b/5-2/service/node_modules/express/History.md @@ -0,0 +1,3062 @@ +4.13.4 / 2016-01-21 +=================== + + * deps: content-disposition@0.5.1 + - perf: enable strict mode + * deps: cookie@0.1.5 + - Throw on invalid values provided to `serialize` + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: finalhandler@0.4.1 + - deps: escape-html@~1.0.3 + * deps: merge-descriptors@1.0.1 + - perf: enable strict mode + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + * deps: proxy-addr@~1.0.10 + - deps: ipaddr.js@1.0.5 + - perf: enable strict mode + * deps: range-parser@~1.0.3 + - perf: enable strict mode + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + * deps: serve-static@~1.10.2 + - deps: escape-html@~1.0.3 + - deps: parseurl@~1.3.0 + - deps: send@0.13.1 + +4.13.3 / 2015-08-02 +=================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + +4.13.2 / 2015-07-31 +=================== + + * deps: accepts@~1.2.12 + - deps: mime-types@~2.1.4 + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +4.13.1 / 2015-07-05 +=================== + + * deps: accepts@~1.2.10 + - deps: mime-types@~2.1.2 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +4.13.0 / 2015-06-20 +=================== + + * Add settings to debug output + * Fix `res.format` error when only `default` provided + * Fix issue where `next('route')` in `app.param` would incorrectly skip values + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * Simplify `res.cookie` to call `res.append` + * Use `array-flatten` module for flattening arrays + * deps: accepts@~1.2.9 + - deps: mime-types@~2.1.1 + - perf: avoid argument reassignment & argument slice + - perf: avoid negotiator recursive construction + - perf: enable strict mode + - perf: remove unnecessary bitwise operator + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: finalhandler@0.4.0 + - Fix a false-positive when unpiping in Node.js 0.8 + - Support `statusCode` property on `Error` objects + - Use `unpipe` module for unpiping requests + - deps: escape-html@1.0.2 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: path-to-regexp@0.1.6 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * deps: serve-static@~1.10.0 + - Add `fallthrough` option + - Fix reading options from options prototype + - Improve the default redirect response headers + - Malformed URLs now `next()` instead of 400 + - deps: escape-html@1.0.2 + - deps: send@0.13.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: isolate `app.render` try block + * perf: remove argument reassignments in application + * perf: remove argument reassignments in request prototype + * perf: remove argument reassignments in response prototype + * perf: remove argument reassignments in routing + * perf: remove argument reassignments in `View` + * perf: skip attempting to decode zero length string + * perf: use saved reference to `http.STATUS_CODES` + +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 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * 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 + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * 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 + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw un-catchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.21.2 / 2015-07-31 +=================== + + * deps: connect@2.30.2 + - deps: body-parser@~1.13.3 + - deps: compression@~1.5.2 + - deps: errorhandler@~1.4.2 + - deps: method-override@~2.3.5 + - deps: serve-index@~1.7.2 + - deps: type-is@~1.6.6 + - deps: vhost@~3.0.1 + * deps: vary@~1.0.1 + - Fix setting empty header from empty `field` + - perf: enable strict mode + - perf: remove argument reassignments + +3.21.1 / 2015-07-05 +=================== + + * deps: basic-auth@~1.0.3 + * deps: connect@2.30.1 + - deps: body-parser@~1.13.2 + - deps: compression@~1.5.1 + - deps: errorhandler@~1.4.1 + - deps: morgan@~1.6.1 + - deps: pause@0.1.0 + - deps: qs@4.0.0 + - deps: serve-index@~1.7.1 + - deps: type-is@~1.6.4 + +3.21.0 / 2015-06-18 +=================== + + * deps: basic-auth@1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: connect@2.30.0 + - deps: body-parser@~1.13.1 + - deps: bytes@2.1.0 + - deps: compression@~1.5.0 + - deps: cookie@0.1.3 + - deps: cookie-parser@~1.3.5 + - deps: csurf@~1.8.3 + - deps: errorhandler@~1.4.0 + - deps: express-session@~1.11.3 + - deps: finalhandler@0.4.0 + - deps: fresh@0.3.0 + - deps: morgan@~1.6.0 + - deps: serve-favicon@~2.3.0 + - deps: serve-index@~1.7.0 + - deps: serve-static@~1.10.0 + - deps: type-is@~1.6.3 + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: mkdirp@0.5.1 + - Work in global strict mode + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + +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 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * 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 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes charset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Closes #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delimited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using using charset utf-8 + * Fixed show-exceptions page, now using using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie complation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'. + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error response support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independent specs for those who cant build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/LICENSE b/5-2/service/node_modules/express/LICENSE new file mode 100644 index 0000000..aa927e4 --- /dev/null +++ b/5-2/service/node_modules/express/LICENSE @@ -0,0 +1,24 @@ +(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 +'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/5-2/service/node_modules/express/Readme.md b/5-2/service/node_modules/express/Readme.md new file mode 100644 index 0000000..6e08454 --- /dev/null +++ b/5-2/service/node_modules/express/Readme.md @@ -0,0 +1,138 @@ +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) + + Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). + + [![NPM Version][npm-image]][npm-url] + [![NPM Downloads][downloads-image]][downloads-url] + [![Linux Build][travis-image]][travis-url] + [![Windows Build][appveyor-image]][appveyor-url] + [![Test Coverage][coveralls-image]][coveralls-url] + +```js +var express = require('express') +var app = express() + +app.get('/', function (req, res) { + res.send('Hello World') +}) + +app.listen(3000) +``` + +## Installation + +```bash +$ npm install express +``` + +## Features + + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly + +## Docs & Community + + * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC + * [Github Organization](https://github.com/expressjs) for Official Middleware & Modules + * [Google Group](https://groups.google.com/group/express-js) for discussion + * [Gitter](https://gitter.im/expressjs/express) for support and discussion + * [Русскоязычная документация](http://jsman.ru/express/) + +###Security Issues + +If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). + +## Quick Start + + 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: + + Install the executable. The executable's major version will match Express's: + +```bash +$ npm install -g express-generator@4 +``` + + Create the app: + +```bash +$ express /tmp/foo && cd /tmp/foo +``` + + Install dependencies: + +```bash +$ npm install +``` + + Start the server: + +```bash +$ npm start +``` + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, web sites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), + you can quickly craft your perfect framework. + +## Examples + + To view the examples, clone the Express repo and install the dependencies: + +```bash +$ git clone git://github.com/expressjs/express.git --depth 1 +$ cd express +$ npm install +``` + + Then run whichever example you want: + +```bash +$ node examples/content-negotiation +``` + +## Tests + + To run the test suite, first install the dependencies, then run `npm test`: + +```bash +$ npm install +$ npm test +``` + +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) [![TJ's Gratipay][gratipay-image-visionmedia]][gratipay-url-visionmedia] + +The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) [![Doug's Gratipay][gratipay-image-dougwilson]][gratipay-url-dougwilson] + +[List of all contributors](https://github.com/expressjs/express/graphs/contributors) + +## License + + [MIT](LICENSE) + +[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 +[downloads-url]: https://npmjs.org/package/express +[travis-image]: https://img.shields.io/travis/expressjs/express/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/express +[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/expressjs/express/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master +[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 +[gratipay-url-dougwilson]: https://gratipay.com/dougwilson/ diff --git a/5-2/service/node_modules/express/index.js b/5-2/service/node_modules/express/index.js new file mode 100644 index 0000000..d219b0c --- /dev/null +++ b/5-2/service/node_modules/express/index.js @@ -0,0 +1,11 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +module.exports = require('./lib/express'); diff --git a/5-2/service/node_modules/express/lib/application.js b/5-2/service/node_modules/express/lib/application.js new file mode 100644 index 0000000..0ee4def --- /dev/null +++ b/5-2/service/node_modules/express/lib/application.js @@ -0,0 +1,643 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var finalhandler = require('finalhandler'); +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var merge = require('utils-merge'); +var resolve = require('path').resolve; +var slice = Array.prototype.slice; + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Variable for trust proxy inheritance back-compat + * @private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ + +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; + + this.defaultConfiguration(); +}; + +/** + * Initialize application configuration. + * @private + */ + +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + 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); + + 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; + this.settings.__proto__ = parent.settings; + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; + +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ + +app.handle = function handle(req, res, callback) { + var router = this._router; + + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ + +app.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires middleware functions'); + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + req.__proto__ = orig.request; + res.__proto__ = orig.response; + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } + + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; + + // store engine + this.engines[extension] = fn; + + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.param = function param(name, fn) { + this.lazyrouter(); + + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } + + return this; + } + + this._router.param(name, fn); + + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge app.locals + merge(renderOptions, this.locals); + + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } + + // merge options + merge(renderOptions, opts); + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} diff --git a/5-2/service/node_modules/express/lib/express.js b/5-2/service/node_modules/express/lib/express.js new file mode 100644 index 0000000..540c8be --- /dev/null +++ b/5-2/service/node_modules/express/lib/express.js @@ -0,0 +1,103 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + app.request = { __proto__: req, app: app }; + app.response = { __proto__: res, app: app }; + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.query = require('./middleware/query'); +exports.static = require('serve-static'); + +/** + * Replace removed middleware with an appropriate error message. + */ + +[ + 'json', + 'urlencoded', + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache', +].forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/5-2/service/node_modules/express/lib/middleware/init.js b/5-2/service/node_modules/express/lib/middleware/init.js new file mode 100644 index 0000000..f3119ed --- /dev/null +++ b/5-2/service/node_modules/express/lib/middleware/init.js @@ -0,0 +1,36 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ + +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; + + req.__proto__ = app.request; + res.__proto__ = app.response; + + res.locals = res.locals || Object.create(null); + + next(); + }; +}; + diff --git a/5-2/service/node_modules/express/lib/middleware/query.js b/5-2/service/node_modules/express/lib/middleware/query.js new file mode 100644 index 0000000..a665f3f --- /dev/null +++ b/5-2/service/node_modules/express/lib/middleware/query.js @@ -0,0 +1,51 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var parseUrl = require('parseurl'); +var qs = require('qs'); + +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = Object.create(options || null); + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + + if (opts !== undefined) { + if (opts.allowDots === undefined) { + opts.allowDots = false; + } + + if (opts.allowPrototypes === undefined) { + opts.allowPrototypes = true; + } + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; diff --git a/5-2/service/node_modules/express/lib/request.js b/5-2/service/node_modules/express/lib/request.js new file mode 100644 index 0000000..33cac18 --- /dev/null +++ b/5-2/service/node_modules/express/lib/request.js @@ -0,0 +1,489 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + */ + +var req = exports = module.exports = { + __proto__: http.IncomingMessage.prototype +}; + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ + +req.get = +req.header = function header(name) { + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", 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. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + +/** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param {Number} size + * @return {Array} + * @public + */ + +req.range = function(size){ + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ + +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; +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + proto = this.get('X-Forwarded-Proto') || proto; + return proto.split(/\s*,\s*/)[0]; +}); + +/** + * Short-hand for: + * + * req.protocol == 'https' + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + return addrs.slice(1).reverse(); +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +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, 0)) { + host = this.get('Host'); + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var s = this.res.statusCode; + + // GET or HEAD for weak freshness validation only + if ('GET' != method && 'HEAD' != method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((s >= 200 && s < 300) || 304 == s) { + return fresh(this.headers, (this.res._headers || {})); + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +}; diff --git a/5-2/service/node_modules/express/lib/response.js b/5-2/service/node_modules/express/lib/response.js new file mode 100644 index 0000000..641704b --- /dev/null +++ b/5-2/service/node_modules/express/lib/response.js @@ -0,0 +1,1053 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var contentDisposition = require('content-disposition'); +var deprecate = require('depd')('express'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var isAbsolute = require('./utils').isAbsolute; +var onFinished = require('on-finished'); +var path = require('path'); +var merge = require('utils-merge'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var statusCodes = http.STATUS_CODES; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = require('vary'); + +/** + * Response prototype. + */ + +var res = module.exports = { + __proto__: http.ServerResponse.prototype +}; + +/** + * Module variables. + * @private + */ + +var charsetRegExp = /;\s*charset\s*=/; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ + +res.status = function status(code) { + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ + +res.send = function send(body) { + var chunk = body; + var encoding; + var len; + var req = this.req; + var type; + + // settings + var app = this.app; + + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } + } + + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statusCodes[chunk]; + } + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + + // populate Content-Length + if (chunk !== undefined) { + if (!Buffer.isBuffer(chunk)) { + // convert chunk to Buffer; saves later double conversions + chunk = new Buffer(chunk, encoding); + encoding = undefined; + } + + len = chunk.length; + this.set('Content-Length', len); + } + + // 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); + } + } + + // freshness + if (req.fresh) this.statusCode = 304; + + // strip irrelevant headers + if (204 == this.statusCode || 304 == this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.json = function json(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = JSON.stringify(val, replacer, spaces); + + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.jsonp = function jsonp(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = JSON.stringify(val, replacer, spaces); + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.charset = 'utf-8'; + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = statusCodes[statusCode] || String(statusCode); + + this.statusCode = statusCode; + this.type('txt'); + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } + + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // create file stream + var file = send(req, path, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') { + next(err); + } + }); +}; + +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + * + * @public + */ + +res.download = function download(path, filename, callback) { + var done = callback; + var name = filename; + + // support function as second arg + if (typeof filename === 'function') { + done = filename; + name = null; + } + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // Resolve the full path for sendFile + var fullPath = resolve(path); + + return this.sendFile(fullPath, { headers: headers }, done); +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ + +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + + return this.set('Content-Type', ct); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

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

hey

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

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

'; + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ + +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } + + vary(this, field); + + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// 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() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + 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; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} diff --git a/5-2/service/node_modules/express/lib/router/index.js b/5-2/service/node_modules/express/lib/router/index.js new file mode 100644 index 0000000..504ed9c --- /dev/null +++ b/5-2/service/node_modules/express/lib/router/index.js @@ -0,0 +1,645 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Route = require('./route'); +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 flatten = require('array-flatten'); +var parseUrl = require('parseurl'); + +/** + * Module variables. + * @private + */ + +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} options + * @return {Router} which is an callable function + * @public + */ + +var proto = module.exports = function(options) { + var opts = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + router.__proto__ = proto; + + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; + + return router; +}; + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } + + // apply param functions + var params = this._params; + var len = params.length; + 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); + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } + + // ensure we end up with a + // middleware function + if ('function' != typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; + +/** + * Dispatch a req, res into the router. + * @private + */ + +proto.handle = function handle(req, res, out) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var search = 1 + req.url.indexOf('?'); + var pathlength = search ? search - 1 : req.url.length; + var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://'); + var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''; + var idx = 0; + var removed = ''; + var slashAdded = false; + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } + + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; + + // 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 = ''; + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } + + // 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); + } + + if (route) { + return layer.handle_request(req, res, next); + } + + trim_prefix(layer, layerError, layerPath, path); + }); + } + + function trim_prefix(layer, layerError, layerPath, path) { + var c = path[layerPath.length]; + if (c && '/' !== c && '.' !== c) return next(layerError); + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + if (layerPath.length !== 0) { + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); + + // Ensure leading slash + if (!fqdn && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Process any parameters for the layer. + * @private + */ + +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; + + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); + } + + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } + + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + + if (!key) { + return done(); + } + + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; + + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; + + // next param + return param(paramCalled.error); + } + + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } + + param(); +}; + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +proto.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var callbacks = flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires middleware functions'); + } + + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; + + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn)); + } + + // add the middleware + debug('use %s %s', path, fn.name || ''); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + } + + return this; +}; + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public + */ + +proto.route = function route(path) { + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; +}; + +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +// 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; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(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) { + return params; + } + + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } + + var i = 0; + var o = 0; + + // determine numeric gaps + while (i in params) { + i++; + } + + while (o in parent) { + o++; + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } + + return mixin(obj, params); +} + +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); + + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + + return function(err){ + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; +} + +// 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() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} diff --git a/5-2/service/node_modules/express/lib/router/layer.js b/5-2/service/node_modules/express/lib/router/layer.js new file mode 100644 index 0000000..fe9210c --- /dev/null +++ b/5-2/service/node_modules/express/lib/router/layer.js @@ -0,0 +1,176 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var pathRegexp = require('path-to-regexp'); +var debug = require('debug')('express:router:layer'); + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Module exports. + * @public + */ + +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %s', path); + var opts = options || {}; + + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); + + if (path === '/' && opts.end === false) { + this.regexp.fast_slash = true; + } +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; + + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } + + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); + } + + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match(path) { + if (path == null) { + // no path, nothing matches + this.params = undefined; + this.path = undefined; + return false; + } + + if (this.regexp.fast_slash) { + // fast path non-ending match for / (everything matches) + this.params = {}; + this.path = ''; + return true; + } + + var m = this.regexp.exec(path); + + if (!m) { + this.params = undefined; + this.path = undefined; + return false; + } + + // store values + this.params = {}; + this.path = m[0]; + + var keys = this.keys; + var params = this.params; + + for (var i = 1; i < m.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(m[i]); + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } + + return true; +}; + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } + + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } + + throw err; + } +} diff --git a/5-2/service/node_modules/express/lib/router/route.js b/5-2/service/node_modules/express/lib/router/route.js new file mode 100644 index 0000000..2788d7b --- /dev/null +++ b/5-2/service/node_modules/express/lib/router/route.js @@ -0,0 +1,210 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:router:route'); +var flatten = require('array-flatten'); +var Layer = require('./layer'); +var methods = require('methods'); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Module exports. + * @public + */ + +module.exports = Route; + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ + +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %s', path); + + // route handlers for various http methods + this.methods = {}; +} + +/** + * Determine if the route handles a given method. + * @private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } + + var name = method.toLowerCase(); + + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } + + return Boolean(this.methods[name]); +}; + +/** + * @return {Array} supported HTTP methods + * @private + */ + +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; +}; + +/** + * dispatch req, res into this route + * @private + */ + +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); + } + + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = this; + + next(); + + function next(err) { + if (err && err === 'route') { + return done(); + } + + var layer = stack[idx++]; + if (!layer) { + return done(err); + } + + if (layer.method && layer.method !== method) { + return next(err); + } + + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires callback functions but got a ' + type; + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); + } + + return this; +}; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires callback functions but got a ' + type; + throw new Error(msg); + } + + debug('%s %s', method, this.path); + + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + } + + return this; + }; +}); diff --git a/5-2/service/node_modules/express/lib/utils.js b/5-2/service/node_modules/express/lib/utils.js new file mode 100644 index 0000000..3d54247 --- /dev/null +++ b/5-2/service/node_modules/express/lib/utils.js @@ -0,0 +1,300 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @api private + */ + +var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var mime = require('send').mime; +var basename = require('path').basename; +var etag = require('etag'); +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); + +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = function (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? new Buffer(body, encoding) + : body; + + return etag(buf, {weak: false}); +}; + +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = function wetag(body, encoding){ + var buf = !Buffer.isBuffer(body) + ? new Buffer(body, encoding) + : body; + + return etag(buf, {weak: true}); +}; + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +exports.isAbsolute = function(path){ + if ('/' == path[0]) return true; + if (':' == path[1] && '\\' == path[2]) return true; + if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; + +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' == pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowDots: false, + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} diff --git a/5-2/service/node_modules/express/lib/view.js b/5-2/service/node_modules/express/lib/view.js new file mode 100644 index 0000000..52415d4 --- /dev/null +++ b/5-2/service/node_modules/express/lib/view.js @@ -0,0 +1,173 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:view'); +var path = require('path'); +var fs = require('fs'); +var utils = require('./utils'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ + +function View(name, options) { + var opts = options || {}; + + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; + } + + if (!opts.engines[this.ext]) { + // load engine + opts.engines[this.ext] = require(this.ext.substr(1)).__express; + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); + + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/5-2/service/node_modules/express/node_modules/accepts/HISTORY.md b/5-2/service/node_modules/express/node_modules/accepts/HISTORY.md new file mode 100644 index 0000000..397636e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/HISTORY.md @@ -0,0 +1,170 @@ +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +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 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/5-2/service/node_modules/express/node_modules/accepts/LICENSE b/5-2/service/node_modules/express/node_modules/accepts/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-2/service/node_modules/express/node_modules/accepts/README.md b/5-2/service/node_modules/express/node_modules/accepts/README.md new file mode 100644 index 0000000..ae36676 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/README.md @@ -0,0 +1,135 @@ +# accepts + +[![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] + +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 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 `*` + +## Installation + +```sh +npm install accepts +``` + +## API + +```js +var accepts = require('accepts') +``` + +### 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) +``` + +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 +[npm-url]: https://npmjs.org/package/accepts +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/accepts +[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 +[downloads-url]: https://npmjs.org/package/accepts diff --git a/5-2/service/node_modules/express/node_modules/accepts/index.js b/5-2/service/node_modules/express/node_modules/accepts/index.js new file mode 100644 index 0000000..e80192a --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/index.js @@ -0,0 +1,231 @@ +/*! + * 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') + +/** + * 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 = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +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 = this.negotiator.mediaTypes(mimes.filter(validMime)); + var first = accepts[0]; + if (!first) return false; + return types[mimes.indexOf(first)]; +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +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 +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +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 +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +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 +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime(type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ + +function validMime(type) { + return typeof type === 'string'; +} diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..61b54b4 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md @@ -0,0 +1,183 @@ +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +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 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md new file mode 100644 index 0000000..e26295d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md @@ -0,0 +1,103 @@ +# mime-types + +[![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] + +The ultimate javascript content-type utility. + +Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, + so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db) +- No `.define()` functionality + +Otherwise, the API is compatible. + +## Install + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://github.com/jshttp/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[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/node/v/mime-types.svg +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js new file mode 100644 index 0000000..f7008b2 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js @@ -0,0 +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 + +/** + * 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) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..41a667a --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -0,0 +1,306 @@ +1.21.0 / 2016-01-06 +=================== + + * Add `application/emergencycalldata.comment+xml` + * Add `application/emergencycalldata.deviceinfo+xml` + * Add `application/emergencycalldata.providerinfo+xml` + * Add `application/emergencycalldata.serviceinfo+xml` + * Add `application/emergencycalldata.subscriberinfo+xml` + * Add `application/vnd.filmit.zfc` + * Add `application/vnd.google-apps.document` + * Add `application/vnd.google-apps.presentation` + * Add `application/vnd.google-apps.spreadsheet` + * Add `application/vnd.mapbox-vector-tile` + * Add `application/vnd.ms-printdevicecapabilities+xml` + * Add `application/vnd.ms-windows.devicepairing` + * Add `application/vnd.ms-windows.nwprinting.oob` + * Add `application/vnd.tml` + * Add `audio/evs` + +1.20.0 / 2015-11-10 +=================== + + * Add `application/cdni` + * Add `application/csvm+json` + * Add `application/rfc+xml` + * Add `application/vnd.3gpp.access-transfer-events+xml` + * Add `application/vnd.3gpp.srvcc-ext+xml` + * Add `application/vnd.ms-windows.wsd.oob` + * Add `application/vnd.oxli.countgraph` + * Add `application/vnd.pagerduty+json` + * Add `text/x-suse-ymp` + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.3gpp-prose-pc3ch+xml` + * Add `application/vnd.3gpp.srvcc-info+xml` + * Add `application/vnd.apple.pkpass` + * Add `application/vnd.drive+json` + +1.18.0 / 2015-09-03 +=================== + + * Add `application/pkcs12` + * Add `application/vnd.3gpp-prose+xml` + * Add `application/vnd.3gpp.mid-call+xml` + * Add `application/vnd.3gpp.state-and-event-info+xml` + * Add `application/vnd.anki` + * Add `application/vnd.firemonkeys.cloudcell` + * Add `application/vnd.openblox.game+xml` + * Add `application/vnd.openblox.game-binary` + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +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 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md new file mode 100644 index 0000000..7662440 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md @@ -0,0 +1,82 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +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 + +```bash +npm install mime-db +``` + +### 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 +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + 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 can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +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 +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[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 +[node-url]: http://nodejs.org/download/ diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json new file mode 100644 index 0000000..412ba9e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json @@ -0,0 +1,6552 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana" + }, + "application/3gpp-ims+xml": { + "source": "iana" + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana" + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana" + }, + "application/bacnet-xdd+zip": { + "source": "iana" + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana" + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana" + }, + "application/ccxml+xml": { + "source": "iana", + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana" + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana" + }, + "application/cellml+xml": { + "source": "iana" + }, + "application/cfw": { + "source": "iana" + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana" + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana" + }, + "application/cstadata+xml": { + "source": "iana" + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "extensions": ["mdp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana" + }, + "application/dicom": { + "source": "iana" + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana" + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/emergencycalldata.comment+xml": { + "source": "iana" + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana" + }, + "application/emma+xml": { + "source": "iana", + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana" + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana" + }, + "application/epub+zip": { + "source": "iana", + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana" + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false, + "extensions": ["woff"] + }, + "application/font-woff2": { + "compressible": false, + "extensions": ["woff2"] + }, + "application/framework-attributes+xml": { + "source": "iana" + }, + "application/gml+xml": { + "source": "apache", + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana" + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana" + }, + "application/ibe-pkg-reply+xml": { + "source": "iana" + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana" + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana" + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana" + }, + "application/kpml-response+xml": { + "source": "iana" + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana" + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana" + }, + "application/mathml-presentation+xml": { + "source": "iana" + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana" + }, + "application/mbms-deregister+xml": { + "source": "iana" + }, + "application/mbms-envelope+xml": { + "source": "iana" + }, + "application/mbms-msk+xml": { + "source": "iana" + }, + "application/mbms-msk-response+xml": { + "source": "iana" + }, + "application/mbms-protection-description+xml": { + "source": "iana" + }, + "application/mbms-reception-report+xml": { + "source": "iana" + }, + "application/mbms-register+xml": { + "source": "iana" + }, + "application/mbms-register-response+xml": { + "source": "iana" + }, + "application/mbms-schedule+xml": { + "source": "iana" + }, + "application/mbms-user-service-description+xml": { + "source": "iana" + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana" + }, + "application/media_control+xml": { + "source": "iana" + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mods+xml": { + "source": "iana", + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana" + }, + "application/mrb-publish+xml": { + "source": "iana" + }, + "application/msc-ivr+xml": { + "source": "iana" + }, + "application/msc-mixer+xml": { + "source": "iana" + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "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", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana" + }, + "application/parityfec": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana" + }, + "application/pidf-diff+xml": { + "source": "iana" + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana" + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/provenance+xml": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana" + }, + "application/pskc+xml": { + "source": "iana", + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf"] + }, + "application/reginfo+xml": { + "source": "iana", + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana" + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana" + }, + "application/rls-services+xml": { + "source": "iana", + "extensions": ["rs"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana" + }, + "application/samlmetadata+xml": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana" + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/sep+xml": { + "source": "iana" + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana" + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana" + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "extensions": ["ssml"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/ttml+xml": { + "source": "iana" + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana" + }, + "application/urc-ressheet+xml": { + "source": "iana" + }, + "application/urc-targetdesc+xml": { + "source": "iana" + }, + "application/urc-uisocketdesc+xml": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana" + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana" + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana" + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana" + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "extensions": ["mpkg"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avistar+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "extensions": ["cdxml"] + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana" + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana" + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana" + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume-movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana" + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana" + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana" + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana" + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana" + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana" + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana" + }, + "application/vnd.etsi.cug+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana" + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana" + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana" + }, + "application/vnd.etsi.sci+xml": { + "source": "iana" + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana" + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana" + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana" + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana" + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana" + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana" + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana" + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana" + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana" + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+xml": { + "source": "iana", + "extensions": ["lasxml"] + }, + "application/vnd.liberty-request+xml": { + "source": "iana" + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana" + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana" + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana" + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache" + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana" + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana" + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana" + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana" + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana" + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana" + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana" + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana" + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana" + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana" + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana" + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana" + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana" + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana" + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana" + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana" + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana" + }, + "application/vnd.omads-email+xml": { + "source": "iana" + }, + "application/vnd.omads-file+xml": { + "source": "iana" + }, + "application/vnd.omads-folder+xml": { + "source": "iana" + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana" + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "apache", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "apache", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "apache", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana" + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana" + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos+xml": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "apache" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana" + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana" + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana" + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana" + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana" + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana" + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana" + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana" + }, + "application/vnd.wv.ssp+xml": { + "source": "iana" + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana" + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "extensions": ["vxml"] + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/watcherinfo+xml": { + "source": "iana" + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-otf": { + "source": "apache", + "compressible": true, + "extensions": ["otf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-ttf": { + "source": "apache", + "compressible": true, + "extensions": ["ttf","ttc"] + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "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, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "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, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana" + }, + "application/xaml+xml": { + "source": "apache", + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana" + }, + "application/xcap-caps+xml": { + "source": "iana" + }, + "application/xcap-diff+xml": { + "source": "iana", + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana" + }, + "application/xcap-error+xml": { + "source": "iana" + }, + "application/xcap-ns+xml": { + "source": "iana" + }, + "application/xcon-conference-info+xml": { + "source": "iana" + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana" + }, + "application/xenc+xml": { + "source": "iana", + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache" + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana" + }, + "application/xmpp+xml": { + "source": "iana" + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yin+xml": { + "source": "iana", + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana" + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4a","m4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/opentype": { + "compressible": true, + "extensions": ["otf"] + }, + "image/bmp": { + "source": "apache", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/fits": { + "source": "iana" + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jp2": { + "source": "iana" + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana" + }, + "image/jpx": { + "source": "iana" + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana" + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana" + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tiff","tif"] + }, + "image/tiff-fx": { + "source": "iana" + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana" + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana" + }, + "image/vnd.valve.source.texture": { + "source": "iana" + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "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"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana" + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana" + }, + "message/global-delivery-status": { + "source": "iana" + }, + "message/global-disposition-notification": { + "source": "iana" + }, + "message/global-headers": { + "source": "iana" + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana" + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana" + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hjson": { + "extensions": ["hjson"] + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana" + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["markdown","md","mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "apache" + }, + "video/3gpp": { + "source": "apache", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "apache" + }, + "video/3gpp2": { + "source": "apache", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "apache" + }, + "video/bt656": { + "source": "apache" + }, + "video/celb": { + "source": "apache" + }, + "video/dv": { + "source": "apache" + }, + "video/h261": { + "source": "apache", + "extensions": ["h261"] + }, + "video/h263": { + "source": "apache", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "apache" + }, + "video/h263-2000": { + "source": "apache" + }, + "video/h264": { + "source": "apache", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "apache" + }, + "video/h264-svc": { + "source": "apache" + }, + "video/jpeg": { + "source": "apache", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "apache" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "apache", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "apache" + }, + "video/mp2p": { + "source": "apache" + }, + "video/mp2t": { + "source": "apache", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "apache", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "apache" + }, + "video/mpeg": { + "source": "apache", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "apache" + }, + "video/mpv": { + "source": "apache" + }, + "video/nv": { + "source": "apache" + }, + "video/ogg": { + "source": "apache", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "apache" + }, + "video/pointer": { + "source": "apache" + }, + "video/quicktime": { + "source": "apache", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raw": { + "source": "apache" + }, + "video/rtp-enc-aescm128": { + "source": "apache" + }, + "video/rtx": { + "source": "apache" + }, + "video/smpte292m": { + "source": "apache" + }, + "video/ulpfec": { + "source": "apache" + }, + "video/vc1": { + "source": "apache" + }, + "video/vnd.cctv": { + "source": "apache" + }, + "video/vnd.dece.hd": { + "source": "apache", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "apache", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "apache" + }, + "video/vnd.dece.pd": { + "source": "apache", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "apache", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "apache", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "apache" + }, + "video/vnd.directv.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dvb.file": { + "source": "apache", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "apache", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "apache" + }, + "video/vnd.motorola.video": { + "source": "apache" + }, + "video/vnd.motorola.videop": { + "source": "apache" + }, + "video/vnd.mpegurl": { + "source": "apache", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "apache", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "apache" + }, + "video/vnd.nokia.videovoip": { + "source": "apache" + }, + "video/vnd.objectvideo": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "apache" + }, + "video/vnd.sealed.mpeg4": { + "source": "apache" + }, + "video/vnd.sealed.swf": { + "source": "apache" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "apache" + }, + "video/vnd.uvvu.mp4": { + "source": "apache", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "apache", + "extensions": ["viv"] + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json new file mode 100644 index 0000000..e6c9732 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json @@ -0,0 +1,94 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.21.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "devDependencies": { + "bluebird": "3.1.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "1.0.1", + "gnode": "0.1.1", + "istanbul": "0.4.1", + "mocha": "1.21.5", + "raw-body": "2.1.5", + "stream-to-array": "2.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "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": "9ab92f0a912a602408a64db5741dfef6f82c597f", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "homepage": "https://github.com/jshttp/mime-db", + "_id": "mime-db@1.21.0", + "_shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "_from": "mime-db@>=1.21.0 <1.22.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" + } + ], + "dist": { + "shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json new file mode 100644 index 0000000..2e4d38a --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json @@ -0,0 +1,84 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "dependencies": { + "mime-db": "~1.21.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec test/test.js", + "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": "329f1c77e1a77c8fac59b15038e3808e9e314d96", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "homepage": "https://github.com/jshttp/mime-types", + "_id": "mime-types@2.1.9", + "_shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "_from": "mime-types@>=2.1.9 <2.2.0", + "_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" + } + ], + "dist": { + "shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md new file mode 100644 index 0000000..aa2a7c4 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md @@ -0,0 +1,76 @@ +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE new file mode 100644 index 0000000..ea6b9e2 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +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 +'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/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md new file mode 100644 index 0000000..ef507fa --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md @@ -0,0 +1,203 @@ +# negotiator + +[![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] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +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 + +```js +negotiator = new Negotiator(request) + +availableLanguages = 'en', 'es', 'fr' + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +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 + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +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 + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +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 +[npm-url]: https://npmjs.org/package/negotiator +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/negotiator +[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 +[downloads-url]: https://npmjs.org/package/negotiator diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js new file mode 100644 index 0000000..edae9cf --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js @@ -0,0 +1,62 @@ + +var preferredCharsets = require('./lib/charset'); +var preferredEncodings = require('./lib/encoding'); +var preferredLanguages = require('./lib/language'); +var preferredMediaTypes = require('./lib/mediaType'); + +module.exports = Negotiator; +Negotiator.Negotiator = Negotiator; + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available) { + var set = this.encodings(available); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available) { + return preferredEncodings(this.request.headers['accept-encoding'], available); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; diff --git a/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js new file mode 100644 index 0000000..7abd17c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js @@ -0,0 +1,102 @@ +module.exports = preferredCharsets; +preferredCharsets.preferredCharsets = preferredCharsets; + +function parseAcceptCharset(accept) { + 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) { + var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +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; + } + } + + return priority; +} + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + 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/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js new file mode 100644 index 0000000..7fed673 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,118 @@ +module.exports = preferredEncodings; +preferredEncodings.preferredEncodings = preferredEncodings; + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + 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 (!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 + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +function parseEncoding(s, i) { + var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); + + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +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; + } + } + + return priority; +} + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +function preferredEncodings(accept, provided) { + 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/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js new file mode 100644 index 0000000..ed9e1ec --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js @@ -0,0 +1,112 @@ +module.exports = preferredLanguages; +preferredLanguages.preferredLanguages = preferredLanguages; + +function parseAcceptLanguage(accept) { + 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) { + var match = s.match(/^\s*(\S+?)(?:-(\S+?))?\s*(?:;(.*))?$/); + if (!match) return null; + + var prefix = match[1], + suffix = match[2], + full = prefix; + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +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; + } + } + + return priority; +} + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + 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/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 0000000..4170c25 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,179 @@ +/** + * 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) { + 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) { + var match = s.match(/\s*(\S+?)\/([^;\s]+)\s*(?:;(.*))?/); + if (!match) return null; + + var type = match[1], + subtype = match[2], + full = "" + type + "/" + subtype, + params = {}, + q = 1; + + if (match[3]) { + params = match[3].split(';').map(function(s) { + return s.trim().split('='); + }).reduce(function (set, p) { + 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) { + q = parseFloat(params.q); + delete params.q; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i, + full: full + }; +} + +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; + } + } + + return priority; +} + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } + +} + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + 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/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json new file mode 100644 index 0000000..66d2824 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json @@ -0,0 +1,86 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "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/" + } + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/negotiator.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "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": "cbb717b3f164f25820f90b160cda6d0166b9d922", + "bugs": { + "url": "https://github.com/jshttp/negotiator/issues" + }, + "homepage": "https://github.com/jshttp/negotiator", + "_id": "negotiator@0.5.3", + "_shasum": "269d5c476810ec92edbe7b6c2f28316384f9a7e8", + "_from": "negotiator@0.5.3", + "_npmVersion": "1.4.28", + "_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": "269d5c476810ec92edbe7b6c2f28316384f9a7e8", + "tarball": "http://registry.npmjs.org/negotiator/-/negotiator-0.5.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.5.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/accepts/package.json b/5-2/service/node_modules/express/node_modules/accepts/package.json new file mode 100644 index 0000000..6455e64 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/accepts/package.json @@ -0,0 +1,98 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "1.2.13", + "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": "git+https://github.com/jshttp/accepts.git" + }, + "dependencies": { + "mime-types": "~2.1.6", + "negotiator": "0.5.3" + }, + "devDependencies": { + "istanbul": "0.3.19", + "mocha": "~1.21.5" + }, + "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/" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ], + "gitHead": "b7e15ecb25dacc0b2133ed0553d64f8a79537e01", + "bugs": { + "url": "https://github.com/jshttp/accepts/issues" + }, + "homepage": "https://github.com/jshttp/accepts", + "_id": "accepts@1.2.13", + "_shasum": "e5f1f3928c6d95fd96558c36ec3d9d0de4a6ecea", + "_from": "accepts@>=1.2.12 <1.3.0", + "_npmVersion": "1.4.28", + "_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": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "e5f1f3928c6d95fd96558c36ec3d9d0de4a6ecea", + "tarball": "http://registry.npmjs.org/accepts/-/accepts-1.2.13.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.2.13.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/array-flatten/LICENSE b/5-2/service/node_modules/express/node_modules/array-flatten/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/array-flatten/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/5-2/service/node_modules/express/node_modules/array-flatten/README.md b/5-2/service/node_modules/express/node_modules/array-flatten/README.md new file mode 100644 index 0000000..91fa5b6 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/array-flatten/README.md @@ -0,0 +1,43 @@ +# Array Flatten + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +> Flatten an array of nested arrays into a single flat array. Accepts an optional depth. + +## Installation + +``` +npm install array-flatten --save +``` + +## Usage + +```javascript +var flatten = require('array-flatten') + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) +//=> [1, 2, 3, 4, 5, 6, 7, 8, 9] + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) +//=> [1, 2, 3, [4, [5], 6], 7, 8, 9] + +(function () { + flatten(arguments) //=> [1, 2, 3] +})(1, [2, 3]) +``` + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat +[npm-url]: https://npmjs.org/package/array-flatten +[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat +[downloads-url]: https://npmjs.org/package/array-flatten +[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat +[travis-url]: https://travis-ci.org/blakeembrey/array-flatten +[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat +[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master diff --git a/5-2/service/node_modules/express/node_modules/array-flatten/array-flatten.js b/5-2/service/node_modules/express/node_modules/array-flatten/array-flatten.js new file mode 100644 index 0000000..089117b --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/array-flatten/array-flatten.js @@ -0,0 +1,64 @@ +'use strict' + +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result +} + +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result +} + +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) +} diff --git a/5-2/service/node_modules/express/node_modules/array-flatten/package.json b/5-2/service/node_modules/express/node_modules/array-flatten/package.json new file mode 100644 index 0000000..f80f937 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/array-flatten/package.json @@ -0,0 +1,62 @@ +{ + "name": "array-flatten", + "version": "1.1.1", + "description": "Flatten an array of nested arrays into a single flat array", + "main": "array-flatten.js", + "files": [ + "array-flatten.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/blakeembrey/array-flatten.git" + }, + "keywords": [ + "array", + "flatten", + "arguments", + "depth" + ], + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/blakeembrey/array-flatten/issues" + }, + "homepage": "https://github.com/blakeembrey/array-flatten", + "devDependencies": { + "istanbul": "^0.3.13", + "mocha": "^2.2.4", + "pre-commit": "^1.0.7", + "standard": "^3.7.3" + }, + "gitHead": "1963a9189229d408e1e8f585a00c8be9edbd1803", + "_id": "array-flatten@1.1.1", + "_shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2", + "_from": "array-flatten@1.1.1", + "_npmVersion": "2.11.3", + "_nodeVersion": "2.3.3", + "_npmUser": { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + }, + "maintainers": [ + { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + } + ], + "dist": { + "shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2", + "tarball": "http://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/content-disposition/HISTORY.md b/5-2/service/node_modules/express/node_modules/content-disposition/HISTORY.md new file mode 100644 index 0000000..76d494c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/content-disposition/HISTORY.md @@ -0,0 +1,45 @@ +0.5.1 / 2016-01-17 +================== + + * perf: enable strict mode + +0.5.0 / 2014-10-11 +================== + + * Add `parse` function + +0.4.0 / 2014-09-21 +================== + + * Expand non-Unicode `filename` to the full ISO-8859-1 charset + +0.3.0 / 2014-09-20 +================== + + * Add `fallback` option + * Add `type` option + +0.2.0 / 2014-09-19 +================== + + * Reduce ambiguity of file names with hex escape in buggy browsers + +0.1.2 / 2014-09-19 +================== + + * Fix periodic invalid Unicode filename header + +0.1.1 / 2014-09-19 +================== + + * Fix invalid characters appearing in `filename*` parameter + +0.1.0 / 2014-09-18 +================== + + * Make the `filename` argument optional + +0.0.0 / 2014-09-18 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/content-disposition/LICENSE b/5-2/service/node_modules/express/node_modules/content-disposition/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/content-disposition/README.md b/5-2/service/node_modules/express/node_modules/content-disposition/README.md new file mode 100644 index 0000000..5cebce4 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/content-disposition/README.md @@ -0,0 +1,141 @@ +# content-disposition + +[![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] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + +```js +var contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + +```js +var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'); +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +var contentDisposition = require('content-disposition') +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +var filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest(req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + var stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://tools.ietf.org/html/rfc2616 +[rfc-5987]: https://tools.ietf.org/html/rfc5987 +[rfc-6266]: https://tools.ietf.org/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition.svg?style=flat +[npm-url]: https://npmjs.org/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/content-disposition +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg?style=flat +[downloads-url]: https://npmjs.org/package/content-disposition diff --git a/5-2/service/node_modules/express/node_modules/content-disposition/index.js b/5-2/service/node_modules/express/node_modules/content-disposition/index.js new file mode 100644 index 0000000..4a352dc --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/content-disposition/index.js @@ -0,0 +1,445 @@ +/*! + * content-disposition + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * Module dependencies. + */ + +var basename = require('path').basename + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + */ + +var encodeUriAttrCharRegExp = /[\x00-\x20"'\(\)*,\/:;<=>?@\[\\\]\{\}\x7f]/g + +/** + * RegExp to match percent encoding escape. + */ + +var hexEscapeRegExp = /%[0-9A-Fa-f]{2}/ +var hexEscapeReplaceRegExp = /%([0-9A-Fa-f]{2})/g + +/** + * RegExp to match non-latin1 characters. + */ + +var nonLatin1RegExp = /[^\x20-\x7e\xa0-\xff]/g + +/** + * 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 for various RFC 2616 grammar + * + * 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 = + * HT = + * CTL = + * OCTET = + */ + +var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g +var textRegExp = /^[\x20-\x7e\x80-\xff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + */ + +var extValueRegExp = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+\-\.^_`|~])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + */ + +var dispositionTypeRegExp = /^([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *(?:$|;)/ + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @api public + */ + +function contentDisposition(filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @api private + */ + +function createparams(filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && nonLatin1RegExp.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = textRegExp.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || hexEscapeRegExp.test(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @api private + */ + +function format(obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !tokenRegExp.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // 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] + + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 6987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @api private + */ + +function decodefield(str) { + var match = extValueRegExp.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + + // to binary string + var binary = encoded.replace(hexEscapeReplaceRegExp, pdecode) + + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = new Buffer(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @api private + */ + +function getlatin1(val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(nonLatin1RegExp, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @api private + */ + +function parse(string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = dispositionTypeRegExp.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = paramRegExp.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + 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 (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + 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') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @api private + */ + +function pdecode(str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @api private + */ + +function pencode(char) { + var hex = String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() + return hex.length === 1 + ? '%0' + hex + : '%' + hex +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @api private + */ + +function qstring(val) { + var str = String(val) + + return '"' + str.replace(quoteRegExp, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @api private + */ + +function ustring(val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(encodeUriAttrCharRegExp, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + */ + +function ContentDisposition(type, parameters) { + this.type = type + this.parameters = parameters +} diff --git a/5-2/service/node_modules/express/node_modules/content-disposition/package.json b/5-2/service/node_modules/express/node_modules/content-disposition/package.json new file mode 100644 index 0000000..1b22eb9 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/content-disposition/package.json @@ -0,0 +1,66 @@ +{ + "name": "content-disposition", + "description": "Create and parse Content-Disposition header", + "version": "0.5.1", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-disposition.git" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "7b391db3af5629d4c698f1de21802940bb9f22a5", + "bugs": { + "url": "https://github.com/jshttp/content-disposition/issues" + }, + "homepage": "https://github.com/jshttp/content-disposition", + "_id": "content-disposition@0.5.1", + "_shasum": "87476c6a67c8daa87e32e87616df883ba7fb071b", + "_from": "content-disposition@0.5.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "87476c6a67c8daa87e32e87616df883ba7fb071b", + "tarball": "http://registry.npmjs.org/content-disposition/-/content-disposition-0.5.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/content-type/HISTORY.md b/5-2/service/node_modules/express/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..8a623a2 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/content-type/HISTORY.md @@ -0,0 +1,9 @@ +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/5-2/service/node_modules/express/node_modules/content-type/LICENSE b/5-2/service/node_modules/express/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/5-2/service/node_modules/express/node_modules/content-type/README.md b/5-2/service/node_modules/express/node_modules/content-type/README.md new file mode 100644 index 0000000..3ed6741 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/content-type/README.md @@ -0,0 +1,92 @@ +# content-type + +[![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] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a content 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 media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({type: 'image/svg+xml'}) +``` + +Format an object into a content type string. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-type.svg +[npm-url]: https://npmjs.org/package/content-type +[node-version-image]: https://img.shields.io/node/v/content-type.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg +[travis-url]: https://travis-ci.org/jshttp/content-type +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-type +[downloads-image]: https://img.shields.io/npm/dm/content-type.svg +[downloads-url]: https://npmjs.org/package/content-type diff --git a/5-2/service/node_modules/express/node_modules/content-type/index.js b/5-2/service/node_modules/express/node_modules/content-type/index.js new file mode 100644 index 0000000..6a2ea9f --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/content-type/index.js @@ -0,0 +1,214 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) */g +var textRegExp = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var qescRegExp = /\\([\u000b\u0020-\u00ff])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var quoteRegExp = /([\\"])/g + +/** + * RegExp to match type in RFC 6838 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+\/[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !typeRegExp.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // 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} + * @public + */ + +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string === 'object') { + // support req/res-like objects as argument + string = getcontenttype(string) + + if (typeof string !== 'string') { + throw new TypeError('content-type header is missing from object'); + } + } + + 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).trim() + : string.trim() + + if (!typeRegExp.test(type)) { + throw new TypeError('invalid media type') + } + + var key + var match + var obj = new ContentType(type.toLowerCase()) + 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') + } + + obj.parameters[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @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} + * @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') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType(type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/5-2/service/node_modules/express/node_modules/content-type/package.json b/5-2/service/node_modules/express/node_modules/content-type/package.json new file mode 100644 index 0000000..e23403c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/content-type/package.json @@ -0,0 +1,65 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-type.git" + }, + "devDependencies": { + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail 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": "3aa58f9c5a358a3634b8601602177888b4a477d8", + "bugs": { + "url": "https://github.com/jshttp/content-type/issues" + }, + "homepage": "https://github.com/jshttp/content-type", + "_id": "content-type@1.0.1", + "_shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "_from": "content-type@>=1.0.1 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "tarball": "http://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/cookie-signature/.npmignore b/5-2/service/node_modules/express/node_modules/cookie-signature/.npmignore new file mode 100644 index 0000000..f1250e5 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/cookie-signature/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/5-2/service/node_modules/express/node_modules/cookie-signature/History.md b/5-2/service/node_modules/express/node_modules/cookie-signature/History.md new file mode 100644 index 0000000..78513cc --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/cookie-signature/History.md @@ -0,0 +1,38 @@ +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 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/cookie-signature/Readme.md b/5-2/service/node_modules/express/node_modules/cookie-signature/Readme.md new file mode 100644 index 0000000..2559e84 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/cookie-signature/Readme.md @@ -0,0 +1,42 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +(The MIT License) + +Copyright (c) 2012 LearnBoost <tj@learnboost.com> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/5-2/service/node_modules/express/node_modules/cookie-signature/index.js b/5-2/service/node_modules/express/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..b8c9463 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/cookie-signature/index.js @@ -0,0 +1,51 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie 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) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("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); + + return sha1(mac) == sha1(val) ? str : false; +}; + +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} diff --git a/5-2/service/node_modules/express/node_modules/cookie-signature/package.json b/5-2/service/node_modules/express/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..28f87d0 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/cookie-signature/package.json @@ -0,0 +1,59 @@ +{ + "name": "cookie-signature", + "version": "1.0.6", + "description": "Sign and unsign cookies", + "keywords": [ + "cookie", + "sign", + "unsign" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@learnboost.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/visionmedia/node-cookie-signature.git" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, + "main": "index", + "gitHead": "391b56cf44d88c493491b7e3fc53208cfb976d2a", + "bugs": { + "url": "https://github.com/visionmedia/node-cookie-signature/issues" + }, + "homepage": "https://github.com/visionmedia/node-cookie-signature", + "_id": "cookie-signature@1.0.6", + "_shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c", + "_from": "cookie-signature@1.0.6", + "_npmVersion": "2.3.0", + "_nodeVersion": "0.10.36", + "_npmUser": { + "name": "natevw", + "email": "natevw@yahoo.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "natevw", + "email": "natevw@yahoo.com" + } + ], + "dist": { + "shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c", + "tarball": "http://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/cookie/HISTORY.md b/5-2/service/node_modules/express/node_modules/cookie/HISTORY.md new file mode 100644 index 0000000..c9803ce --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/cookie/HISTORY.md @@ -0,0 +1,72 @@ +0.1.5 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.1.4 / 2015-09-17 +================== + + * Throw better error for invalid argument to parse + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.1.3 / 2015-05-19 +================== + + * Reduce the scope of try-catch deopt + * Remove argument reassignments + +0.1.2 / 2014-04-16 +================== + + * Remove unnecessary files from npm package + +0.1.1 / 2014-02-23 +================== + + * Fix bad parse when cookie value contained a comma + * Fix support for `maxAge` of `0` + +0.1.0 / 2013-05-01 +================== + + * Add `decode` option + * Add `encode` option + +0.0.6 / 2013-04-08 +================== + + * Ignore cookie parts missing `=` + +0.0.5 / 2012-10-29 +================== + + * Return raw cookie value if value unescape errors + +0.0.4 / 2012-06-21 +================== + + * Use encode/decodeURIComponent for cookie encoding/decoding + - Improve server/client interoperability + +0.0.3 / 2012-06-06 +================== + + * Only escape special characters per the cookie RFC + +0.0.2 / 2012-06-01 +================== + + * Fix `maxAge` option to not throw error + +0.0.1 / 2012-05-28 +================== + + * Add more tests + +0.0.0 / 2012-05-28 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/cookie/LICENSE b/5-2/service/node_modules/express/node_modules/cookie/LICENSE new file mode 100644 index 0000000..e849495 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +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 +'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/5-2/service/node_modules/express/node_modules/cookie/README.md b/5-2/service/node_modules/express/node_modules/cookie/README.md new file mode 100644 index 0000000..acdb5c2 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/cookie/README.md @@ -0,0 +1,64 @@ +# cookie + +[![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] + +cookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers. + +See [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies. + +## how? + +``` +npm install cookie +``` + +```javascript +var cookie = require('cookie'); + +var hdr = cookie.serialize('foo', 'bar'); +// hdr = 'foo=bar'; + +var cookies = cookie.parse('foo=bar; cat=meow; dog=ruff'); +// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' }; +``` + +## more + +The serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values. + +### path +> cookie path + +### expires +> absolute expiration date for the cookie (Date object) + +### maxAge +> relative max age of the cookie from when the client receives it (seconds) + +### domain +> domain for the cookie + +### secure +> true or false + +### httpOnly +> true or false + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/cookie.svg +[npm-url]: https://npmjs.org/package/cookie +[node-version-image]: https://img.shields.io/node/v/cookie.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/cookie/master.svg +[travis-url]: https://travis-ci.org/jshttp/cookie +[coveralls-image]: https://img.shields.io/coveralls/jshttp/cookie/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[downloads-image]: https://img.shields.io/npm/dm/cookie.svg +[downloads-url]: https://npmjs.org/package/cookie diff --git a/5-2/service/node_modules/express/node_modules/cookie/index.js b/5-2/service/node_modules/express/node_modules/cookie/index.js new file mode 100644 index 0000000..b8389a1 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/cookie/index.js @@ -0,0 +1,156 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var decode = decodeURIComponent; +var encode = encodeURIComponent; + +/** + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF + */ + +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var pairs = str.split(/; */); + var dec = opt.decode || decode; + + pairs.forEach(function(pair) { + var eq_idx = pair.indexOf('=') + + // skip things that don't look like key=value + if (eq_idx < 0) { + return; + } + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + }); + + return obj; +} + +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var pairs = [name + '=' + value]; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + pairs.push('Max-Age=' + maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + + pairs.push('Domain=' + opt.domain); + } + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + pairs.push('Path=' + opt.path); + } + + if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString()); + if (opt.httpOnly) pairs.push('HttpOnly'); + if (opt.secure) pairs.push('Secure'); + + return pairs.join('; '); +} + +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ + +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} diff --git a/5-2/service/node_modules/express/node_modules/cookie/package.json b/5-2/service/node_modules/express/node_modules/cookie/package.json new file mode 100644 index 0000000..01399d0 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/cookie/package.json @@ -0,0 +1,76 @@ +{ + "name": "cookie", + "description": "cookie parsing and serialization", + "version": "0.1.5", + "author": { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "cookie", + "cookies" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/cookie.git" + }, + "devDependencies": { + "istanbul": "0.3.20", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --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": "0dfc4876575cef2609cdc1082fccf832743822c2", + "bugs": { + "url": "https://github.com/jshttp/cookie/issues" + }, + "homepage": "https://github.com/jshttp/cookie", + "_id": "cookie@0.1.5", + "_shasum": "6ab9948a4b1ae21952cd2588530a4722d4044d7c", + "_from": "cookie@0.1.5", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "6ab9948a4b1ae21952cd2588530a4722d4044d7c", + "tarball": "http://registry.npmjs.org/cookie/-/cookie-0.1.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/debug/.jshintrc b/5-2/service/node_modules/express/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/5-2/service/node_modules/express/node_modules/debug/.npmignore b/5-2/service/node_modules/express/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/5-2/service/node_modules/express/node_modules/debug/History.md b/5-2/service/node_modules/express/node_modules/debug/History.md new file mode 100644 index 0000000..854c971 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/History.md @@ -0,0 +1,195 @@ + +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 +================== + + * 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/5-2/service/node_modules/express/node_modules/debug/Makefile b/5-2/service/node_modules/express/node_modules/debug/Makefile new file mode 100644 index 0000000..5cf4a59 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/Makefile @@ -0,0 +1,36 @@ + +# 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 dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +distclean: clean + @rm -rf node_modules + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean distclean diff --git a/5-2/service/node_modules/express/node_modules/debug/Readme.md b/5-2/service/node_modules/express/node_modules/debug/Readme.md new file mode 100644 index 0000000..b4f45e3 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/Readme.md @@ -0,0 +1,188 @@ +# 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'); +``` + +### 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 + - 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/5-2/service/node_modules/express/node_modules/debug/bower.json b/5-2/service/node_modules/express/node_modules/debug/bower.json new file mode 100644 index 0000000..6af573f --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/bower.json @@ -0,0 +1,28 @@ +{ + "name": "visionmedia-debug", + "main": "dist/debug.js", + "version": "2.2.0", + "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/5-2/service/node_modules/express/node_modules/debug/browser.js b/5-2/service/node_modules/express/node_modules/debug/browser.js new file mode 100644 index 0000000..7c76452 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/browser.js @@ -0,0 +1,168 @@ + +/** + * 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; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : 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) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.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/5-2/service/node_modules/express/node_modules/debug/component.json b/5-2/service/node_modules/express/node_modules/debug/component.json new file mode 100644 index 0000000..ca10637 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.2.0", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/5-2/service/node_modules/express/node_modules/debug/debug.js b/5-2/service/node_modules/express/node_modules/debug/debug.js new file mode 100644 index 0000000..7571a86 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * 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/5-2/service/node_modules/express/node_modules/debug/node.js b/5-2/service/node_modules/express/node_modules/debug/node.js new file mode 100644 index 0000000..1d392a8 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/node.js @@ -0,0 +1,209 @@ + +/** + * 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/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/.npmignore b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/History.md b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/LICENSE b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/README.md b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/index.js b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/package.json b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/debug/package.json b/5-2/service/node_modules/express/node_modules/debug/package.json new file mode 100644 index 0000000..24bb9c9 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/debug/package.json @@ -0,0 +1,73 @@ +{ + "name": "debug", + "version": "2.2.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "license": "MIT", + "dependencies": { + "ms": "0.7.1" + }, + "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": "b38458422b5aa8aa6d286b10dfe427e8a67e2b35", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@2.2.0", + "scripts": {}, + "_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "_from": "debug@>=2.2.0 <2.3.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "tarball": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/depd/History.md b/5-2/service/node_modules/express/node_modules/depd/History.md new file mode 100644 index 0000000..ace1171 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/depd/History.md @@ -0,0 +1,84 @@ +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/5-2/service/node_modules/express/node_modules/depd/LICENSE b/5-2/service/node_modules/express/node_modules/depd/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-2/service/node_modules/express/node_modules/depd/Readme.md b/5-2/service/node_modules/express/node_modules/depd/Readme.md new file mode 100644 index 0000000..09bb979 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/depd/Readme.md @@ -0,0 +1,281 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction() { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: http://nodejs.org/download/ +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/5-2/service/node_modules/express/node_modules/depd/index.js b/5-2/service/node_modules/express/node_modules/depd/index.js new file mode 100644 index 0000000..fddcae8 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/depd/index.js @@ -0,0 +1,521 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace(str, namespace) { + var val = str.split(/[ ,]+/) + + namespace = String(namespace).toLowerCase() + + for (var i = 0 ; i < val.length; i++) { + if (!(str = val[i])) continue; + + // namespace contained + if (str === '*' || str.toLowerCase() === namespace) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor(obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter() { return value } + + if (descriptor.writable) { + descriptor.set = function setter(val) { return value = val } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString(arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString(stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate(message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log(message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + callSite = callSiteLocation(stack[1]) + callSite.name = site.name + file = callSite[0] + } else { + // get call site + i = 2 + site = callSiteLocation(stack[i]) + callSite = site + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? site.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + if (!message) { + message = callSite === site || !callSite.name + ? defaultMessage(site) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, message, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var msg = format.call(this, message, caller, stack.slice(i)) + process.stderr.write(msg + '\n', 'utf8') + + return +} + +/** + * Get call site location as array. + */ + +function callSiteLocation(callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage(site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain(msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor(msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' // bold cyan + + ' \x1b[33;1mdeprecated\x1b[22;39m' // bold yellow + + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation(callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace(obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter() { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter() { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError(namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return stackString = createStackString.call(this, stack) + }, + set: function setter(val) { + stackString = val + } + }) + + return error +} diff --git a/5-2/service/node_modules/express/node_modules/depd/lib/browser/index.js b/5-2/service/node_modules/express/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..f464e05 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/depd/lib/browser/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate(message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + return +} diff --git a/5-2/service/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js b/5-2/service/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js new file mode 100644 index 0000000..4b73381 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js @@ -0,0 +1,35 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = bufferConcat + +/** + * Concatenate an array of Buffers. + */ + +function bufferConcat(bufs) { + var length = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + length += bufs[i].length + } + + var buf = new Buffer(length) + var pos = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + bufs[i].copy(buf, pos) + pos += bufs[i].length + } + + return buf +} diff --git a/5-2/service/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js b/5-2/service/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 0000000..9ecef34 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation(callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString(callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName(obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/5-2/service/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js b/5-2/service/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 0000000..a05fceb --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount(emitter, type) { + return emitter.listeners(type).length +} diff --git a/5-2/service/node_modules/express/node_modules/depd/lib/compat/index.js b/5-2/service/node_modules/express/node_modules/depd/lib/compat/index.js new file mode 100644 index 0000000..aa3c1de --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/depd/lib/compat/index.js @@ -0,0 +1,84 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('buffer') +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'bufferConcat', function bufferConcat() { + return Buffer.concat || require('./buffer-concat') +}) + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace(obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount() { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty(obj, prop, getter) { + function get() { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString(obj) { + return obj.toString() +} diff --git a/5-2/service/node_modules/express/node_modules/depd/package.json b/5-2/service/node_modules/express/node_modules/depd/package.json new file mode 100644 index 0000000..9da460a --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/depd/package.json @@ -0,0 +1,67 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "1.1.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/dougwilson/nodejs-depd.git" + }, + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail test/", + "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": "78c659de20283e3a6bee92bda455e6daff01686a", + "bugs": { + "url": "https://github.com/dougwilson/nodejs-depd/issues" + }, + "homepage": "https://github.com/dougwilson/nodejs-depd", + "_id": "depd@1.1.0", + "_shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "_from": "depd@>=1.1.0 <1.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "tarball": "http://registry.npmjs.org/depd/-/depd-1.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/depd/-/depd-1.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/escape-html/LICENSE b/5-2/service/node_modules/express/node_modules/escape-html/LICENSE new file mode 100644 index 0000000..2e70de9 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/escape-html/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2013 TJ Holowaychuk +Copyright (c) 2015 Andreas Lubbe +Copyright (c) 2015 Tiancheng "Timothy" Gu + +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/5-2/service/node_modules/express/node_modules/escape-html/Readme.md b/5-2/service/node_modules/express/node_modules/escape-html/Readme.md new file mode 100644 index 0000000..653d9ea --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/escape-html/Readme.md @@ -0,0 +1,43 @@ + +# escape-html + + Escape string for use in HTML + +## Example + +```js +var escape = require('escape-html'); +var html = escape('foo & bar'); +// -> foo & bar +``` + +## Benchmark + +``` +$ npm run-script bench + +> escape-html@1.0.3 bench nodejs-escape-html +> 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 + + 1 test completed. + 2 tests completed. + 3 tests completed. + + no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) + single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) + many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) +``` + +## License + + MIT \ No newline at end of file diff --git a/5-2/service/node_modules/express/node_modules/escape-html/index.js b/5-2/service/node_modules/express/node_modules/escape-html/index.js new file mode 100644 index 0000000..bf9e226 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/escape-html/index.js @@ -0,0 +1,78 @@ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} diff --git a/5-2/service/node_modules/express/node_modules/escape-html/package.json b/5-2/service/node_modules/express/node_modules/escape-html/package.json new file mode 100644 index 0000000..eb73427 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/escape-html/package.json @@ -0,0 +1,57 @@ +{ + "name": "escape-html", + "description": "Escape string for use in HTML", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "escape", + "html", + "utility" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/component/escape-html.git" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4" + }, + "files": [ + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "bench": "node benchmark/index.js" + }, + "gitHead": "7ac2ea3977fcac3d4c5be8d2a037812820c65f28", + "bugs": { + "url": "https://github.com/component/escape-html/issues" + }, + "homepage": "https://github.com/component/escape-html", + "_id": "escape-html@1.0.3", + "_shasum": "0258eae4d3d0c0974de1c169188ef0051d1d1988", + "_from": "escape-html@>=1.0.3 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "0258eae4d3d0c0974de1c169188ef0051d1d1988", + "tarball": "http://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/etag/HISTORY.md b/5-2/service/node_modules/express/node_modules/etag/HISTORY.md new file mode 100644 index 0000000..bd0f26d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/etag/HISTORY.md @@ -0,0 +1,71 @@ +1.7.0 / 2015-06-08 +================== + + * Always include entity length in ETags for hash length extensions + * Generate non-Stats ETags using MD5 only (no longer CRC32) + * Improve stat performance by removing hashing + * Remove base64 padding in ETags to shorten + * Use MD5 instead of MD4 in weak ETags over 1KB + +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 +================== + + * deps: crc@3.2.1 + - Minor fixes + +1.5.0 / 2014-10-14 +================== + + * Improve string performance + * Slightly improve speed for weak ETags over 1KB + +1.4.0 / 2014-09-21 +================== + + * Support "fake" stats objects + * Support Node.js 0.6 + +1.3.1 / 2014-09-14 +================== + + * Use the (new and improved) `crc` for crc32 + +1.3.0 / 2014-08-29 +================== + + * Default strings to strong ETags + * Improve speed for weak ETags over 1KB + +1.2.1 / 2014-08-29 +================== + + * Use the (much faster) `buffer-crc32` for crc32 + +1.2.0 / 2014-08-24 +================== + + * Add support for file stat objects + +1.1.0 / 2014-08-24 +================== + + * Add fast-path for empty entity + * Add weak ETag generation + * Shrink size of generated ETags + +1.0.1 / 2014-08-24 +================== + + * Fix behavior of string containing Unicode + +1.0.0 / 2014-05-18 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/etag/LICENSE b/5-2/service/node_modules/express/node_modules/etag/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/etag/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-2/service/node_modules/express/node_modules/etag/README.md b/5-2/service/node_modules/express/node_modules/etag/README.md new file mode 100644 index 0000000..8da9e05 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/etag/README.md @@ -0,0 +1,165 @@ +# etag + +[![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] + +Create simple ETags + +## Installation + +```sh +$ npm install etag +``` + +## API + +```js +var etag = require('etag') +``` + +### etag(entity, [options]) + +Generate a strong ETag for the given entity. This should be the complete +body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By +default, a strong ETag is generated except for `fs.Stats`, which will +generate a weak ETag (this can be overwritten by `options.weak`). + +```js +res.setHeader('ETag', etag(body)) +``` + +#### Options + +`etag` accepts these properties in the options object. + +##### weak + +Specifies if the generated ETag will include the weak validator mark (that +is, the leading `W/`). The actual entity tag is the same. The default value +is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +```bash +$ npm run-script bench + +> 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 + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 289,198 ops/sec ±1.09% (190 runs sampled) +* buffer - weak x 287,838 ops/sec ±0.91% (189 runs sampled) +* string - strong x 284,586 ops/sec ±1.05% (192 runs sampled) +* string - weak x 287,439 ops/sec ±0.82% (192 runs sampled) + +> node benchmark/body1-1kb.js + + 1KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 212,423 ops/sec ±0.75% (193 runs sampled) +* buffer - weak x 211,871 ops/sec ±0.74% (194 runs sampled) + string - strong x 205,291 ops/sec ±0.86% (194 runs sampled) + string - weak x 208,463 ops/sec ±0.79% (192 runs sampled) + +> node benchmark/body2-5kb.js + + 5KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 92,901 ops/sec ±0.58% (195 runs sampled) +* buffer - weak x 93,045 ops/sec ±0.65% (192 runs sampled) + string - strong x 89,621 ops/sec ±0.68% (194 runs sampled) + string - weak x 90,070 ops/sec ±0.70% (196 runs sampled) + +> node benchmark/body3-10kb.js + + 10KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 54,220 ops/sec ±0.85% (192 runs sampled) +* buffer - weak x 54,069 ops/sec ±0.83% (191 runs sampled) + string - strong x 53,078 ops/sec ±0.53% (194 runs sampled) + string - weak x 53,849 ops/sec ±0.47% (197 runs sampled) + +> node benchmark/body4-100kb.js + + 100KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 6,673 ops/sec ±0.15% (197 runs sampled) +* buffer - weak x 6,716 ops/sec ±0.12% (198 runs sampled) + string - strong x 6,357 ops/sec ±0.14% (197 runs sampled) + string - weak x 6,344 ops/sec ±0.21% (197 runs sampled) + +> node benchmark/stats.js + + stats + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* real - strong x 1,671,989 ops/sec ±0.13% (197 runs sampled) +* real - weak x 1,681,297 ops/sec ±0.12% (198 runs sampled) + fake - strong x 927,063 ops/sec ±0.14% (198 runs sampled) + fake - weak x 914,461 ops/sec ±0.41% (191 runs sampled) +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master +[downloads-image]: https://img.shields.io/npm/dm/etag.svg +[downloads-url]: https://npmjs.org/package/etag diff --git a/5-2/service/node_modules/express/node_modules/etag/index.js b/5-2/service/node_modules/express/node_modules/etag/index.js new file mode 100644 index 0000000..b582c84 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/etag/index.js @@ -0,0 +1,132 @@ +/*! + * etag + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = etag + +/** + * Module dependencies. + * @private + */ + +var crypto = require('crypto') +var Stats = require('fs').Stats + +/** + * Module variables. + * @private + */ + +var base64PadCharRegExp = /=+$/ +var toString = Object.prototype.toString + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag(entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-1B2M2Y8AsgTpgAmY7PhCfg"' + } + + // compute hash of entity + var hash = crypto + .createHash('md5') + .update(entity, 'utf8') + .digest('base64') + .replace(base64PadCharRegExp, '') + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag(entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats(obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + 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' + && 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag(stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} diff --git a/5-2/service/node_modules/express/node_modules/etag/package.json b/5-2/service/node_modules/express/node_modules/etag/package.json new file mode 100644 index 0000000..8dc110c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/etag/package.json @@ -0,0 +1,73 @@ +{ + "name": "etag", + "description": "Create simple ETags", + "version": "1.7.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "David Björklund", + "email": "david.bjorklund@gmail.com" + } + ], + "license": "MIT", + "keywords": [ + "etag", + "http", + "res" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/etag.git" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.3.14", + "mocha": "~1.21.4", + "seedrandom": "2.3.11" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "a511f5c8c930fd9546dbd88acb080f96bc788cfc", + "bugs": { + "url": "https://github.com/jshttp/etag/issues" + }, + "homepage": "https://github.com/jshttp/etag", + "_id": "etag@1.7.0", + "_shasum": "03d30b5f67dd6e632d2945d30d6652731a34d5d8", + "_from": "etag@>=1.7.0 <1.8.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "03d30b5f67dd6e632d2945d30d6652731a34d5d8", + "tarball": "http://registry.npmjs.org/etag/-/etag-1.7.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/etag/-/etag-1.7.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/finalhandler/HISTORY.md b/5-2/service/node_modules/express/node_modules/finalhandler/HISTORY.md new file mode 100644 index 0000000..78dddc0 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/finalhandler/HISTORY.md @@ -0,0 +1,98 @@ +0.4.1 / 2015-12-02 +================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + +0.4.0 / 2015-06-14 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + * Support `statusCode` property on `Error` objects + * Use `unpipe` module for unpiping requests + * deps: escape-html@1.0.2 + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.3.1 / 2014-10-16 +================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + +0.3.0 / 2014-09-17 +================== + + * Terminate in progress response only on error + * Use `on-finished` to determine request status + +0.2.0 / 2014-09-03 +================== + + * Set `X-Content-Type-Options: nosniff` header + * deps: debug@~2.0.0 + +0.1.0 / 2014-07-16 +================== + + * Respond after request fully read + - prevents hung responses and socket hang ups + * deps: debug@1.0.4 + +0.0.3 / 2014-07-11 +================== + + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.0.2 / 2014-06-19 +================== + + * Handle invalid status codes + +0.0.1 / 2014-06-05 +================== + + * deps: debug@1.0.2 + +0.0.0 / 2014-06-05 +================== + + * Extracted from connect/express diff --git a/5-2/service/node_modules/express/node_modules/finalhandler/LICENSE b/5-2/service/node_modules/express/node_modules/finalhandler/LICENSE new file mode 100644 index 0000000..b60a5ad --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/finalhandler/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-2/service/node_modules/express/node_modules/finalhandler/README.md b/5-2/service/node_modules/express/node_modules/finalhandler/README.md new file mode 100644 index 0000000..6b171d4 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/finalhandler/README.md @@ -0,0 +1,133 @@ +# finalhandler + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js function to invoke as the final step to respond to HTTP request. + +## Installation + +```sh +$ npm install finalhandler +``` + +## API + +```js +var finalhandler = require('finalhandler') +``` + +### finalhandler(req, res, [options]) + +Returns function to be invoked as the final step for the given `req` and `res`. +This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will +write out a 404 response to the `res`. If it is truthy, an error response will +be written out to the `res`, and `res.statusCode` is set from `err.status`. + +The final handler will also unpipe anything from `req` when it is invoked. + +#### options.env + +By default, the environment is determined by `NODE_ENV` variable, but it can be +overridden by this option. + +#### options.onerror + +Provide a function to be called with the `err` when it exists. Can be used for +writing errors to a central location without excessive function generation. Called +as `onerror(err, req, res)`. + +## Examples + +### always 404 + +```js +var finalhandler = require('finalhandler') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + done() +}) + +server.listen(3000) +``` + +### perform simple action + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) +``` + +### use with middleware-style functions + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +var serve = serveStatic('public') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + serve(req, res, done) +}) + +server.listen(3000) +``` + +### keep log of all errors + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res, {onerror: logerror}) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) + +function logerror(err) { + console.error(err.stack || err.toString()) +} +``` + +## License + +[MIT](LICENSE) + +[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 +[node-url]: http://nodejs.org/download/ +[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 +[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg +[downloads-url]: https://npmjs.org/package/finalhandler diff --git a/5-2/service/node_modules/express/node_modules/finalhandler/index.js b/5-2/service/node_modules/express/node_modules/finalhandler/index.js new file mode 100644 index 0000000..0de7c6b --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/finalhandler/index.js @@ -0,0 +1,151 @@ +/*! + * finalhandler + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('finalhandler') +var escapeHtml = require('escape-html') +var http = require('http') +var onFinished = require('on-finished') +var unpipe = require('unpipe') + +/** + * Module variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished + +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler(req, res, options) { + var opts = options || {} + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + + return function (err) { + var status = res.statusCode + + // ignore 404 on in-flight response + if (!err && res._header) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect err.statusCode + if (err.statusCode) { + status = err.statusCode + } + + // respect err.status + if (err.status) { + status = err.status + } + + // default status code to 500 + if (!status || status < 400) { + status = 500 + } + + // production gets a basic error message + var msg = env === 'production' + ? http.STATUS_CODES[status] + : err.stack || err.toString() + msg = escapeHtml(msg) + .replace(/\n/g, '
') + .replace(/ /g, '  ') + '\n' + } else { + status = 404 + msg = 'Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl || req.url) + '\n' + } + + debug('default %s', status) + + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } + + // cannot actually respond + if (res._header) { + return req.socket.destroy() + } + + send(req, res, status, msg) + } +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {string} body + * @private + */ + +function send(req, res, status, body) { + function write() { + res.statusCode = status + + // security header for content sniffing + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() +} diff --git a/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md b/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md new file mode 100644 index 0000000..85e0f8d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE b/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE new file mode 100644 index 0000000..aed0138 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md b/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md new file mode 100644 index 0000000..e536ad2 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js b/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js new file mode 100644 index 0000000..15c3d97 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json b/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json new file mode 100644 index 0000000..4af1b49 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json @@ -0,0 +1,59 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/unpipe.git" + }, + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "d2df901c06487430e78dca62b6edb8bb2fc5e99d", + "bugs": { + "url": "https://github.com/stream-utils/unpipe/issues" + }, + "homepage": "https://github.com/stream-utils/unpipe", + "_id": "unpipe@1.0.0", + "_shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "_from": "unpipe@>=1.0.0 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "tarball": "http://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/finalhandler/package.json b/5-2/service/node_modules/express/node_modules/finalhandler/package.json new file mode 100644 index 0000000..0afe7fc --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/finalhandler/package.json @@ -0,0 +1,81 @@ +{ + "name": "finalhandler", + "description": "Node.js final http responder", + "version": "0.4.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/finalhandler.git" + }, + "dependencies": { + "debug": "~2.2.0", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "unpipe": "~1.0.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "2.3.4", + "readable-stream": "2.0.4", + "supertest": "1.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "ac2036774059eb93dbac8475580e52433204d4d4", + "bugs": { + "url": "https://github.com/pillarjs/finalhandler/issues" + }, + "homepage": "https://github.com/pillarjs/finalhandler", + "_id": "finalhandler@0.4.1", + "_shasum": "85a17c6c59a94717d262d61230d4b0ebe3d4a14d", + "_from": "finalhandler@0.4.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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "85a17c6c59a94717d262d61230d4b0ebe3d4a14d", + "tarball": "http://registry.npmjs.org/finalhandler/-/finalhandler-0.4.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-0.4.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/fresh/HISTORY.md b/5-2/service/node_modules/express/node_modules/fresh/HISTORY.md new file mode 100644 index 0000000..3c95fbb --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/fresh/HISTORY.md @@ -0,0 +1,38 @@ +0.3.0 / 2015-05-12 +================== + + * Add weak `ETag` matching support + +0.2.4 / 2014-09-07 +================== + + * Support Node.js 0.6 + +0.2.3 / 2014-09-07 +================== + + * Move repository to jshttp + +0.2.2 / 2014-02-19 +================== + + * Revert "Fix for blank page on Safari reload" + +0.2.1 / 2014-01-29 +================== + + * Fix for blank page on Safari reload + +0.2.0 / 2013-08-11 +================== + + * Return stale for `Cache-Control: no-cache` + +0.1.0 / 2012-06-15 +================== + * Add `If-None-Match: *` support + +0.0.1 / 2012-06-10 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/fresh/LICENSE b/5-2/service/node_modules/express/node_modules/fresh/LICENSE new file mode 100644 index 0000000..f527394 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/fresh/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/fresh/README.md b/5-2/service/node_modules/express/node_modules/fresh/README.md new file mode 100644 index 0000000..0813e30 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/fresh/README.md @@ -0,0 +1,58 @@ +# fresh + +[![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] + +HTTP response freshness testing + +## Installation + +``` +$ npm install fresh +``` + +## API + +```js +var fresh = require('fresh') +``` + +### fresh(req, res) + + Check freshness of `req` and `res` headers. + + When the cache is "fresh" __true__ is returned, + otherwise __false__ is returned to indicate that + the cache is now stale. + +## Example + +```js +var req = { 'if-none-match': 'tobi' }; +var res = { 'etag': 'luna' }; +fresh(req, res); +// => false + +var req = { 'if-none-match': 'tobi' }; +var res = { 'etag': 'tobi' }; +fresh(req, res); +// => true +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/fresh.svg +[npm-url]: https://npmjs.org/package/fresh +[node-version-image]: https://img.shields.io/node/v/fresh.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg +[travis-url]: https://travis-ci.org/jshttp/fresh +[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master +[downloads-image]: https://img.shields.io/npm/dm/fresh.svg +[downloads-url]: https://npmjs.org/package/fresh diff --git a/5-2/service/node_modules/express/node_modules/fresh/index.js b/5-2/service/node_modules/express/node_modules/fresh/index.js new file mode 100644 index 0000000..a900873 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/fresh/index.js @@ -0,0 +1,57 @@ + +/** + * Expose `fresh()`. + */ + +module.exports = fresh; + +/** + * Check freshness of `req` and `res` headers. + * + * When the cache is "fresh" __true__ is returned, + * otherwise __false__ is returned to indicate that + * the cache is now stale. + * + * @param {Object} req + * @param {Object} res + * @return {Boolean} + * @api public + */ + +function fresh(req, res) { + // defaults + var etagMatches = true; + var notModified = true; + + // fields + var modifiedSince = req['if-modified-since']; + var noneMatch = req['if-none-match']; + var lastModified = res['last-modified']; + var etag = res['etag']; + var cc = req['cache-control']; + + // unconditional request + if (!modifiedSince && !noneMatch) return false; + + // check for no-cache cache request directive + if (cc && cc.indexOf('no-cache') !== -1) return false; + + // parse if-none-match + if (noneMatch) noneMatch = noneMatch.split(/ *, */); + + // if-none-match + if (noneMatch) { + etagMatches = noneMatch.some(function (match) { + return match === '*' || match === etag || match === 'W/' + etag; + }); + } + + // if-modified-since + if (modifiedSince) { + modifiedSince = new Date(modifiedSince); + lastModified = new Date(lastModified); + notModified = lastModified <= modifiedSince; + } + + return !! (etagMatches && notModified); +} diff --git a/5-2/service/node_modules/express/node_modules/fresh/package.json b/5-2/service/node_modules/express/node_modules/fresh/package.json new file mode 100644 index 0000000..74332c4 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/fresh/package.json @@ -0,0 +1,87 @@ +{ + "name": "fresh", + "description": "HTTP response freshness testing", + "version": "0.3.0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "fresh", + "http", + "conditional", + "cache" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/fresh.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "14616c9748368ca08cd6a955dd88ab659b778634", + "bugs": { + "url": "https://github.com/jshttp/fresh/issues" + }, + "homepage": "https://github.com/jshttp/fresh", + "_id": "fresh@0.3.0", + "_shasum": "651f838e22424e7566de161d8358caa199f83d4f", + "_from": "fresh@0.3.0", + "_npmVersion": "1.4.28", + "_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": "651f838e22424e7566de161d8358caa199f83d4f", + "tarball": "http://registry.npmjs.org/fresh/-/fresh-0.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/merge-descriptors/HISTORY.md b/5-2/service/node_modules/express/node_modules/merge-descriptors/HISTORY.md new file mode 100644 index 0000000..486771f --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/merge-descriptors/HISTORY.md @@ -0,0 +1,21 @@ +1.0.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.0.0 / 2015-03-01 +================== + + * Add option to only add new descriptors + * Add simple argument validation + * Add jsdoc to source file + +0.0.2 / 2013-12-14 +================== + + * Move repository to `component` organization + +0.0.1 / 2013-10-29 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/merge-descriptors/LICENSE b/5-2/service/node_modules/express/node_modules/merge-descriptors/LICENSE new file mode 100644 index 0000000..274bfd8 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/merge-descriptors/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 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 +'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/5-2/service/node_modules/express/node_modules/merge-descriptors/README.md b/5-2/service/node_modules/express/node_modules/merge-descriptors/README.md new file mode 100644 index 0000000..d593c0e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/merge-descriptors/README.md @@ -0,0 +1,48 @@ +# Merge Descriptors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Merge objects using descriptors. + +```js +var thing = { + get name() { + return 'jon' + } +} + +var animal = { + +} + +merge(animal, thing) + +animal.name === 'jon' +``` + +## API + +### merge(destination, source) + +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 + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/merge-descriptors.svg +[npm-url]: https://npmjs.org/package/merge-descriptors +[travis-image]: https://img.shields.io/travis/component/merge-descriptors/master.svg +[travis-url]: https://travis-ci.org/component/merge-descriptors +[coveralls-image]: https://img.shields.io/coveralls/component/merge-descriptors/master.svg +[coveralls-url]: https://coveralls.io/r/component/merge-descriptors?branch=master +[downloads-image]: https://img.shields.io/npm/dm/merge-descriptors.svg +[downloads-url]: https://npmjs.org/package/merge-descriptors diff --git a/5-2/service/node_modules/express/node_modules/merge-descriptors/index.js b/5-2/service/node_modules/express/node_modules/merge-descriptors/index.js new file mode 100644 index 0000000..573b132 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/merge-descriptors/index.js @@ -0,0 +1,60 @@ +/*! + * merge-descriptors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * 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 +} diff --git a/5-2/service/node_modules/express/node_modules/merge-descriptors/package.json b/5-2/service/node_modules/express/node_modules/merge-descriptors/package.json new file mode 100644 index 0000000..a65d2e8 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/merge-descriptors/package.json @@ -0,0 +1,138 @@ +{ + "name": "merge-descriptors", + "description": "Merge objects using descriptors", + "version": "1.0.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Mike Grabowski", + "email": "grabbou@gmail.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/component/merge-descriptors.git" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --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": "f26c49c3b423b0b2ac31f6e32a84e1632f2d7ac2", + "bugs": { + "url": "https://github.com/component/merge-descriptors/issues" + }, + "homepage": "https://github.com/component/merge-descriptors", + "_id": "merge-descriptors@1.0.1", + "_shasum": "b00aaa556dd8b44568150ec9d1b953f3f90cbb61", + "_from": "merge-descriptors@1.0.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "anthonyshort", + "email": "antshort@gmail.com" + }, + { + "name": "clintwood", + "email": "clint@anotherway.co.za" + }, + { + "name": "dfcreative", + "email": "df.creative@gmail.com" + }, + { + "name": "dominicbarnes", + "email": "dominic@dbarnes.info" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "ianstormtaylor", + "email": "ian@ianstormtaylor.com" + }, + { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + { + "name": "mattmueller", + "email": "mattmuelle@gmail.com" + }, + { + "name": "queckezz", + "email": "fabian.eichenberger@gmail.com" + }, + { + "name": "stephenmathieson", + "email": "me@stephenmathieson.com" + }, + { + "name": "thehydroimpulse", + "email": "dnfagnan@gmail.com" + }, + { + "name": "timaschew", + "email": "timaschew@gmail.com" + }, + { + "name": "timoxley", + "email": "secoif@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + { + "name": "trevorgerhardt", + "email": "trevorgerhardt@gmail.com" + }, + { + "name": "yields", + "email": "yields@icloud.com" + } + ], + "dist": { + "shasum": "b00aaa556dd8b44568150ec9d1b953f3f90cbb61", + "tarball": "http://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/methods/HISTORY.md b/5-2/service/node_modules/express/node_modules/methods/HISTORY.md new file mode 100644 index 0000000..c0ecf07 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/methods/HISTORY.md @@ -0,0 +1,29 @@ +1.1.2 / 2016-01-17 +================== + + * perf: enable strict mode + +1.1.1 / 2014-12-30 +================== + + * Improve `browserify` support + +1.1.0 / 2014-07-05 +================== + + * Add `CONNECT` method + +1.0.1 / 2014-06-02 +================== + + * Fix module to work with harmony transform + +1.0.0 / 2014-05-08 +================== + + * Add `PURGE` method + +0.1.0 / 2013-10-28 +================== + + * Add `http.METHODS` support diff --git a/5-2/service/node_modules/express/node_modules/methods/LICENSE b/5-2/service/node_modules/express/node_modules/methods/LICENSE new file mode 100644 index 0000000..220dc1a --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/methods/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013-2014 TJ Holowaychuk +Copyright (c) 2015-2016 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/5-2/service/node_modules/express/node_modules/methods/README.md b/5-2/service/node_modules/express/node_modules/methods/README.md new file mode 100644 index 0000000..672a32b --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/methods/README.md @@ -0,0 +1,51 @@ +# Methods + +[![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] + +HTTP verbs that Node.js core's HTTP parser supports. + +This module provides an export that is just like `http.METHODS` from Node.js core, +with the following differences: + + * All method names are lower-cased. + * Contains a fallback list of methods for Node.js versions that do not have a + `http.METHODS` export (0.10 and lower). + * Provides the fallback list when using tools like `browserify` without pulling + in the `http` shim module. + +## Install + +```bash +$ npm install methods +``` + +## API + +```js +var methods = require('methods') +``` + +### methods + +This is an array of lower-cased method names that Node.js supports. If Node.js +provides the `http.METHODS` export, then this is the same array lower-cased, +otherwise it is a snapshot of the verbs from Node.js 0.10. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat +[npm-url]: https://npmjs.org/package/methods +[node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/methods +[coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master +[downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat +[downloads-url]: https://npmjs.org/package/methods diff --git a/5-2/service/node_modules/express/node_modules/methods/index.js b/5-2/service/node_modules/express/node_modules/methods/index.js new file mode 100644 index 0000000..667a50b --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/methods/index.js @@ -0,0 +1,69 @@ +/*! + * methods + * Copyright(c) 2013-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var http = require('http'); + +/** + * Module exports. + * @public + */ + +module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); + +/** + * Get the current Node.js methods. + * @private + */ + +function getCurrentNodeMethods() { + return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { + return method.toLowerCase(); + }); +} + +/** + * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * @private + */ + +function getBasicNodeMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect' + ]; +} diff --git a/5-2/service/node_modules/express/node_modules/methods/package.json b/5-2/service/node_modules/express/node_modules/methods/package.json new file mode 100644 index 0000000..fd072fc --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/methods/package.json @@ -0,0 +1,88 @@ +{ + "name": "methods", + "description": "HTTP methods that node supports", + "version": "1.1.2", + "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+https://github.com/jshttp/methods.git" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE" + ], + "engines": { + "node": ">= 0.6" + }, + "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/" + }, + "browser": { + "http": false + }, + "keywords": [ + "http", + "methods" + ], + "gitHead": "25d257d913f1b94bd2d73581521ff72c81469140", + "bugs": { + "url": "https://github.com/jshttp/methods/issues" + }, + "homepage": "https://github.com/jshttp/methods", + "_id": "methods@1.1.2", + "_shasum": "5529a4d67654134edcc5266656835b0f851afcee", + "_from": "methods@>=1.1.2 <1.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "5529a4d67654134edcc5266656835b0f851afcee", + "tarball": "http://registry.npmjs.org/methods/-/methods-1.1.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/on-finished/HISTORY.md b/5-2/service/node_modules/express/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000..98ff0e9 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/on-finished/HISTORY.md @@ -0,0 +1,88 @@ +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +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 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/on-finished/LICENSE b/5-2/service/node_modules/express/node_modules/on-finished/LICENSE new file mode 100644 index 0000000..5931fd2 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/on-finished/README.md b/5-2/service/node_modules/express/node_modules/on-finished/README.md new file mode 100644 index 0000000..a0e1157 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/on-finished/README.md @@ -0,0 +1,154 @@ +# on-finished + +[![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] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to 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, res) { + // clean up open fds, etc. + // err contains the error is request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to 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 = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg +[downloads-url]: https://npmjs.org/package/on-finished diff --git a/5-2/service/node_modules/express/node_modules/on-finished/index.js b/5-2/service/node_modules/express/node_modules/on-finished/index.js new file mode 100644 index 0000000..9abd98f --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/on-finished/index.js @@ -0,0 +1,196 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener(msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish(error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket) + callback(socket) + } +} diff --git a/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE b/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md b/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js b/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json b/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json new file mode 100644 index 0000000..1d223fb --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json @@ -0,0 +1,64 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jonathanong/ee-first.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "512e0ce4cc3643f603708f965a97b61b1a9c0441", + "bugs": { + "url": "https://github.com/jonathanong/ee-first/issues" + }, + "homepage": "https://github.com/jonathanong/ee-first", + "_id": "ee-first@1.1.1", + "_shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "_from": "ee-first@1.1.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/on-finished/package.json b/5-2/service/node_modules/express/node_modules/on-finished/package.json new file mode 100644 index 0000000..7b2ebdd --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/on-finished/package.json @@ -0,0 +1,71 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.3.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/on-finished.git" + }, + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "34babcb58126a416fcf5205768204f2e12699dda", + "bugs": { + "url": "https://github.com/jshttp/on-finished/issues" + }, + "homepage": "https://github.com/jshttp/on-finished", + "_id": "on-finished@2.3.0", + "_shasum": "20f1336481b083cd75337992a16971aa2d906947", + "_from": "on-finished@>=2.3.0 <2.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "20f1336481b083cd75337992a16971aa2d906947", + "tarball": "http://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/parseurl/HISTORY.md b/5-2/service/node_modules/express/node_modules/parseurl/HISTORY.md new file mode 100644 index 0000000..395041e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/parseurl/HISTORY.md @@ -0,0 +1,47 @@ +1.3.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.3.0 / 2014-08-09 +================== + + * Add `parseurl.original` for parsing `req.originalUrl` with fallback + * Return `undefined` if `req.url` is `undefined` + +1.2.0 / 2014-07-21 +================== + + * Cache URLs based on original value + * Remove no-longer-needed URL mis-parse work-around + * Simplify the "fast-path" `RegExp` + +1.1.3 / 2014-07-08 +================== + + * Fix typo + +1.1.2 / 2014-07-08 +================== + + * Seriously fix Node.js 0.8 compatibility + +1.1.1 / 2014-07-08 +================== + + * Fix Node.js 0.8 compatibility + +1.1.0 / 2014-07-08 +================== + + * Incorporate URL href-only parse fast-path + +1.0.1 / 2014-03-08 +================== + + * Add missing `require` + +1.0.0 / 2014-03-08 +================== + + * Genesis from `connect` diff --git a/5-2/service/node_modules/express/node_modules/parseurl/LICENSE b/5-2/service/node_modules/express/node_modules/parseurl/LICENSE new file mode 100644 index 0000000..ec7dfe7 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/parseurl/LICENSE @@ -0,0 +1,24 @@ + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/parseurl/README.md b/5-2/service/node_modules/express/node_modules/parseurl/README.md new file mode 100644 index 0000000..f4796eb --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/parseurl/README.md @@ -0,0 +1,120 @@ +# parseurl + +[![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] + +Parse a URL with memoization. + +## Install + +```bash +$ npm install parseurl +``` + +## API + +```js +var parseurl = require('parseurl') +``` + +### parseurl(req) + +Parse the URL of the given request object (looks at the `req.url` property) +and return the result. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.url` does +not change will return a cached parsed object, rather than parsing again. + +### parseurl.original(req) + +Parse the original URL of the given request object and return the result. +This works by trying to parse `req.originalUrl` if it is a string, otherwise +parses `req.url`. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.originalUrl` +does not change will return a cached parsed object, rather than parsing again. + +## Benchmark + +```bash +$ npm run-script bench + +> parseurl@1.3.1 bench nodejs-parseurl +> node benchmark/index.js + +> node benchmark/fullurl.js + + Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 1,290,780 ops/sec ±0.46% (195 runs sampled) + nativeurl x 56,401 ops/sec ±0.22% (196 runs sampled) + parseurl x 55,231 ops/sec ±0.22% (194 runs sampled) + +> node benchmark/pathquery.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 1,986,668 ops/sec ±0.27% (190 runs sampled) + nativeurl x 98,740 ops/sec ±0.21% (195 runs sampled) + parseurl x 2,628,171 ops/sec ±0.36% (195 runs sampled) + +> node benchmark/samerequest.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 2,184,468 ops/sec ±0.40% (194 runs sampled) + nativeurl x 99,437 ops/sec ±0.71% (194 runs sampled) + parseurl x 10,498,005 ops/sec ±0.61% (186 runs sampled) + +> node benchmark/simplepath.js + + Parsing URL "/foo/bar" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 4,535,825 ops/sec ±0.27% (191 runs sampled) + nativeurl x 98,769 ops/sec ±0.54% (191 runs sampled) + parseurl x 4,164,865 ops/sec ±0.34% (192 runs sampled) + +> node benchmark/slash.js + + Parsing URL "/" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 4,908,405 ops/sec ±0.42% (191 runs sampled) + nativeurl x 100,945 ops/sec ±0.59% (188 runs sampled) + parseurl x 4,333,208 ops/sec ±0.27% (194 runs sampled) +``` + +## License + + [MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/parseurl.svg +[npm-url]: https://npmjs.org/package/parseurl +[node-version-image]: https://img.shields.io/node/v/parseurl.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/pillarjs/parseurl/master.svg +[travis-url]: https://travis-ci.org/pillarjs/parseurl +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/parseurl/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master +[downloads-image]: https://img.shields.io/npm/dm/parseurl.svg +[downloads-url]: https://npmjs.org/package/parseurl diff --git a/5-2/service/node_modules/express/node_modules/parseurl/index.js b/5-2/service/node_modules/express/node_modules/parseurl/index.js new file mode 100644 index 0000000..56cc6ec --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/parseurl/index.js @@ -0,0 +1,138 @@ +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var url = require('url') +var parse = url.parse +var Url = url.Url + +/** + * Pattern for a simple path case. + * See: https://github.com/joyent/node/pull/7878 + */ + +var simplePathRegExp = /^(\/\/?(?!\/)[^\?#\s]*)(\?[^#\s]*)?$/ + +/** + * Exports. + */ + +module.exports = parseurl +module.exports.original = originalurl + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @api public + */ + +function parseurl(req) { + var url = req.url + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return req._parsedUrl = parsed +}; + +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @api public + */ + +function originalurl(req) { + var url = req.originalUrl + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return req._parsedOriginalUrl = parsed +}; + +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @api private + */ + +function fastparse(str) { + // Try fast path regexp + // See: https://github.com/joyent/node/pull/7878 + var simplePath = typeof str === 'string' && simplePathRegExp.exec(str) + + // Construct simple URL + if (simplePath) { + var pathname = simplePath[1] + var search = simplePath[2] || null + var url = Url !== undefined + ? new Url() + : {} + url.path = str + url.href = str + url.pathname = pathname + url.search = search + url.query = search && search.substr(1) + + return url + } + + return parse(str) +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @api private + */ + +function fresh(url, parsedUrl) { + return typeof parsedUrl === 'object' + && parsedUrl !== null + && (Url === undefined || parsedUrl instanceof Url) + && parsedUrl._raw === url +} diff --git a/5-2/service/node_modules/express/node_modules/parseurl/package.json b/5-2/service/node_modules/express/node_modules/parseurl/package.json new file mode 100644 index 0000000..7ba6287 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/parseurl/package.json @@ -0,0 +1,89 @@ +{ + "name": "parseurl", + "description": "parse a url with memoization", + "version": "1.3.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/parseurl.git" + }, + "license": "MIT", + "devDependencies": { + "benchmark": "2.0.0", + "beautify-benchmark": "0.2.4", + "fast-url-parser": "1.1.3", + "istanbul": "0.4.2", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --check-leaks --bail --reporter spec test/", + "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": "6d22d376d75b927ab2b5347ce3a1d6735133dd43", + "bugs": { + "url": "https://github.com/pillarjs/parseurl/issues" + }, + "homepage": "https://github.com/pillarjs/parseurl", + "_id": "parseurl@1.3.1", + "_shasum": "c8ab8c9223ba34888aa64a297b28853bec18da56", + "_from": "parseurl@>=1.3.1 <1.4.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" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "c8ab8c9223ba34888aa64a297b28853bec18da56", + "tarball": "http://registry.npmjs.org/parseurl/-/parseurl-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/path-to-regexp/History.md b/5-2/service/node_modules/express/node_modules/path-to-regexp/History.md new file mode 100644 index 0000000..7f65878 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/path-to-regexp/History.md @@ -0,0 +1,36 @@ +0.1.7 / 2015-07-28 +================== + + * Fixed regression with escaped round brackets and matching groups. + +0.1.6 / 2015-06-19 +================== + + * Replace `index` feature by outputting all parameters, unnamed and named. + +0.1.5 / 2015-05-08 +================== + + * Add an index property for position in match result. + +0.1.4 / 2015-03-05 +================== + + * Add license information + +0.1.3 / 2014-07-06 +================== + + * Better array support + * Improved support for trailing slash in non-ending mode + +0.1.0 / 2014-03-06 +================== + + * add options.end + +0.0.2 / 2013-02-10 +================== + + * Update to match current express + * add .license property to component.json diff --git a/5-2/service/node_modules/express/node_modules/path-to-regexp/LICENSE b/5-2/service/node_modules/express/node_modules/path-to-regexp/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/path-to-regexp/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/5-2/service/node_modules/express/node_modules/path-to-regexp/Readme.md b/5-2/service/node_modules/express/node_modules/path-to-regexp/Readme.md new file mode 100644 index 0000000..95452a6 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,35 @@ +# Path-to-RegExp + +Turn an Express-style path string such as `/user/:name` into a regular expression. + +**Note:** This is a legacy branch. You should upgrade to `1.x`. + +## Usage + +```javascript +var pathToRegexp = require('path-to-regexp'); +``` + +### pathToRegexp(path, keys, options) + + - **path** A string in the express format, an array of such strings, or a regular expression + - **keys** An array to be populated with the keys present in the url. Once the function completes, this will be an array of strings. + - **options** + - **options.sensitive** Defaults to false, set this to true to make routes case sensitive + - **options.strict** Defaults to false, set this to true to make the trailing slash matter. + - **options.end** Defaults to true, set this to false to only match the prefix of the URL. + +```javascript +var keys = []; +var exp = pathToRegexp('/foo/:bar', keys); +//keys = ['bar'] +//exp = /^\/foo\/(?:([^\/]+?))\/?$/i +``` + +## Live Demo + +You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/). + +## License + + MIT diff --git a/5-2/service/node_modules/express/node_modules/path-to-regexp/index.js b/5-2/service/node_modules/express/node_modules/path-to-regexp/index.js new file mode 100644 index 0000000..500d1da --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/path-to-regexp/index.js @@ -0,0 +1,129 @@ +/** + * Expose `pathtoRegexp`. + */ + +module.exports = pathtoRegexp; + +/** + * Match matching groups in a regular expression. + */ +var MATCHING_GROUP_REGEXP = /\((?!\?)/g; + +/** + * Normalize the given path string, + * returning a regular expression. + * + * An empty array should be passed, + * which will contain the placeholder + * key names. For example "/user/:id" will + * then contain ["id"]. + * + * @param {String|RegExp|Array} path + * @param {Array} keys + * @param {Object} options + * @return {RegExp} + * @api private + */ + +function pathtoRegexp(path, keys, options) { + options = options || {}; + keys = keys || []; + var strict = options.strict; + var end = options.end !== false; + var flags = options.sensitive ? '' : 'i'; + var extraOffset = 0; + var keysOffset = keys.length; + var i = 0; + var name = 0; + var m; + + if (path instanceof RegExp) { + while (m = MATCHING_GROUP_REGEXP.exec(path.source)) { + keys.push({ + name: name++, + optional: false, + offset: m.index + }); + } + + return path; + } + + if (Array.isArray(path)) { + // Map array parts into regexps and return their source. We also pass + // the same keys and options instance into every generation to get + // consistent matching groups before we join the sources together. + path = path.map(function (value) { + return pathtoRegexp(value, keys, options).source; + }); + + return new RegExp('(?:' + path.join('|') + ')', flags); + } + + path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) + .replace(/\/\(/g, '/(?:') + .replace(/([\/\.])/g, '\\$1') + .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) { + slash = slash || ''; + format = format || ''; + capture = capture || '([^\\/' + format + ']+?)'; + optional = optional || ''; + + keys.push({ + name: key, + optional: !!optional, + offset: offset + extraOffset + }); + + var result = '' + + (optional ? '' : slash) + + '(?:' + + format + (optional ? slash : '') + capture + + (star ? '((?:[\\/' + format + '].+?)?)' : '') + + ')' + + optional; + + extraOffset += result.length - match.length; + + return result; + }) + .replace(/\*/g, function (star, index) { + var len = keys.length + + while (len-- > keysOffset && keys[len].offset > index) { + keys[len].offset += 3; // Replacement length minus asterisk length. + } + + return '(.*)'; + }); + + // This is a workaround for handling unnamed matching groups. + while (m = MATCHING_GROUP_REGEXP.exec(path)) { + var escapeCount = 0; + var index = m.index; + + while (path.charAt(--index) === '\\') { + escapeCount++; + } + + // It's possible to escape the bracket. + if (escapeCount % 2 === 1) { + continue; + } + + if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) { + keys.splice(keysOffset + i, 0, { + name: name++, // Unnamed matching groups must be consistently linear. + optional: false, + offset: m.index + }); + } + + i++; + } + + // If the path is non-ending, match until the end or a slash. + path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)')); + + return new RegExp(path, flags); +}; diff --git a/5-2/service/node_modules/express/node_modules/path-to-regexp/package.json b/5-2/service/node_modules/express/node_modules/path-to-regexp/package.json new file mode 100644 index 0000000..118b1e6 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/path-to-regexp/package.json @@ -0,0 +1,185 @@ +{ + "name": "path-to-regexp", + "description": "Express style path to RegExp utility", + "version": "0.1.7", + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "keywords": [ + "express", + "regexp" + ], + "component": { + "scripts": { + "path-to-regexp": "index.js" + } + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/component/path-to-regexp.git" + }, + "devDependencies": { + "mocha": "^1.17.1", + "istanbul": "^0.2.6" + }, + "gitHead": "039118d6c3c186d3f176c73935ca887a32a33d93", + "bugs": { + "url": "https://github.com/component/path-to-regexp/issues" + }, + "homepage": "https://github.com/component/path-to-regexp#readme", + "_id": "path-to-regexp@0.1.7", + "_shasum": "df604178005f522f15eb4490e7247a1bfaa67f8c", + "_from": "path-to-regexp@0.1.7", + "_npmVersion": "2.13.2", + "_nodeVersion": "2.3.3", + "_npmUser": { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "hughsk", + "email": "hughskennedy@gmail.com" + }, + { + "name": "timaschew", + "email": "timaschew@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "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": "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" + }, + { + "name": "dfcreative", + "email": "df.creative@gmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "df604178005f522f15eb4490e7247a1bfaa67f8c", + "tarball": "http://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/HISTORY.md b/5-2/service/node_modules/express/node_modules/proxy-addr/HISTORY.md new file mode 100644 index 0000000..84f11aa --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/HISTORY.md @@ -0,0 +1,80 @@ +1.0.10 / 2015-12-09 +=================== + + * deps: ipaddr.js@1.0.5 + - Fix regression in `isValid` with non-string arguments + +1.0.9 / 2015-12-01 +================== + + * deps: ipaddr.js@1.0.4 + - Fix accepting some invalid IPv6 addresses + - Reject CIDRs with negative or overlong masks + * perf: enable strict mode + +1.0.8 / 2015-05-10 +================== + + * deps: ipaddr.js@1.0.1 + +1.0.7 / 2015-03-16 +================== + + * deps: ipaddr.js@0.1.9 + - Fix OOM on certain inputs to `isValid` + +1.0.6 / 2015-02-01 +================== + + * deps: ipaddr.js@0.1.8 + +1.0.5 / 2015-01-08 +================== + + * deps: ipaddr.js@0.1.6 + +1.0.4 / 2014-11-23 +================== + + * deps: ipaddr.js@0.1.5 + - Fix edge cases with `isValid` + +1.0.3 / 2014-09-21 +================== + + * Use `forwarded` npm module + +1.0.2 / 2014-09-18 +================== + + * Fix a global leak when multiple subnets are trusted + * Support Node.js 0.6 + * deps: ipaddr.js@0.1.3 + +1.0.1 / 2014-06-03 +================== + + * Fix links in npm package + +1.0.0 / 2014-05-08 +================== + + * Add `trust` argument to determine proxy trust on + * Accepts custom function + * Accepts IPv4/IPv6 address(es) + * Accepts subnets + * Accepts pre-defined names + * Add optional `trust` argument to `proxyaddr.all` to + stop at first untrusted + * Add `proxyaddr.compile` to pre-compile `trust` function + to make subsequent calls faster + +0.0.1 / 2014-05-04 +================== + + * Fix bad npm publish + +0.0.0 / 2014-05-04 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/LICENSE b/5-2/service/node_modules/express/node_modules/proxy-addr/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/README.md b/5-2/service/node_modules/express/node_modules/proxy-addr/README.md new file mode 100644 index 0000000..26f7fc0 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/README.md @@ -0,0 +1,137 @@ +# proxy-addr + +[![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] + +Determine address of proxied request + +## Install + +```sh +$ npm install proxy-addr +``` + +## API + +```js +var proxyaddr = require('proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + +```js +proxyaddr(req, function(addr){ return addr === '127.0.0.1' }) +proxyaddr(req, function(addr, i){ return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +proxyaddr(req, ['fe80::/ffc0::']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + +```js +var trust = proxyaddr.compile('localhost') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master +[downloads-image]: https://img.shields.io/npm/dm/proxy-addr.svg +[downloads-url]: https://npmjs.org/package/proxy-addr diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/index.js b/5-2/service/node_modules/express/node_modules/proxy-addr/index.js new file mode 100644 index 0000000..3200efb --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/index.js @@ -0,0 +1,347 @@ +/*! + * proxy-addr + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = proxyaddr; +module.exports.all = alladdrs; +module.exports.compile = compile; + +/** + * Module dependencies. + */ + +var forwarded = require('forwarded'); +var ipaddr = require('ipaddr.js'); + +/** + * Variables. + */ + +var digitre = /^[0-9]+$/; +var isip = ipaddr.isValid; +var parseip = ipaddr.parse; + +/** + * Pre-defined IP ranges. + */ + +var ipranges = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +}; + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @api public + */ + +function alladdrs(req, trust) { + // get addresses + var addrs = forwarded(req); + + if (!trust) { + // Return all addresses + return addrs; + } + + if (typeof trust !== 'function') { + trust = compile(trust); + } + + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue; + + addrs.length = i + 1; + } + + return addrs; +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @api private + */ + +function compile(val) { + if (!val) { + throw new TypeError('argument is required'); + } + + var trust = typeof val === 'string' + ? [val] + : val; + + if (!Array.isArray(trust)) { + throw new TypeError('unsupported trust argument'); + } + + for (var i = 0; i < trust.length; i++) { + val = trust[i]; + + if (!ipranges.hasOwnProperty(val)) { + continue; + } + + // Splice in pre-defined range + val = ipranges[val]; + trust.splice.apply(trust, [i, 1].concat(val)); + i += val.length - 1; + } + + return compileTrust(compileRangeSubnets(trust)); +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @api private + */ + +function compileRangeSubnets(arr) { + var rangeSubnets = new Array(arr.length); + + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]); + } + + return rangeSubnets; +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @api private + */ + +function compileTrust(rangeSubnets) { + // Return optimized function based on length + var len = rangeSubnets.length; + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets); +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @api private + */ + +function parseipNotation(note) { + var ip; + var kind; + var max; + var pos = note.lastIndexOf('/'); + var range; + + ip = pos !== -1 + ? note.substring(0, pos) + : note; + + if (!isip(ip)) { + throw new TypeError('invalid IP address: ' + ip); + } + + ip = parseip(ip); + + kind = ip.kind(); + max = kind === 'ipv6' + ? 128 + : 32; + + range = pos !== -1 + ? note.substring(pos + 1, note.length) + : max; + + if (typeof range !== 'number') { + range = digitre.test(range) + ? parseInt(range, 10) + : isip(range) + ? parseNetmask(range) + : 0; + } + + if (ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address(); + range = range <= max + ? range - 96 + : range; + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note); + } + + return [ip, range]; +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} note + * @api private + */ + +function parseNetmask(netmask) { + var ip = parseip(netmask); + var parts; + var size; + + switch (ip.kind()) { + case 'ipv4': + parts = ip.octets; + size = 8; + break; + case 'ipv6': + parts = ip.parts; + size = 16; + break; + } + + var max = Math.pow(2, size) - 1; + var part; + var range = 0; + + for (var i = 0; i < parts.length; i++) { + part = parts[i] & max; + + if (part === max) { + range += size; + continue; + } + + while (part) { + part = (part << 1) & max; + range += 1; + } + + break; + } + + return range; +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @api public + */ + +function proxyaddr(req, trust) { + if (!req) { + throw new TypeError('req argument is required'); + } + + if (!trust) { + throw new TypeError('trust argument is required'); + } + + var addrs = alladdrs(req, trust); + var addr = addrs[addrs.length - 1]; + + return addr; +} + +/** + * Static trust function to trust nothing. + * + * @api private + */ + +function trustNone() { + return false; +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @api private + */ + +function trustMulti(subnets) { + return function trust(addr) { + if (!isip(addr)) return false; + + var ip = parseip(addr); + var ipv4; + var kind = ip.kind(); + var subnet; + var subnetip; + var subnetkind; + var subnetrange; + var trusted; + + for (var i = 0; i < subnets.length; i++) { + subnet = subnets[i]; + subnetip = subnet[0]; + subnetkind = subnetip.kind(); + subnetrange = subnet[1]; + trusted = ip; + + if (kind !== subnetkind) { + if (kind !== 'ipv6' || subnetkind !== 'ipv4' || !ip.isIPv4MappedAddress()) { + continue; + } + + // Store addr as IPv4 + ipv4 = ipv4 || ip.toIPv4Address(); + trusted = ipv4; + } + + if (trusted.match(subnetip, subnetrange)) return true; + } + + return false; + }; +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @api private + */ + +function trustSingle(subnet) { + var subnetip = subnet[0]; + var subnetkind = subnetip.kind(); + var subnetisipv4 = subnetkind === 'ipv4'; + var subnetrange = subnet[1]; + + return function trust(addr) { + if (!isip(addr)) return false; + + var ip = parseip(addr); + var kind = ip.kind(); + + return kind === subnetkind + ? ip.match(subnetip, subnetrange) + : subnetisipv4 && kind === 'ipv6' && ip.isIPv4MappedAddress() + ? ip.toIPv4Address().match(subnetip, subnetrange) + : false; + }; +} diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md new file mode 100644 index 0000000..97fa1d1 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md @@ -0,0 +1,4 @@ +0.1.0 / 2014-09-21 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md new file mode 100644 index 0000000..2b4988f --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md @@ -0,0 +1,53 @@ +# forwarded + +[![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] + +Parse HTTP X-Forwarded-For header + +## Installation + +```sh +$ npm install forwarded +``` + +## API + +```js +var forwarded = require('forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`. In reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/forwarded.svg?style=flat +[npm-url]: https://npmjs.org/package/forwarded +[node-version-image]: https://img.shields.io/node/v/forwarded.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/forwarded.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/forwarded +[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master +[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg?style=flat +[downloads-url]: https://npmjs.org/package/forwarded diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js new file mode 100644 index 0000000..2f5c340 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js @@ -0,0 +1,35 @@ +/*! + * forwarded + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {Object} req + * @api public + */ + +function forwarded(req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = (req.headers['x-forwarded-for'] || '') + .split(/ *, */) + .filter(Boolean) + .reverse() + var socketAddr = req.connection.remoteAddress + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json new file mode 100644 index 0000000..7d24004 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json @@ -0,0 +1,65 @@ +{ + "name": "forwarded", + "description": "Parse HTTP X-Forwarded-For header", + "version": "0.1.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "x-forwarded-for", + "http", + "req" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/forwarded.git" + }, + "devDependencies": { + "istanbul": "0.3.2", + "mocha": "~1.21.4" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "e9a9faeb3cfaadf40eb57d144fff26bca9b818e8", + "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 <0.2.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", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore new file mode 100644 index 0000000..7a1537b --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore @@ -0,0 +1,2 @@ +.idea +node_modules diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml new file mode 100644 index 0000000..aa3d14a --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml @@ -0,0 +1,10 @@ +language: node_js + +node_js: + - "0.10" + - "0.11" + - "0.12" + - "4.0" + - "4.1" + - "4.2" + - "5" diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile new file mode 100644 index 0000000..7fd355a --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile @@ -0,0 +1,18 @@ +fs = require 'fs' +CoffeeScript = require 'coffee-script' +nodeunit = require 'nodeunit' +UglifyJS = require 'uglify-js' + +task 'build', 'build the JavaScript files from CoffeeScript source', build = (cb) -> + source = fs.readFileSync 'src/ipaddr.coffee' + fs.writeFileSync 'lib/ipaddr.js', CoffeeScript.compile source.toString() + + invoke 'test' + invoke 'compress' + +task 'test', 'run the bundled tests', (cb) -> + nodeunit.reporters.default.run ['test'] + +task 'compress', 'uglify the resulting javascript', (cb) -> + result = UglifyJS.minify('lib/ipaddr.js') + fs.writeFileSync('ipaddr.min.js', result.code) diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE new file mode 100644 index 0000000..3493f0d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011 Peter Zotov + +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/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md new file mode 100644 index 0000000..f4f8776 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md @@ -0,0 +1,161 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +var ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and +`ipaddr.process`. All of them receive a string as a single parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 couterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. +Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); +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"` +(the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with both +IPv6 and IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +var rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "he.net" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. +(Actually, JavaScript mostly does not know about byte buffers. They are emulated with +arrays of numbers, each in range of 0..255.) + +```js +var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them +have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address +for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with +the `::` substitution); the `toNormalizedString()` method will return an address where +all zeroes are explicit. + +For example: + +```js +var addr = ipaddr.parse("2001:0db8::0001"); +addr.toString(); // => "2001:db8::1" +addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +var addr = ipaddr.parse("192.168.1.1"); +addr.octets // => [192, 168, 1, 1] +``` diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json new file mode 100644 index 0000000..bc04ffe --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json @@ -0,0 +1,29 @@ +{ + "name": "ipaddr.js", + "version": "1.0.5", + "homepage": "https://github.com/whitequark/ipaddr.js", + "authors": [ + "whitequark " + ], + "description": "IP address manipulation library in JavaScript (CoffeeScript, actually)", + "main": "lib/ipaddr.js", + "moduleType": [ + "globals", + "node" + ], + "keywords": [ + "javscript", + "ip", + "address", + "ipv4", + "ipv6" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 0000000..ee5179d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.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),r[i]>>o!==t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(e in t)for(i=t[e],!i[0]||i[0]instanceof Array||(i=[i]),a=0,s=i.length;s>a;a++)if(o=i[a],r.match.apply(r,o))return e;return n},t.IPv4=function(){function r(r){var t,n,e;if(4!==r.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(n=0,e=r.length;e>n;n++)if(t=r[n],!(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 n;if(void 0===t&&(n=r,r=n[0],t=n[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}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(o=t.slice(1,6),a=[],r=0,e=o.length;e>r;r++)i=o[r],a.push(n(i));return a}();if(t=r.match(e.longValue)){if(a=n(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,n,e;if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8");for(n=0,e=r.length;e>n;n++)if(t=r[n],!(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,n,e,i,o,a;for(i=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),r=[],n=function(t){return r.push(t)},e=0,o=0,a=i.length;a>o;o++)switch(t=i[o],e){case 0:n("0"===t?"":t),e=1;break;case 1:"0"===t?e=2:n(t);break;case 2:"0"!==t&&(n(""),n(t),e=3);break;case 3:n(t)}return 2===e&&(n(""),n("")),r.join(":")},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],i=this.parts,n=0,e=i.length;e>n;n++)t=i[n],r.push(t>>8),r.push(255&t);return r},r.prototype.toNormalizedString=function(){var r;return 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).join(":")},r.prototype.match=function(r,t){var n;if(void 0===t&&(n=r,r=n[0],t=n[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,n,e;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=this.parts.slice(-2),r=e[0],n=e[1],new t.IPv4([r>>8,255&r,n>>8,255&n])},r}(),i="(?:[0-9a-f]+::?)+",o={"native":new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+(""+n+"\\."+n+"\\."+n+"\\."+n+"$"),"i")},r=function(r,t){var n,e,i,o,a;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for(n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(a=t-n,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,n,e,o;for(e=r.split(":"),o=[],t=0,n=e.length;n>t;t++)i=e[t],o.push(parseInt(i,16));return o}()},t.IPv6.parser=function(t){var n,e;return t.match(o["native"])?r(t,8):(n=t.match(o.transitional))&&(e=r(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},t.IPv4.isIPv4=t.IPv6.isIPv6=function(r){return null!==this.parser(r)},t.IPv4.isValid=function(r){var t;try{return new this(this.parser(r)),!0}catch(n){return t=n,!1}},t.IPv6.isValid=function(r){var t;if("string"==typeof r&&-1===r.indexOf(":"))return!1;try{return new this(this.parser(r)),!0}catch(n){return t=n,!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=function(r){var t,n;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&32>=t))return[this.parse(n[1]),t];throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv6.parseCIDR=function(r){var t,n;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&128>=t))return[this.parse(n[1]),t];throw new Error("ipaddr: string is not formatted like an IPv6 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 n;try{return t.IPv6.parseCIDR(r)}catch(e){n=e;try{return t.IPv4.parseCIDR(r)}catch(e){throw n=e,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/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js new file mode 100644 index 0000000..ef179b4 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js @@ -0,0 +1,467 @@ +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root; + + ipaddr = {}; + + root = this; + + if ((typeof module !== "undefined" && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } + + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var rangeName, rangeSubnets, subnet, _i, _len; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (_i = 0, _len = rangeSubnets.length; _i < _len; _i++) { + subnet = rangeSubnets[_i]; + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + return defaultName; + }; + + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var octet, _i, _len; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (_i = 0, _len = octets.length; _i < _len; _i++) { + octet = octets[_i]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet is a byte"); + } + } + this.octets = octets; + } + + IPv4.prototype.kind = function() { + return 'ipv4'; + }; + + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + + 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"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; + + return IPv4; + + })(); + + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; + + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var _i, _len, _ref, _results; + _ref = match.slice(1, 6); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(parseIntAuto(part)); + } + return _results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var _i, _results; + _results = []; + for (shift = _i = 0; _i <= 24; shift = _i += 8) { + _results.push((value >> shift) & 0xff); + } + return _results; + })()).reverse(); + } else { + return null; + } + }; + + ipaddr.IPv6 = (function() { + function IPv6(parts) { + var part, _i, _len; + if (parts.length !== 8) { + throw new Error("ipaddr: ipv6 part count should be 8"); + } + for (_i = 0, _len = parts.length; _i < _len; _i++) { + part = parts[_i]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit to two octets"); + } + } + this.parts = parts; + } + + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + + IPv6.prototype.toString = function() { + var compactStringParts, part, pushPart, state, stringParts, _i, _len; + stringParts = (function() { + var _i, _len, _ref, _results; + _ref = this.parts; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(part.toString(16)); + } + return _results; + }).call(this); + compactStringParts = []; + pushPart = function(part) { + return compactStringParts.push(part); + }; + state = 0; + for (_i = 0, _len = stringParts.length; _i < _len; _i++) { + part = stringParts[_i]; + switch (state) { + case 0: + if (part === '0') { + pushPart(''); + } else { + pushPart(part); + } + state = 1; + break; + case 1: + if (part === '0') { + state = 2; + } else { + pushPart(part); + } + break; + case 2: + if (part !== '0') { + pushPart(''); + pushPart(part); + state = 3; + } + break; + case 3: + pushPart(part); + } + } + if (state === 2) { + pushPart(''); + pushPart(''); + } + return compactStringParts.join(":"); + }; + + IPv6.prototype.toByteArray = function() { + var bytes, part, _i, _len, _ref; + bytes = []; + _ref = this.parts; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; + + IPv6.prototype.toNormalizedString = function() { + var part; + return ((function() { + var _i, _len, _ref, _results; + _ref = this.parts; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(part.toString(16)); + } + return _results; + }).call(this)).join(":"); + }; + + 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"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; + + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; + + IPv6.prototype.toIPv4Address = function() { + var high, low, _ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + _ref = this.parts.slice(-2), high = _ref[0], low = _ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + return IPv6; + + })(); + + ipv6Part = "(?:[0-9a-f]+::?)+"; + + ipv6Regexes = { + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + ("" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$"), 'i') + }; + + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + return (function() { + var _i, _len, _ref, _results; + _ref = string.split(":"); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(parseInt(part, 16)); + } + return _results; + })(); + }; + + ipaddr.IPv6.parser = function(string) { + var match, parts; + if (string.match(ipv6Regexes['native'])) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + parts = expandIPv6(match[1].slice(0, -1), 6); + if (parts) { + parts.push(parseInt(match[2]) << 8 | parseInt(match[3])); + parts.push(parseInt(match[4]) << 8 | parseInt(match[5])); + return parts; + } + } + return null; + }; + + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (_error) { + e = _error; + return false; + } + }; + + ipaddr.IPv6.isValid = function(string) { + var e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + new this(this.parser(string)); + return true; + } catch (_error) { + e = _error; + return false; + } + }; + + ipaddr.IPv4.parse = ipaddr.IPv6.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + return [this.parse(match[1]), maskLength]; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + return [this.parse(match[1]), maskLength]; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + + 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); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + +}).call(this); diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json new file mode 100644 index 0000000..6b61f32 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json @@ -0,0 +1,60 @@ +{ + "name": "ipaddr.js", + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "version": "1.0.5", + "author": { + "name": "whitequark", + "email": "whitequark@whitequark.org" + }, + "directories": { + "lib": "./lib" + }, + "dependencies": {}, + "devDependencies": { + "coffee-script": "~1.6", + "nodeunit": ">=0.8.2 <0.8.7", + "uglify-js": "latest" + }, + "scripts": { + "test": "cake build test" + }, + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "repository": { + "type": "git", + "url": "git://github.com/whitequark/ipaddr.js.git" + }, + "main": "./lib/ipaddr", + "engines": { + "node": ">= 0.10" + }, + "license": "MIT", + "gitHead": "46438c8bfa187505b7007a277f09a4a9e73d5686", + "bugs": { + "url": "https://github.com/whitequark/ipaddr.js/issues" + }, + "_id": "ipaddr.js@1.0.5", + "_shasum": "5fa78cf301b825c78abc3042d812723049ea23c7", + "_from": "ipaddr.js@1.0.5", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "whitequark", + "email": "whitequark@whitequark.org" + }, + "maintainers": [ + { + "name": "whitequark", + "email": "whitequark@whitequark.org" + } + ], + "dist": { + "shasum": "5fa78cf301b825c78abc3042d812723049ea23c7", + "tarball": "http://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.0.5.tgz" + }, + "_resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.0.5.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/whitequark/ipaddr.js#readme" +} diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee new file mode 100644 index 0000000..550174f --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee @@ -0,0 +1,396 @@ +# Define the main object +ipaddr = {} + +root = this + +# Export for both the CommonJS and browser-like environment +if module? && module.exports + module.exports = ipaddr +else + root['ipaddr'] = ipaddr + +# A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher. +matchCIDR = (first, second, partSize, cidrBits) -> + if first.length != second.length + throw new Error "ipaddr: cannot match CIDR for objects with different lengths" + + part = 0 + while cidrBits > 0 + shift = partSize - cidrBits + shift = 0 if shift < 0 + + if first[part] >> shift != second[part] >> shift + return false + + cidrBits -= partSize + part += 1 + + return true + +# An utility function to ease named range matching. See examples below. +ipaddr.subnetMatch = (address, rangeList, defaultName='unicast') -> + for rangeName, rangeSubnets of rangeList + # ECMA5 Array.isArray isn't available everywhere + if rangeSubnets[0] && !(rangeSubnets[0] instanceof Array) + rangeSubnets = [ rangeSubnets ] + + for subnet in rangeSubnets + return rangeName if address.match.apply(address, subnet) + + return defaultName + +# An IPv4 address (RFC791). +class ipaddr.IPv4 + # Constructs a new IPv4 address from an array of four octets. + # Verifies the input. + constructor: (octets) -> + if octets.length != 4 + throw new Error "ipaddr: ipv4 octet count should be 4" + + for octet in octets + if !(0 <= octet <= 255) + throw new Error "ipaddr: ipv4 octet is a byte" + + @octets = octets + + # The 'kind' method exists on both IPv4 and IPv6 classes. + kind: -> + return 'ipv4' + + # Returns the address in convenient, decimal-dotted format. + toString: -> + return @octets.join "." + + # Returns an array of byte-sized values in network order + toByteArray: -> + return @octets.slice(0) # octets.clone + + # 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" + + return matchCIDR(this.octets, other.octets, 8, cidrRange) + + # Special IPv4 address ranges. + SpecialRanges: + unspecified: [ + [ new IPv4([0, 0, 0, 0]), 8 ] + ] + broadcast: [ + [ new IPv4([255, 255, 255, 255]), 32 ] + ] + multicast: [ # RFC3171 + [ new IPv4([224, 0, 0, 0]), 4 ] + ] + linkLocal: [ # RFC3927 + [ new IPv4([169, 254, 0, 0]), 16 ] + ] + loopback: [ # RFC5735 + [ new IPv4([127, 0, 0, 0]), 8 ] + ] + private: [ # RFC1918 + [ new IPv4([10, 0, 0, 0]), 8 ] + [ new IPv4([172, 16, 0, 0]), 12 ] + [ new IPv4([192, 168, 0, 0]), 16 ] + ] + reserved: [ # Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700 + [ new IPv4([192, 0, 0, 0]), 24 ] + [ new IPv4([192, 0, 2, 0]), 24 ] + [ new IPv4([192, 88, 99, 0]), 24 ] + [ new IPv4([198, 51, 100, 0]), 24 ] + [ new IPv4([203, 0, 113, 0]), 24 ] + [ new IPv4([240, 0, 0, 0]), 4 ] + ] + + # Checks if the address corresponds to one of the special ranges. + range: -> + return ipaddr.subnetMatch(this, @SpecialRanges) + + # Convrets this IPv4 address to an IPv4-mapped IPv6 address. + toIPv4MappedAddress: -> + return ipaddr.IPv6.parse "::ffff:#{@toString()}" + +# A list of regular expressions that match arbitrary IPv4 addresses, +# for which a number of weird notations exist. +# Note that an address like 0010.0xa5.1.1 is considered legal. +ipv4Part = "(0?\\d+|0x[a-f0-9]+)" +ipv4Regexes = + fourOctet: new RegExp "^#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' + longValue: new RegExp "^#{ipv4Part}$", 'i' + +# Classful variants (like a.b, where a is an octet, and b is a 24-bit +# value representing last three octets; this corresponds to a class C +# address) are omitted due to classless nature of modern Internet. +ipaddr.IPv4.parser = (string) -> + parseIntAuto = (string) -> + if string[0] == "0" && string[1] != "x" + parseInt(string, 8) + else + parseInt(string) + + # parseInt recognizes all that octal & hexadecimal weirdness for us + if match = string.match(ipv4Regexes.fourOctet) + return (parseIntAuto(part) for part in match[1..5]) + else if match = string.match(ipv4Regexes.longValue) + value = parseIntAuto(match[1]) + if value > 0xffffffff || value < 0 + throw new Error "ipaddr: address outside defined range" + return ((value >> shift) & 0xff for shift in [0..24] by 8).reverse() + else + return null + +# An IPv6 address (RFC2460) +class ipaddr.IPv6 + # Constructs an IPv6 address from an array of eight 16-bit parts. + # Throws an error if the input is invalid. + constructor: (parts) -> + if parts.length != 8 + throw new Error "ipaddr: ipv6 part count should be 8" + + for part in parts + if !(0 <= part <= 0xffff) + throw new Error "ipaddr: ipv6 part should fit to two octets" + + @parts = parts + + # The 'kind' method exists on both IPv4 and IPv6 classes. + kind: -> + return 'ipv6' + + # Returns the address in compact, human-readable format like + # 2001:db8:8:66::1 + toString: -> + stringParts = (part.toString(16) for part in @parts) + + compactStringParts = [] + pushPart = (part) -> compactStringParts.push part + + state = 0 + for part in stringParts + switch state + when 0 + if part == '0' + pushPart('') + else + pushPart(part) + + state = 1 + when 1 + if part == '0' + state = 2 + else + pushPart(part) + when 2 + unless part == '0' + pushPart('') + pushPart(part) + state = 3 + when 3 + pushPart(part) + + if state == 2 + pushPart('') + pushPart('') + + return compactStringParts.join ":" + + # Returns an array of byte-sized values in network order + toByteArray: -> + bytes = [] + for part in @parts + bytes.push(part >> 8) + bytes.push(part & 0xff) + + return bytes + + # Returns the address in expanded format with all zeroes included, like + # 2001:db8:8:66:0:0:0:1 + toNormalizedString: -> + return (part.toString(16) for part in @parts).join ":" + + # 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" + + return matchCIDR(this.parts, other.parts, 16, cidrRange) + + # Special IPv6 ranges + SpecialRanges: + unspecified: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128 ] # RFC4291, here and after + linkLocal: [ new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10 ] + multicast: [ new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8 ] + loopback: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128 ] + uniqueLocal: [ new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7 ] + ipv4Mapped: [ new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96 ] + rfc6145: [ new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96 ] # RFC6145 + rfc6052: [ new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96 ] # RFC6052 + '6to4': [ new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16 ] # RFC3056 + teredo: [ new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32 ] # RFC6052, RFC6146 + reserved: [ + [ new IPv6([ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32 ] # RFC4291 + ] + + # Checks if the address corresponds to one of the special ranges. + range: -> + return ipaddr.subnetMatch(this, @SpecialRanges) + + # Checks if this address is an IPv4-mapped IPv6 address. + isIPv4MappedAddress: -> + return @range() == 'ipv4Mapped' + + # Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address. + # Throws an error otherwise. + toIPv4Address: -> + unless @isIPv4MappedAddress() + throw new Error "ipaddr: trying to convert a generic ipv6 address to ipv4" + + [high, low] = @parts[-2..-1] + + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]) + +# IPv6-matching regular expressions. +# For IPv6, the task is simpler: it is enough to match the colon-delimited +# hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at +# the end. +ipv6Part = "(?:[0-9a-f]+::?)+" +ipv6Regexes = + native: new RegExp "^(::)?(#{ipv6Part})?([0-9a-f]+)?(::)?$", 'i' + transitional: new RegExp "^((?:#{ipv6Part})|(?:::)(?:#{ipv6Part})?)" + + "#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' + +# Expand :: in an IPv6 address or address part consisting of `parts` groups. +expandIPv6 = (string, parts) -> + # More than one '::' means invalid adddress + if string.indexOf('::') != string.lastIndexOf('::') + return null + + # How many parts do we already have? + colonCount = 0 + lastColon = -1 + while (lastColon = string.indexOf(':', lastColon + 1)) >= 0 + colonCount++ + + # 0::0 is two parts more than :: + colonCount-- if string.substr(0, 2) == '::' + colonCount-- if string.substr(-2, 2) == '::' + + # The following loop would hang if colonCount > parts + if colonCount > parts + return null + + # replacement = ':' + '0:' * (parts - colonCount) + replacementCount = parts - colonCount + replacement = ':' + while replacementCount-- + replacement += '0:' + + # Insert the missing zeroes + string = string.replace('::', replacement) + + # Trim any garbage which may be hanging around if :: was at the edge in + # the source string + string = string[1..-1] if string[0] == ':' + string = string[0..-2] if string[string.length-1] == ':' + + return (parseInt(part, 16) for part in string.split(":")) + +# Parse an IPv6 address. +ipaddr.IPv6.parser = (string) -> + if string.match(ipv6Regexes['native']) + return expandIPv6(string, 8) + + else if match = string.match(ipv6Regexes['transitional']) + parts = expandIPv6(match[1][0..-2], 6) + if parts + parts.push(parseInt(match[2]) << 8 | parseInt(match[3])) + parts.push(parseInt(match[4]) << 8 | parseInt(match[5])) + return parts + + return null + +# Checks if a given string is formatted like IPv4/IPv6 address. +ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = (string) -> + return @parser(string) != null + +# Checks if a given string is a valid IPv4/IPv6 address. +ipaddr.IPv4.isValid = (string) -> + try + new this(@parser(string)) + return true + catch e + return false + +ipaddr.IPv6.isValid = (string) -> + # Since IPv6.isValid is always called first, this shortcut + # provides a substantial performance gain. + if typeof string == "string" and string.indexOf(":") == -1 + return false + + try + new this(@parser(string)) + return true + catch e + return false + +# Tries to parse and validate a string with IPv4/IPv6 address. +# Throws an error if it fails. +ipaddr.IPv4.parse = ipaddr.IPv6.parse = (string) -> + parts = @parser(string) + if parts == null + throw new Error "ipaddr: string is not formatted like ip address" + + return new this(parts) + +ipaddr.IPv4.parseCIDR = (string) -> + if match = string.match(/^(.+)\/(\d+)$/) + maskLength = parseInt(match[2]) + if maskLength >= 0 and maskLength <= 32 + return [@parse(match[1]), maskLength] + + throw new Error "ipaddr: string is not formatted like an IPv4 CIDR range" + +ipaddr.IPv6.parseCIDR = (string) -> + if match = string.match(/^(.+)\/(\d+)$/) + maskLength = parseInt(match[2]) + if maskLength >= 0 and maskLength <= 128 + return [@parse(match[1]), maskLength] + + throw new Error "ipaddr: string is not formatted like an IPv6 CIDR range" + +# Checks if the address is valid IP address +ipaddr.isValid = (string) -> + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string) + +# Try to parse an address and throw an error if it is impossible +ipaddr.parse = (string) -> + if ipaddr.IPv6.isValid(string) + return ipaddr.IPv6.parse(string) + else if ipaddr.IPv4.isValid(string) + return ipaddr.IPv4.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) + if addr.kind() == 'ipv6' && addr.isIPv4MappedAddress() + return addr.toIPv4Address() + else + return addr diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee new file mode 100644 index 0000000..17739e2 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee @@ -0,0 +1,282 @@ +ipaddr = require '../lib/ipaddr' + +module.exports = + 'should define main classes': (test) -> + test.ok(ipaddr.IPv4?, 'defines IPv4 class') + test.ok(ipaddr.IPv6?, 'defines IPv6 class') + test.done() + + 'can construct IPv4 from octets': (test) -> + test.doesNotThrow -> + new ipaddr.IPv4([192, 168, 1, 2]) + test.done() + + 'refuses to construct invalid IPv4': (test) -> + test.throws -> + new ipaddr.IPv4([300, 1, 2, 3]) + test.throws -> + new ipaddr.IPv4([8, 8, 8]) + test.done() + + 'converts IPv4 to string correctly': (test) -> + addr = new ipaddr.IPv4([192, 168, 1, 1]) + test.equal(addr.toString(), '192.168.1.1') + test.done() + + 'returns correct kind for IPv4': (test) -> + addr = new ipaddr.IPv4([1, 2, 3, 4]) + test.equal(addr.kind(), 'ipv4') + test.done() + + 'allows to access IPv4 octets': (test) -> + addr = new ipaddr.IPv4([42, 0, 0, 0]) + test.equal(addr.octets[0], 42) + test.done() + + 'checks IPv4 address format': (test) -> + test.equal(ipaddr.IPv4.isIPv4('192.168.007.0xa'), true) + test.equal(ipaddr.IPv4.isIPv4('1024.0.0.1'), true) + test.equal(ipaddr.IPv4.isIPv4('8.0xa.wtf.6'), false) + test.done() + + 'validates IPv4 addresses': (test) -> + test.equal(ipaddr.IPv4.isValid('192.168.007.0xa'), true) + test.equal(ipaddr.IPv4.isValid('1024.0.0.1'), false) + test.equal(ipaddr.IPv4.isValid('8.0xa.wtf.6'), false) + test.done() + + 'parses IPv4 in several weird formats': (test) -> + test.deepEqual(ipaddr.IPv4.parse('192.168.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('0xc0.168.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('192.0250.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('0xc0a80101').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('030052000401').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('3232235777').octets, [192, 168, 1, 1]) + test.done() + + 'barfs at invalid IPv4': (test) -> + test.throws -> + ipaddr.IPv4.parse('10.0.0.wtf') + test.done() + + 'matches IPv4 CIDR correctly': (test) -> + addr = new ipaddr.IPv4([10, 5, 0, 1]) + test.equal(addr.match(ipaddr.IPv4.parse('0.0.0.0'), 0), true) + test.equal(addr.match(ipaddr.IPv4.parse('11.0.0.0'), 8), false) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.0'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.1'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.10'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.5.5.0'), 16), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 16), false) + test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 15), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.5.0.2'), 32), false) + 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.throws -> + ipaddr.IPv4.parseCIDR('0.0.0.0/-1') + test.throws -> + ipaddr.IPv4.parseCIDR('0.0.0.0/33') + 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') + test.equal(ipaddr.IPv4.parse('10.1.0.1').range(), 'private') + test.equal(ipaddr.IPv4.parse('192.168.2.1').range(), 'private') + test.equal(ipaddr.IPv4.parse('224.100.0.1').range(), 'multicast') + test.equal(ipaddr.IPv4.parse('169.254.15.0').range(), 'linkLocal') + test.equal(ipaddr.IPv4.parse('127.1.1.1').range(), 'loopback') + test.equal(ipaddr.IPv4.parse('255.255.255.255').range(), 'broadcast') + test.equal(ipaddr.IPv4.parse('240.1.2.3').range(), 'reserved') + test.equal(ipaddr.IPv4.parse('8.8.8.8').range(), 'unicast') + test.done() + + 'can construct IPv6 from parts': (test) -> + test.doesNotThrow -> + new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.done() + + 'refuses to construct invalid IPv6': (test) -> + test.throws -> + new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 0, 1]) + test.throws -> + new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 1]) + test.done() + + 'converts IPv6 to string correctly': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.equal(addr.toNormalizedString(), '2001:db8:f53a:0:0:0:0:1') + test.equal(addr.toString(), '2001:db8:f53a::1') + test.equal(new ipaddr.IPv6([0, 0, 0, 0, 0, 0, 0, 1]).toString(), '::1') + test.equal(new ipaddr.IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]).toString(), '2001:db8::') + test.done() + + 'returns correct kind for IPv6': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.equal(addr.kind(), 'ipv6') + test.done() + + 'allows to access IPv6 address parts': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 42, 0, 1]) + test.equal(addr.parts[5], 42) + test.done() + + 'checks IPv6 address format': (test) -> + test.equal(ipaddr.IPv6.isIPv6('2001:db8:F53A::1'), true) + test.equal(ipaddr.IPv6.isIPv6('200001::1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:192.168.1.1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1:0'), false) + test.equal(ipaddr.IPv6.isIPv6('fe80::wtf'), false) + test.done() + + 'validates IPv6 addresses': (test) -> + test.equal(ipaddr.IPv6.isValid('2001:db8:F53A::1'), true) + test.equal(ipaddr.IPv6.isValid('200001::1'), false) + test.equal(ipaddr.IPv6.isValid('::ffff:192.168.1.1'), true) + test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1'), false) + test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1:0'), false) + test.equal(ipaddr.IPv6.isValid('2001:db8::F53A::1'), false) + test.equal(ipaddr.IPv6.isValid('fe80::wtf'), false) + test.equal(ipaddr.IPv6.isValid('2002::2:'), false) + test.equal(ipaddr.IPv6.isValid(undefined), false) + test.done() + + 'parses IPv6 in different formats': (test) -> + test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A:0:0:0:0:1').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.deepEqual(ipaddr.IPv6.parse('fe80::10').parts, [0xfe80, 0, 0, 0, 0, 0, 0, 0x10]) + test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A::').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 0]) + test.deepEqual(ipaddr.IPv6.parse('::1').parts, [0, 0, 0, 0, 0, 0, 0, 1]) + test.deepEqual(ipaddr.IPv6.parse('::').parts, [0, 0, 0, 0, 0, 0, 0, 0]) + test.done() + + 'barfs at invalid IPv6': (test) -> + test.throws -> + ipaddr.IPv6.parse('fe80::0::1') + test.done() + + 'matches IPv6 CIDR correctly': (test) -> + addr = ipaddr.IPv6.parse('2001:db8:f53a::1') + test.equal(addr.match(ipaddr.IPv6.parse('::'), 0), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53a::1:1'), 64), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53b::1:1'), 48), false) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f531::1:1'), 44), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f500::1'), 40), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db9:f500::1'), 40), false) + 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.throws -> + ipaddr.IPv6.parseCIDR('2001:db8:f53a::1/-1') + test.throws -> + ipaddr.IPv6.parseCIDR('2001:db8:f53a::1/129') + test.done() + + 'converts between IPv4-mapped IPv6 addresses and IPv4 addresses': (test) -> + addr = ipaddr.IPv4.parse('77.88.21.11') + mapped = addr.toIPv4MappedAddress() + test.deepEqual(mapped.parts, [0, 0, 0, 0, 0, 0xffff, 0x4d58, 0x150b]) + test.deepEqual(mapped.toIPv4Address().octets, addr.octets) + test.done() + + 'refuses to convert non-IPv4-mapped IPv6 address to IPv4 address': (test) -> + test.throws -> + ipaddr.IPv6.parse('2001:db8::1').toIPv4Address() + test.done() + + 'detects reserved IPv6 networks': (test) -> + test.equal(ipaddr.IPv6.parse('::').range(), 'unspecified') + test.equal(ipaddr.IPv6.parse('fe80::1234:5678:abcd:0123').range(), 'linkLocal') + test.equal(ipaddr.IPv6.parse('ff00::1234').range(), 'multicast') + test.equal(ipaddr.IPv6.parse('::1').range(), 'loopback') + test.equal(ipaddr.IPv6.parse('fc00::').range(), 'uniqueLocal') + test.equal(ipaddr.IPv6.parse('::ffff:192.168.1.10').range(), 'ipv4Mapped') + test.equal(ipaddr.IPv6.parse('::ffff:0:192.168.1.10').range(), 'rfc6145') + test.equal(ipaddr.IPv6.parse('64:ff9b::1234').range(), 'rfc6052') + test.equal(ipaddr.IPv6.parse('2002:1f63:45e8::1').range(), '6to4') + test.equal(ipaddr.IPv6.parse('2001::4242').range(), 'teredo') + test.equal(ipaddr.IPv6.parse('2001:db8::3210').range(), 'reserved') + test.equal(ipaddr.IPv6.parse('2001:470:8:66::1').range(), 'unicast') + test.done() + + 'is able to determine IP address type': (test) -> + test.equal(ipaddr.parse('8.8.8.8').kind(), 'ipv4') + test.equal(ipaddr.parse('2001:db8:3312::1').kind(), 'ipv6') + test.done() + + 'throws an error if tried to parse an invalid address': (test) -> + test.throws -> + ipaddr.parse('::some.nonsense') + test.done() + + 'correctly processes IPv4-mapped addresses': (test) -> + test.equal(ipaddr.process('8.8.8.8').kind(), 'ipv4') + test.equal(ipaddr.process('2001:db8:3312::1').kind(), 'ipv6') + test.equal(ipaddr.process('::ffff:192.168.1.1').kind(), 'ipv4') + test.done() + + 'correctly converts IPv6 and IPv4 addresses to byte arrays': (test) -> + test.deepEqual(ipaddr.parse('1.2.3.4').toByteArray(), + [0x1, 0x2, 0x3, 0x4]); + # Fuck yeah. The first byte of Google's IPv6 address is 42. 42! + test.deepEqual(ipaddr.parse('2a00:1450:8007::68').toByteArray(), + [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68 ]) + test.done() + + 'correctly parses 1 as an IPv4 address': (test) -> + test.equal(ipaddr.IPv6.isValid('1'), false) + test.equal(ipaddr.IPv4.isValid('1'), true) + 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) + test.done() + + 'does not hang on ::8:8:8:8:8:8:8:8:8': (test) -> + test.equal(ipaddr.IPv6.isValid('::8:8:8:8:8:8:8:8:8'), false) + test.done() + + 'subnetMatch does not fail on empty range': (test) -> + ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {}, false) + ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {subnet: []}, false) + test.done() + + 'subnetMatch returns default subnet on empty range': (test) -> + test.equal(ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {}, false), false) + test.equal(ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {subnet: []}, false), false) + test.done() diff --git a/5-2/service/node_modules/express/node_modules/proxy-addr/package.json b/5-2/service/node_modules/express/node_modules/proxy-addr/package.json new file mode 100644 index 0000000..04af756 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/proxy-addr/package.json @@ -0,0 +1,90 @@ +{ + "name": "proxy-addr", + "description": "Determine address of proxied request", + "version": "1.0.10", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/proxy-addr.git" + }, + "dependencies": { + "forwarded": "~0.1.0", + "ipaddr.js": "1.0.5" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "0cdb6444100a7930285ed2555d0c3c687690a7a5", + "bugs": { + "url": "https://github.com/jshttp/proxy-addr/issues" + }, + "homepage": "https://github.com/jshttp/proxy-addr", + "_id": "proxy-addr@1.0.10", + "_shasum": "0d40a82f801fc355567d2ecb65efe3f077f121c5", + "_from": "proxy-addr@>=1.0.10 <1.1.0", + "_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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "0d40a82f801fc355567d2ecb65efe3f077f121c5", + "tarball": "http://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.10.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.10.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/qs/.eslintignore b/5-2/service/node_modules/express/node_modules/qs/.eslintignore new file mode 100644 index 0000000..1521c8b --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/.eslintignore @@ -0,0 +1 @@ +dist diff --git a/5-2/service/node_modules/express/node_modules/qs/.npmignore b/5-2/service/node_modules/express/node_modules/qs/.npmignore new file mode 100644 index 0000000..2abba8d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/.npmignore @@ -0,0 +1,19 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov +complexity.md +dist diff --git a/5-2/service/node_modules/express/node_modules/qs/.travis.yml b/5-2/service/node_modules/express/node_modules/qs/.travis.yml new file mode 100644 index 0000000..f502178 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/.travis.yml @@ -0,0 +1,6 @@ +language: node_js + +node_js: + - 0.10 + - 0.12 + - iojs diff --git a/5-2/service/node_modules/express/node_modules/qs/CHANGELOG.md b/5-2/service/node_modules/express/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000..1fadc78 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/CHANGELOG.md @@ -0,0 +1,88 @@ + +## [**3.1.0**](https://github.com/hapijs/qs/issues?milestone=24&state=open) +- [**#89**](https://github.com/hapijs/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/hapijs/qs/issues?milestone=23&state=closed) +- [**#77**](https://github.com/hapijs/qs/issues/77) Perf boost +- [**#60**](https://github.com/hapijs/qs/issues/60) Add explicit option to disable array parsing +- [**#80**](https://github.com/hapijs/qs/issues/80) qs.parse silently drops properties +- [**#74**](https://github.com/hapijs/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/hapijs/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/hapijs/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/hapijs/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/hapijs/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/hapijs/qs/issues/85) No equal sign +- [**#84**](https://github.com/hapijs/qs/issues/84) update license attribute + +## [**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". + +## [**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 + +## [**2.2.5**](https://github.com/hapijs/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/hapijs/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/hapijs/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/hapijs/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/hapijs/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/hapijs/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/hapijs/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/hapijs/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/hapijs/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/hapijs/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/hapijs/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/hapijs/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/hapijs/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/hapijs/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/hapijs/qs/issues/32) account for circular references properly, closes #31 +- [**#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 +- [**#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 +- [**#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) +- [**#22**](https://github.com/hapijs/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/hapijs/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/hapijs/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/hapijs/qs/issues/20) Configurable parametersLimit +- [**#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 + +## [**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 +- [**#15**](https://github.com/hapijs/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/hapijs/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/hapijs/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/hapijs/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/hapijs/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/hapijs/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/hapijs/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/hapijs/qs/issues/6) Minor grammar fix in README + +## [**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/5-2/service/node_modules/express/node_modules/qs/CONTRIBUTING.md b/5-2/service/node_modules/express/node_modules/qs/CONTRIBUTING.md new file mode 100644 index 0000000..8928361 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/CONTRIBUTING.md @@ -0,0 +1 @@ +Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md). diff --git a/5-2/service/node_modules/express/node_modules/qs/LICENSE b/5-2/service/node_modules/express/node_modules/qs/LICENSE new file mode 100644 index 0000000..d456948 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/5-2/service/node_modules/express/node_modules/qs/README.md b/5-2/service/node_modules/express/node_modules/qs/README.md new file mode 100644 index 0000000..48a0de9 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/README.md @@ -0,0 +1,317 @@ +# qs + +A querystring parsing and stringifying library with some added security. + +[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs) + +Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var Qs = require('qs'); + +var obj = Qs.parse('a=c'); // { a: 'c' } +var str = Qs.stringify(obj); // 'a=c' +``` + +### Parsing Objects + +```javascript +Qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`, or prefixing the sub-key with a dot `.`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +{ + foo: { + bar: 'baz' + } +} +``` + +When using the `plainObjects` option the parsed value is returned as a plain object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +Qs.parse('a.hasOwnProperty=b', { plainObjects: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. + +```javascript +Qs.parse('a.hasOwnProperty=b', { allowPrototypes: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +URI encoded strings work too: + +```javascript +Qs.parse('a%5Bb%5D=c'); +// { a: { b: 'c' } } +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +{ + foo: { + bar: { + baz: 'foobarbaz' + } + } +} +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +{ + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +} +``` + +This depth can be overridden by passing a `depth` option to `Qs.parse(string, [options])`: + +```javascript +Qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } } +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +Qs.parse('a=b&c=d', { parameterLimit: 1 }); +// { a: 'b' } +``` + +An optional delimiter can also be passed: + +```javascript +Qs.parse('a=b;c=d', { delimiter: ';' }); +// { a: 'b', c: 'd' } +``` + +Delimiters can be a regular expression too: + +```javascript +Qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +// { a: 'b', c: 'd', e: 'f' } +``` + +Option `allowDots` can be used to disable dot notation: + +```javascript +Qs.parse('a.b=c', { allowDots: false }); +// { 'a.b': 'c' } } +``` + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +Qs.parse('a[]=b&a[]=c'); +// { a: ['b', 'c'] } +``` + +You may specify an index as well: + +```javascript +Qs.parse('a[1]=c&a[0]=b'); +// { a: ['b', 'c'] } +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +Qs.parse('a[1]=b&a[15]=c'); +// { a: ['b', 'c'] } +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +Qs.parse('a[]=&a[]=b'); +// { a: ['', 'b'] } +Qs.parse('a[0]=b&a[1]=&a[2]=c'); +// { a: ['b', '', 'c'] } +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key: + +```javascript +Qs.parse('a[100]=b'); +// { a: { '100': 'b' } } +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +Qs.parse('a[1]=b', { arrayLimit: 0 }); +// { a: { '1': 'b' } } +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +Qs.parse('a[]=b', { parseArrays: false }); +// { a: { '0': 'b' } } +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +Qs.parse('a[0]=b&a[b]=c'); +// { a: { '0': 'b', b: 'c' } } +``` + +You can also create arrays of objects: + +```javascript +Qs.parse('a[][b]=c'); +// { a: [{ b: 'c' }] } +``` + +### Stringifying + +```javascript +Qs.stringify(object, [options]); +``` + +When stringifying, **qs** always URI encodes output. Objects are stringified as you would expect: + +```javascript +Qs.stringify({ a: 'b' }); +// 'a=b' +Qs.stringify({ a: { b: 'c' } }); +// 'a%5Bb%5D=c' +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +Qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +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 +Qs.stringify({ a: '' }); +// 'a=' +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +Qs.stringify({ a: null, b: undefined }); +// 'a=' +``` + +The delimiter may be overridden with stringify as well: + +```javascript +Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }); +// 'a=b;c=d' +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +Qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }) +// 'a=b&c=d&e[f]=123&e[g][0]=4' +Qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }) +// 'a=b&e=f' +Qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }) +// 'a[0]=b&a[2]=d' +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +Qs.stringify({ a: null, b: '' }); +// 'a=&b=' +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +Qs.parse('a&b=') +// { a: '', b: '' } +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +Qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +// 'a&b=' +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +Qs.parse('a&b=', { strictNullHandling: true }); +// { a: null, b: '' } + +``` diff --git a/5-2/service/node_modules/express/node_modules/qs/bower.json b/5-2/service/node_modules/express/node_modules/qs/bower.json new file mode 100644 index 0000000..ffd0641 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/bower.json @@ -0,0 +1,22 @@ +{ + "name": "qs", + "main": "dist/qs.js", + "version": "3.0.0", + "homepage": "https://github.com/hapijs/qs", + "authors": [ + "Nathan LaFreniere " + ], + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/5-2/service/node_modules/express/node_modules/qs/lib/index.js b/5-2/service/node_modules/express/node_modules/qs/lib/index.js new file mode 100644 index 0000000..0e09493 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/lib/index.js @@ -0,0 +1,15 @@ +// Load modules + +var Stringify = require('./stringify'); +var Parse = require('./parse'); + + +// Declare internals + +var internals = {}; + + +module.exports = { + stringify: Stringify, + parse: Parse +}; diff --git a/5-2/service/node_modules/express/node_modules/qs/lib/parse.js b/5-2/service/node_modules/express/node_modules/qs/lib/parse.js new file mode 100644 index 0000000..e7c56c5 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/lib/parse.js @@ -0,0 +1,186 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + depth: 5, + arrayLimit: 20, + parameterLimit: 1000, + strictNullHandling: false, + plainObjects: false, + allowPrototypes: false +}; + + +internals.parseValues = function (str, options) { + + var obj = {}; + var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); + + for (var i = 0, il = parts.length; i < il; ++i) { + var part = parts[i]; + var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; + + if (pos === -1) { + obj[Utils.decode(part)] = ''; + + if (options.strictNullHandling) { + obj[Utils.decode(part)] = null; + } + } + else { + var key = Utils.decode(part.slice(0, pos)); + var val = Utils.decode(part.slice(pos + 1)); + + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + obj[key] = val; + } + else { + obj[key] = [].concat(obj[key]).concat(val); + } + } + } + + return obj; +}; + + +internals.parseObject = function (chain, val, options) { + + if (!chain.length) { + return val; + } + + var root = chain.shift(); + + var obj; + if (root === '[]') { + obj = []; + obj = obj.concat(internals.parseObject(chain, val, options)); + } + else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; + var index = parseInt(cleanRoot, 10); + var indexString = '' + index; + if (!isNaN(index) && + root !== cleanRoot && + indexString === cleanRoot && + index >= 0 && + (options.parseArrays && + index <= options.arrayLimit)) { + + obj = []; + obj[index] = internals.parseObject(chain, val, options); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val, options); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, options) { + + if (!key) { + return; + } + + // Transform dot notation to bracket notation + + if (options.allowDots) { + key = key.replace(/\.([^\.\[]+)/g, '[$1]'); + } + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1])) { + + if (!options.allowPrototypes) { + return; + } + } + + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + + ++i; + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { + + if (!options.allowPrototypes) { + continue; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val, options); +}; + + +module.exports = function (str, options) { + + options = options || {}; + options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.allowDots = options.allowDots !== false; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : internals.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : internals.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var newObj = internals.parseKeys(key, tempObj[key], options); + obj = Utils.merge(obj, newObj, options); + } + + return Utils.compact(obj); +}; diff --git a/5-2/service/node_modules/express/node_modules/qs/lib/stringify.js b/5-2/service/node_modules/express/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000..7414284 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/lib/stringify.js @@ -0,0 +1,121 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + arrayPrefixGenerators: { + brackets: function (prefix, key) { + + return prefix + '[]'; + }, + indices: function (prefix, key) { + + return prefix + '[' + key + ']'; + }, + repeat: function (prefix, key) { + + return prefix; + } + }, + strictNullHandling: false +}; + + +internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, filter) { + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } + else if (Utils.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + else if (obj === null) { + if (strictNullHandling) { + return Utils.encode(prefix); + } + + obj = ''; + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + return [Utils.encode(prefix) + '=' + Utils.encode(obj)]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys = Array.isArray(filter) ? filter : Object.keys(obj); + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (Array.isArray(obj)) { + values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, filter)); + } + else { + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, filter)); + } + } + + return values; +}; + + +module.exports = function (obj, options) { + + options = options || {}; + var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + var objKeys; + var filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } + else if (Array.isArray(options.filter)) { + objKeys = filter = options.filter; + } + + var keys = []; + + if (typeof obj !== 'object' || + obj === null) { + + 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]; + + if (!objKeys) { + 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, generateArrayPrefix, strictNullHandling, filter)); + } + + return keys.join(delimiter); +}; diff --git a/5-2/service/node_modules/express/node_modules/qs/lib/utils.js b/5-2/service/node_modules/express/node_modules/qs/lib/utils.js new file mode 100644 index 0000000..88f3147 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/lib/utils.js @@ -0,0 +1,190 @@ +// Load modules + + +// Declare internals + +var internals = {}; +internals.hexTable = new Array(256); +for (var h = 0; h < 256; ++h) { + internals.hexTable[h] = '%' + ((h < 16 ? '0' : '') + h.toString(16)).toUpperCase(); +} + + +exports.arrayToObject = function (source, options) { + + var obj = options.plainObjects ? Object.create(null) : {}; + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.merge = function (target, source, options) { + + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } + else if (typeof target === 'object') { + target[source] = true; + } + else { + target = [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + target = [target].concat(source); + return target; + } + + if (Array.isArray(target) && + !Array.isArray(source)) { + + target = exports.arrayToObject(target, options); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = value; + } + else { + target[key] = exports.merge(target[key], value, options); + } + } + + return target; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function (str) { + + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + if (typeof str !== 'string') { + str = '' + str; + } + + var out = ''; + for (var i = 0, il = str.length; i < il; ++i) { + var c = str.charCodeAt(i); + + if (c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A)) { // A-Z + + out += str[i]; + continue; + } + + if (c < 0x80) { + out += internals.hexTable[c]; + continue; + } + + if (c < 0x800) { + out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + ++i; + c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF)); + out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function (obj, refs) { + + if (typeof obj !== 'object' || + obj === null) { + + return obj; + } + + refs = refs || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } + + refs.push(obj); + + if (Array.isArray(obj)) { + var compacted = []; + + for (var i = 0, il = obj.length; i < il; ++i) { + if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } + + return compacted; + } + + var keys = Object.keys(obj); + for (i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + obj[key] = exports.compact(obj[key], refs); + } + + return obj; +}; + + +exports.isRegExp = function (obj) { + + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + + +exports.isBuffer = function (obj) { + + if (obj === null || + typeof obj === 'undefined') { + + return false; + } + + return !!(obj.constructor && + obj.constructor.isBuffer && + obj.constructor.isBuffer(obj)); +}; diff --git a/5-2/service/node_modules/express/node_modules/qs/package.json b/5-2/service/node_modules/express/node_modules/qs/package.json new file mode 100644 index 0000000..1bae0ed --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/package.json @@ -0,0 +1,57 @@ +{ + "name": "qs", + "version": "4.0.0", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/hapijs/qs", + "main": "lib/index.js", + "dependencies": {}, + "devDependencies": { + "browserify": "^10.2.1", + "code": "1.x.x", + "lab": "5.x.x" + }, + "scripts": { + "test": "lab -a code -t 100 -L", + "test-cov-html": "lab -a code -r html -o coverage.html", + "dist": "browserify --standalone Qs lib/index.js > dist/qs.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/hapijs/qs.git" + }, + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "gitHead": "e573dd08eae6cce30d2202704691a102dfa3782a", + "bugs": { + "url": "https://github.com/hapijs/qs/issues" + }, + "_id": "qs@4.0.0", + "_shasum": "c31d9b74ec27df75e543a86c78728ed8d4623607", + "_from": "qs@4.0.0", + "_npmVersion": "2.12.0", + "_nodeVersion": "0.12.4", + "_npmUser": { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + "dist": { + "shasum": "c31d9b74ec27df75e543a86c78728ed8d4623607", + "tarball": "http://registry.npmjs.org/qs/-/qs-4.0.0.tgz" + }, + "maintainers": [ + { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/qs/-/qs-4.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/qs/test/parse.js b/5-2/service/node_modules/express/node_modules/qs/test/parse.js new file mode 100644 index 0000000..a19d764 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/test/parse.js @@ -0,0 +1,478 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('parse()', function () { + + it('parses a simple string', function (done) { + + expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' }); + expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' }); + expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } }); + expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } }); + expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } }); + expect(Qs.parse('foo', { strictNullHandling: true })).to.deep.equal({ foo: null }); + expect(Qs.parse('foo' )).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=')).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' }); + expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' }); + expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' }); + expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' }); + expect(Qs.parse('foo2=bar2&baz2=')).to.deep.equal({ foo2: 'bar2', baz2: '' }); + expect(Qs.parse('foo=bar&baz', { strictNullHandling: true })).to.deep.equal({ foo: 'bar', baz: null }); + expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' }); + expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({ + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + done(); + }); + + it('allows disabling dot notation', function (done) { + + expect(Qs.parse('a.b=c')).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse('a.b=c', { allowDots: false })).to.deep.equal({ 'a.b': 'c' }); + done(); + }); + + it('parses a single nested string', function (done) { + + expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } }); + done(); + }); + + it('parses a double nested string', function (done) { + + expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } }); + done(); + }); + + it('defaults to a depth of 5', function (done) { + + expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }); + done(); + }); + + it('only parses one level when depth = 1', function (done) { + + expect(Qs.parse('a[b][c]=d', { depth: 1 })).to.deep.equal({ a: { b: { '[c]': 'd' } } }); + expect(Qs.parse('a[b][c][d]=e', { depth: 1 })).to.deep.equal({ a: { b: { '[c][d]': 'e' } } }); + done(); + }); + + it('parses a simple array', function (done) { + + expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses an explicit array', function (done) { + + expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] }); + expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + done(); + }); + + it('parses a mix of simple and explicit arrays', function (done) { + + expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses a nested array', function (done) { + + expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } }); + expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } }); + done(); + }); + + it('allows to specify array indices', function (done) { + + expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] }); + done(); + }); + + it('limits specific array indices to 20', function (done) { + + expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] }); + expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } }); + done(); + }); + + it('supports keys that begin with a number', function (done) { + + expect(Qs.parse('a[12b]=c')).to.deep.equal({ a: { '12b': 'c' } }); + done(); + }); + + it('supports encoded = signs', function (done) { + + expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' }); + done(); + }); + + it('is ok with url encoded strings', function (done) { + + expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } }); + expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } }); + done(); + }); + + it('allows brackets in the value', function (done) { + + expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' }); + expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' }); + done(); + }); + + it('allows empty values', function (done) { + + expect(Qs.parse('')).to.deep.equal({}); + expect(Qs.parse(null)).to.deep.equal({}); + expect(Qs.parse(undefined)).to.deep.equal({}); + done(); + }); + + it('transforms arrays to objects', function (done) { + + expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + expect(Qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c')).to.deep.equal({ a: { '0': 'b', t: 'u', c: true } }); + expect(Qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y')).to.deep.equal({ a: { '0': 'b', '1': 'c', x: 'y' } }); + done(); + }); + + it('transforms arrays to objects (dot notation)', function (done) { + + expect(Qs.parse('foo[0].baz=bar&fool.bad=baz')).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz=bar&fool.bad.boo=baz')).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + expect(Qs.parse('foo[0][0].baz=bar&fool.bad=baz')).to.deep.equal({ foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].bar=2')).to.deep.equal({ foo: [{ baz: ['15'], bar: '2' }] }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2')).to.deep.equal({ foo: [{ baz: ['15', '16'], bar: '2' }] }); + expect(Qs.parse('foo.bad=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo.bad=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + done(); + }); + + it('can add keys to objects', function (done) { + + expect(Qs.parse('a[b]=c&a=d')).to.deep.equal({ a: { b: 'c', d: true } }); + done(); + }); + + it('correctly prunes undefined values when converting an array to an object', function (done) { + + expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } }); + done(); + }); + + it('supports malformed uri characters', function (done) { + + expect(Qs.parse('{%:%}', { strictNullHandling: true })).to.deep.equal({ '{%:%}': null }); + expect(Qs.parse('{%:%}=')).to.deep.equal({ '{%:%}': '' }); + expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' }); + done(); + }); + + it('doesn\'t produce empty keys', function (done) { + + expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' }); + done(); + }); + + it('cannot access Object prototype', function (done) { + + Qs.parse('constructor[prototype][bad]=bad'); + Qs.parse('bad[constructor][prototype][bad]=bad'); + expect(typeof Object.prototype.bad).to.equal('undefined'); + done(); + }); + + it('parses arrays of objects', function (done) { + + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + done(); + }); + + it('allows for empty strings in arrays', function (done) { + + expect(Qs.parse('a[]=b&a[]=&a[]=c')).to.deep.equal({ a: ['b', '', 'c'] }); + expect(Qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true })).to.deep.equal({ a: ['b', null, 'c', ''] }); + expect(Qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true })).to.deep.equal({ a: ['b', '', 'c', null] }); + expect(Qs.parse('a[]=&a[]=b&a[]=c')).to.deep.equal({ a: ['', 'b', 'c'] }); + done(); + }); + + it('compacts sparse arrays', function (done) { + + expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] }); + done(); + }); + + it('parses semi-parsed strings', function (done) { + + expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } }); + done(); + }); + + it('parses buffers correctly', function (done) { + + var b = new Buffer('test'); + expect(Qs.parse({ a: b })).to.deep.equal({ a: b }); + done(); + }); + + it('continues parsing when no parent is found', function (done) { + + expect(Qs.parse('[]=&a=b')).to.deep.equal({ '0': '', a: 'b' }); + expect(Qs.parse('[]&a=b', { strictNullHandling: true })).to.deep.equal({ '0': null, a: 'b' }); + expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' }); + done(); + }); + + it('does not error when parsing a very long array', function (done) { + + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str += '&' + str; + } + + expect(function () { + + Qs.parse(str); + }).to.not.throw(); + + done(); + }); + + it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) { + + Object.prototype.crash = ''; + Array.prototype.crash = ''; + expect(Qs.parse.bind(null, 'a=b')).to.not.throw(); + expect(Qs.parse('a=b')).to.deep.equal({ a: 'b' }); + expect(Qs.parse.bind(null, 'a[][b]=c')).to.not.throw(); + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + done(); + }); + + it('parses a string with an alternative string delimiter', function (done) { + + expect(Qs.parse('a=b;c=d', { delimiter: ';' })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('parses a string with an alternative RegExp delimiter', function (done) { + + expect(Qs.parse('a=b; c=d', { delimiter: /[;,] */ })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not use non-splittable objects as delimiters', function (done) { + + expect(Qs.parse('a=b&c=d', { delimiter: true })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('allows overriding parameter limit', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: 1 })).to.deep.equal({ a: 'b' }); + done(); + }); + + it('allows setting the parameter limit to Infinity', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: Infinity })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + 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(); + }); + + it('allows disabling array parsing', function (done) { + + expect(Qs.parse('a[0]=b&a[1]=c', { parseArrays: false })).to.deep.equal({ a: { '0': 'b', '1': 'c' } }); + done(); + }); + + it('parses an object', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object in dot notation', function (done) { + + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object and not child values', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': { 'test': 3 } }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': { 'test': 3 } }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('does not blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = Qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + expect(result).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not crash when parsing circular references', function (done) { + + var a = {}; + a.b = a; + + var parsed; + + expect(function () { + + parsed = Qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }).to.not.throw(); + + 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(); + }); + + it('parses plain objects correctly', function (done) { + + var a = Object.create(null); + a.b = 'c'; + + expect(Qs.parse(a)).to.deep.equal({ b: 'c' }); + var result = Qs.parse({ a: a }); + expect(result).to.contain('a'); + expect(result.a).to.deep.equal(a); + done(); + }); + + it('parses dates correctly', function (done) { + + var now = new Date(); + expect(Qs.parse({ a: now })).to.deep.equal({ a: now }); + done(); + }); + + it('parses regular expressions correctly', function (done) { + + var re = /^test$/; + expect(Qs.parse({ a: re })).to.deep.equal({ a: re }); + done(); + }); + + it('can allow overwriting prototype properties', function (done) { + + expect(Qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true })).to.deep.equal({ a: { hasOwnProperty: 'b' } }, { prototype: false }); + expect(Qs.parse('hasOwnProperty=b', { allowPrototypes: true })).to.deep.equal({ hasOwnProperty: 'b' }, { prototype: false }); + done(); + }); + + it('can return plain objects', function (done) { + + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + expect(Qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true })).to.deep.equal(expected); + expect(Qs.parse(null, { plainObjects: true })).to.deep.equal(Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a['0'] = 'b'; + expectedArray.a.c = 'd'; + expect(Qs.parse('a[]=b&a[c]=d', { plainObjects: true })).to.deep.equal(expectedArray); + done(); + }); +}); diff --git a/5-2/service/node_modules/express/node_modules/qs/test/stringify.js b/5-2/service/node_modules/express/node_modules/qs/test/stringify.js new file mode 100644 index 0000000..48b7803 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/test/stringify.js @@ -0,0 +1,259 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('stringify()', function () { + + it('stringifies a querystring object', function (done) { + + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 })).to.equal('a=1'); + expect(Qs.stringify({ a: 1, b: 2 })).to.equal('a=1&b=2'); + expect(Qs.stringify({ a: 'A_Z' })).to.equal('a=A_Z'); + expect(Qs.stringify({ a: '€' })).to.equal('a=%E2%82%AC'); + expect(Qs.stringify({ a: '' })).to.equal('a=%EE%80%80'); + expect(Qs.stringify({ a: 'א' })).to.equal('a=%D7%90'); + expect(Qs.stringify({ a: '𐐷' })).to.equal('a=%F0%90%90%B7'); + done(); + }); + + it('stringifies a nested object', function (done) { + + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + expect(Qs.stringify({ a: { b: { c: { d: 'e' } } } })).to.equal('a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + done(); + }); + + it('stringifies an array value', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d'); + done(); + }); + + it('omits array indices when asked', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false })).to.equal('a=b&a=c&a=d'); + done(); + }); + + it('stringifies a nested array value', function (done) { + + expect(Qs.stringify({ a: { b: ['c', 'd'] } })).to.equal('a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + done(); + }); + + it('stringifies an object inside an array', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] })).to.equal('a%5B0%5D%5Bb%5D=c'); + expect(Qs.stringify({ a: [{ b: { c: [1] } }] })).to.equal('a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1'); + done(); + }); + + it('does not omit object keys when indices = false', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] }, { indices: false })).to.equal('a%5Bb%5D=c'); + 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'); + done(); + }); + + it('stringifies an empty value', function (done) { + + expect(Qs.stringify({ a: '' })).to.equal('a='); + expect(Qs.stringify({ a: null }, { strictNullHandling: true })).to.equal('a'); + + expect(Qs.stringify({ a: '', b: '' })).to.equal('a=&b='); + expect(Qs.stringify({ a: null, b: '' }, { strictNullHandling: true })).to.equal('a&b='); + + expect(Qs.stringify({ a: { b: '' } })).to.equal('a%5Bb%5D='); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: true })).to.equal('a%5Bb%5D'); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: false })).to.equal('a%5Bb%5D='); + + done(); + }); + + it('stringifies an empty object', function (done) { + + var obj = Object.create(null); + obj.a = 'b'; + expect(Qs.stringify(obj)).to.equal('a=b'); + done(); + }); + + it('returns an empty string for invalid input', function (done) { + + expect(Qs.stringify(undefined)).to.equal(''); + expect(Qs.stringify(false)).to.equal(''); + expect(Qs.stringify(null)).to.equal(''); + expect(Qs.stringify('')).to.equal(''); + done(); + }); + + it('stringifies an object with an empty object as a child', function (done) { + + var obj = { + a: Object.create(null) + }; + + obj.a.b = 'c'; + expect(Qs.stringify(obj)).to.equal('a%5Bb%5D=c'); + done(); + }); + + it('drops keys with a value of undefined', function (done) { + + expect(Qs.stringify({ a: undefined })).to.equal(''); + + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true })).to.equal('a%5Bc%5D'); + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false })).to.equal('a%5Bc%5D='); + expect(Qs.stringify({ a: { b: undefined, c: '' } })).to.equal('a%5Bc%5D='); + done(); + }); + + it('url encodes values', function (done) { + + expect(Qs.stringify({ a: 'b c' })).to.equal('a=b%20c'); + done(); + }); + + it('stringifies a date', function (done) { + + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + expect(Qs.stringify({ a: now })).to.equal(str); + done(); + }); + + it('stringifies the weird object from qs', function (done) { + + expect(Qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' })).to.equal('my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + done(); + }); + + it('skips properties that are part of the object prototype', function (done) { + + Object.prototype.crash = 'test'; + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + delete Object.prototype.crash; + done(); + }); + + it('stringifies boolean values', function (done) { + + expect(Qs.stringify({ a: true })).to.equal('a=true'); + expect(Qs.stringify({ a: { b: true } })).to.equal('a%5Bb%5D=true'); + expect(Qs.stringify({ b: false })).to.equal('b=false'); + expect(Qs.stringify({ b: { c: false } })).to.equal('b%5Bc%5D=false'); + done(); + }); + + it('stringifies buffer values', function (done) { + + expect(Qs.stringify({ a: new Buffer('test') })).to.equal('a=test'); + expect(Qs.stringify({ a: { b: new Buffer('test') } })).to.equal('a%5Bb%5D=test'); + done(); + }); + + it('stringifies an object using an alternative delimiter', function (done) { + + expect(Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' })).to.equal('a=b;c=d'); + done(); + }); + + it('doesn\'t blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + expect(Qs.stringify({ a: 'b', c: 'd' })).to.equal('a=b&c=d'); + global.Buffer = tempBuffer; + done(); + }); + + it('selects properties when filter=array', function (done) { + + expect(Qs.stringify({ a: 'b' }, { filter: ['a'] })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 }, { filter: [] })).to.equal(''); + expect(Qs.stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] })).to.equal('a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3'); + done(); + + }); + + it('supports custom representations when filter=function', function (done) { + + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + + calls++; + if (calls === 1) { + expect(prefix).to.be.empty(); + expect(value).to.equal(obj); + } + else if (prefix === 'c') { + return; + } + else if (value instanceof Date) { + expect(prefix).to.equal('e[f]'); + return value.getTime(); + } + return value; + }; + + expect(Qs.stringify(obj, { filter: filterFunc })).to.equal('a=b&e%5Bf%5D=1257894000000'); + expect(calls).to.equal(5); + done(); + + }); +}); diff --git a/5-2/service/node_modules/express/node_modules/qs/test/utils.js b/5-2/service/node_modules/express/node_modules/qs/test/utils.js new file mode 100644 index 0000000..a9a6b52 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/qs/test/utils.js @@ -0,0 +1,28 @@ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Utils = require('../lib/utils'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('merge()', function () { + + it('can merge two objects with the same key', function (done) { + + expect(Utils.merge({ a: 'b' }, { a: 'c' })).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); +}); diff --git a/5-2/service/node_modules/express/node_modules/range-parser/HISTORY.md b/5-2/service/node_modules/express/node_modules/range-parser/HISTORY.md new file mode 100644 index 0000000..f640bea --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/range-parser/HISTORY.md @@ -0,0 +1,40 @@ +unreleased +========== + + * perf: enable strict mode + +1.0.2 / 2014-09-08 +================== + + * Support Node.js 0.6 + +1.0.1 / 2014-09-07 +================== + + * Move repository to jshttp + +1.0.0 / 2013-12-11 +================== + + * Add repository to package.json + * Add MIT license + +0.0.4 / 2012-06-17 +================== + + * Change ret -1 for unsatisfiable and -2 when invalid + +0.0.3 / 2012-06-17 +================== + + * Fix last-byte-pos default to len - 1 + +0.0.2 / 2012-06-14 +================== + + * Add `.type` + +0.0.1 / 2012-06-11 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/range-parser/LICENSE b/5-2/service/node_modules/express/node_modules/range-parser/LICENSE new file mode 100644 index 0000000..a491841 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/range-parser/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/range-parser/README.md b/5-2/service/node_modules/express/node_modules/range-parser/README.md new file mode 100644 index 0000000..32f58f6 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/range-parser/README.md @@ -0,0 +1,57 @@ +# range-parser + +[![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] + +Range header field parser. + +## Installation + +``` +$ npm install range-parser +``` + +## API + +```js +var parseRange = require('range-parser') +``` + +### parseRange(size, header) + +Parse the given `header` string where `size` is the maximum size of the resource. +An array of ranges will be returned or negative numbers indicating an error parsing. + + * `-2` signals a malformed header string + * `-1` signals an invalid range + +```js +// parse header from request +var range = parseRange(req.headers.range) + +// the type of the range +if (range.type === 'bytes') { + // the ranges + range.forEach(function (r) { + // do something with r.start and r.end + }) +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/range-parser.svg +[npm-url]: https://npmjs.org/package/range-parser +[node-version-image]: https://img.shields.io/node/v/range-parser.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/range-parser.svg +[travis-url]: https://travis-ci.org/jshttp/range-parser +[coveralls-image]: https://img.shields.io/coveralls/jshttp/range-parser.svg +[coveralls-url]: https://coveralls.io/r/jshttp/range-parser +[downloads-image]: https://img.shields.io/npm/dm/range-parser.svg +[downloads-url]: https://npmjs.org/package/range-parser diff --git a/5-2/service/node_modules/express/node_modules/range-parser/index.js b/5-2/service/node_modules/express/node_modules/range-parser/index.js new file mode 100644 index 0000000..814e533 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/range-parser/index.js @@ -0,0 +1,63 @@ +/*! + * range-parser + * Copyright(c) 2012-2014 TJ Holowaychuk + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = rangeParser; + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @return {Array} + * @public + */ + +function rangeParser(size, str) { + var valid = true; + var i = str.indexOf('='); + + if (-1 == i) return -2; + + var arr = str.slice(i + 1).split(',').map(function(range){ + var range = range.split('-') + , start = parseInt(range[0], 10) + , end = parseInt(range[1], 10); + + // -nnn + if (isNaN(start)) { + start = size - end; + end = size - 1; + // nnn- + } else if (isNaN(end)) { + end = size - 1; + } + + // limit last-byte-pos to current length + if (end > size - 1) end = size - 1; + + // invalid + if (isNaN(start) + || isNaN(end) + || start > end + || start < 0) valid = false; + + return { + start: start, + end: end + }; + }); + + arr.type = str.slice(0, i); + + return valid ? arr : -1; +} diff --git a/5-2/service/node_modules/express/node_modules/range-parser/package.json b/5-2/service/node_modules/express/node_modules/range-parser/package.json new file mode 100644 index 0000000..5d4411b --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/range-parser/package.json @@ -0,0 +1,75 @@ +{ + "name": "range-parser", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "description": "Range header field string parser", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "range", + "parser", + "http" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/range-parser.git" + }, + "devDependencies": { + "istanbul": "0.4.0", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "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" + }, + "gitHead": "18e46a3de74afff9f4e22717f11ddd6e9aa6d845", + "bugs": { + "url": "https://github.com/jshttp/range-parser/issues" + }, + "homepage": "https://github.com/jshttp/range-parser", + "_id": "range-parser@1.0.3", + "_shasum": "6872823535c692e2c2a0103826afd82c2e0ff175", + "_from": "range-parser@>=1.0.3 <1.1.0", + "_npmVersion": "1.4.28", + "_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": "6872823535c692e2c2a0103826afd82c2e0ff175", + "tarball": "http://registry.npmjs.org/range-parser/-/range-parser-1.0.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/send/HISTORY.md b/5-2/service/node_modules/express/node_modules/send/HISTORY.md new file mode 100644 index 0000000..d3dca9c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/HISTORY.md @@ -0,0 +1,310 @@ +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * 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: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.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/5-2/service/node_modules/express/node_modules/send/LICENSE b/5-2/service/node_modules/express/node_modules/send/LICENSE new file mode 100644 index 0000000..e4d595b --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +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: + +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/5-2/service/node_modules/express/node_modules/send/README.md b/5-2/service/node_modules/express/node_modules/send/README.md new file mode 100644 index 0000000..3586060 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/README.md @@ -0,0 +1,195 @@ +# send + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Send is a library for streaming files from the file system as a http response +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. + +Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). + +## 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"). + + - `'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. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### 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 example + +```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 +[npm-url]: https://npmjs.org/package/send +[travis-image]: https://img.shields.io/travis/pillarjs/send/master.svg?label=linux +[travis-url]: https://travis-ci.org/pillarjs/send +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/send/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/send +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/send/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master +[downloads-image]: https://img.shields.io/npm/dm/send.svg +[downloads-url]: https://npmjs.org/package/send +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/5-2/service/node_modules/express/node_modules/send/index.js b/5-2/service/node_modules/express/node_modules/send/index.js new file mode 100644 index 0000000..3510989 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/index.js @@ -0,0 +1,820 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('send') +var deprecate = require('depd')('send') +var destroy = require('destroy') +var escapeHtml = require('escape-html') + , parseRange = require('range-parser') + , Stream = require('stream') + , mime = require('mime') + , fresh = require('fresh') + , path = require('path') + , fs = require('fs') + , normalize = path.normalize + , join = path.join +var etag = require('etag') +var EventEmitter = require('events').EventEmitter; +var ms = require('ms'); +var onFinished = require('on-finished') +var statuses = require('statuses') + +/** + * Variables. + */ +var extname = path.extname +var maxMaxAge = 60 * 60 * 24 * 365 * 1000; // 1 year +var resolve = path.resolve +var sep = path.sep +var toString = Object.prototype.toString +var upPathRegexp = /(?:^|[\\\/])\.\.(?:[\\\/]|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = send +module.exports.mime = mime + +/** + * Shim EventEmitter.listenerCount for node.js < 0.10 + */ + +/* istanbul ignore next */ +var listenerCount = EventEmitter.listenerCount + || function(emitter, type){ return emitter.listeners(type).length; }; + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ + +function send(req, path, options) { + return new SendStream(req, path, options); +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ + +function SendStream(req, path, options) { + var opts = options || {} + + this.options = opts + this.path = path + this.req = req + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true + + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' + + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + this._hidden = Boolean(opts.hidden) + + if (opts.hidden !== undefined) { + deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') + } + + // legacy support + if (opts.dotfiles === undefined) { + this._dotfiles = undefined + } + + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] + + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] + + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true + + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), maxMaxAge) + : 0 + + this._root = opts.root + ? resolve(opts.root) + : null + + if (!this._root && opts.from) { + this.from(opts.from) + } +} + +/** + * Inherits from `Stream.prototype`. + */ + +SendStream.prototype.__proto__ = Stream.prototype; + +/** + * Enable or disable etag generation. + * + * @param {Boolean} val + * @return {SendStream} + * @api public + */ + +SendStream.prototype.etag = deprecate.function(function etag(val) { + val = Boolean(val); + debug('etag %s', val); + this._etag = val; + return this; +}, 'send.etag: pass etag as option'); + +/** + * Enable or disable "hidden" (dot) files. + * + * @param {Boolean} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.hidden = deprecate.function(function hidden(val) { + val = Boolean(val); + debug('hidden %s', val); + this._hidden = val; + this._dotfiles = undefined + return this; +}, 'send.hidden: use dotfiles option'); + +/** + * Set index `paths`, set to a falsy + * value to disable index support. + * + * @param {String|Boolean|Array} paths + * @return {SendStream} + * @api public + */ + +SendStream.prototype.index = deprecate.function(function index(paths) { + var index = !paths ? [] : normalizeList(paths, 'paths argument'); + debug('index %o', paths); + this._index = index; + return this; +}, 'send.index: pass index as option'); + +/** + * Set root `path`. + * + * @param {String} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.root = function(path){ + path = String(path); + this._root = resolve(path) + return this; +}; + +SendStream.prototype.from = deprecate.function(SendStream.prototype.root, + 'send.from: pass root as option'); + +SendStream.prototype.root = deprecate.function(SendStream.prototype.root, + 'send.root: pass root as option'); + +/** + * Set max-age to `maxAge`. + * + * @param {Number} maxAge + * @return {SendStream} + * @api public + */ + +SendStream.prototype.maxage = deprecate.function(function maxage(maxAge) { + maxAge = typeof maxAge === 'string' + ? ms(maxAge) + : Number(maxAge); + if (isNaN(maxAge)) maxAge = 0; + if (Infinity == maxAge) maxAge = 60 * 60 * 24 * 365 * 1000; + debug('max-age %d', maxAge); + this._maxage = maxAge; + return this; +}, 'send.maxage: pass maxAge as option'); + +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [error] + * @private + */ + +SendStream.prototype.error = function error(status, error) { + // emit if listeners instead of responding + if (listenerCount(this, 'error') !== 0) { + return this.emit('error', createError(error, status, { + expose: false + })) + } + + var res = this.res + var msg = statuses[status] + + // wipe all existing headers + res._headers = null + + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/plain; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(msg) +} + +/** + * Check if the pathname ends with "/". + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.hasTrailingSlash = function(){ + return '/' == this.path[this.path.length - 1]; +}; + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function(){ + return this.req.headers['if-none-match'] + || this.req.headers['if-modified-since']; +}; + +/** + * Strip content-* header fields. + * + * @private + */ + +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields() { + var res = this.res + var headers = Object.keys(res._headers || {}) + + for (var i = 0; i < headers.length; i++) { + var header = headers[i] + if (header.substr(0, 8) === 'content-' && header !== 'content-location') { + res.removeHeader(header) + } + } +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function(){ + var res = this.res; + debug('not modified'); + this.removeContentHeaderFields(); + res.statusCode = 304; + res.end(); +}; + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent(){ + var err = new Error('Can\'t set headers after they are sent.'); + debug('headers already sent'); + this.error(500, err); +}; + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function(){ + var res = this.res; + return (res.statusCode >= 200 && res.statusCode < 300) || 304 == res.statusCode; +}; + +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ + +SendStream.prototype.onStatError = function onStatError(error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function(){ + return fresh(this.req.headers, this.res._headers); +}; + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh(){ + var ifRange = this.req.headers['if-range']; + + if (!ifRange) return true; + + return ~ifRange.indexOf('"') + ? ~ifRange.indexOf(this.res._headers['etag']) + : Date.parse(this.res._headers['last-modified']) <= Date.parse(ifRange); +}; + +/** + * Redirect to path. + * + * @param {string} path + * @private + */ + +SendStream.prototype.redirect = function redirect(path) { + if (listenerCount(this, 'directory') !== 0) { + this.emit('directory') + return + } + + if (this.hasTrailingSlash()) { + this.error(403) + return + } + + var loc = path + '/' + var msg = 'Redirecting to ' + escapeHtml(loc) + '\n' + var res = this.res + + // redirect + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(msg) +} + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function(res){ + var self = this + , args = arguments + , root = this._root; + + // references + this.res = res; + + // decode the path + var path = decode(this.path) + if (path === -1) return this.error(400) + + // null byte(s) + if (~path.indexOf('\0')) return this.error(400); + + var parts + if (root !== null) { + // malicious path + 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 { + // ".." is malicious without "root" + if (upPathRegexp.test(path)) { + debug('malicious path "%s"', path) + return this.error(403) + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + // dotfile handling + if (containsDotFile(parts)) { + var access = this._dotfiles + + // legacy support + if (access === undefined) { + access = parts[parts.length - 1][0] === '.' + ? (this._hidden ? 'allow' : 'ignore') + : 'allow' + } + + debug('%s dotfile "%s"', access, path) + switch (access) { + case 'allow': + break + case 'deny': + return this.error(403) + case 'ignore': + default: + return this.error(404) + } + } + + // index file support + if (this._index.length && this.path[this.path.length - 1] === '/') { + this.sendIndex(path); + return res; + } + + this.sendFile(path); + return res; +}; + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function(path, stat){ + var len = stat.size; + var options = this.options + var opts = {} + var res = this.res; + var req = this.req; + var ranges = req.headers.range; + var offset = options.start || 0; + + if (res._header) { + // impossible to send now + return this.headersAlreadySent(); + } + + debug('pipe "%s"', path) + + // set header fields + this.setHeader(path, stat); + + // set content-type + this.type(path); + + // conditional GET support + if (this.isConditionalGET() + && this.isCachable() + && this.isFresh()) { + return this.notModified(); + } + + // adjust len to start/end options + len = Math.max(0, len - offset); + if (options.end !== undefined) { + var bytes = options.end - offset + 1; + if (len > bytes) len = bytes; + } + + // Range support + if (ranges) { + ranges = parseRange(len, ranges); + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale'); + ranges = -2; + } + + // unsatisfiable + if (-1 == ranges) { + debug('range unsatisfiable'); + res.setHeader('Content-Range', 'bytes */' + stat.size); + return this.error(416); + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (-2 != ranges && ranges.length === 1) { + debug('range %j', ranges); + + // Content-Range + res.statusCode = 206; + res.setHeader('Content-Range', 'bytes ' + + ranges[0].start + + '-' + + ranges[0].end + + '/' + + len); + + 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, opts) +}; + +/** + * Transfer file for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendFile = function sendFile(path) { + var i = 0 + var self = this + + debug('stat "%s"', path); + fs.stat(path, function onstat(err, stat) { + if (err && err.code === 'ENOENT' + && !extname(path) + && path[path.length - 1] !== sep) { + // not found, check extensions + return next(err) + } + if (err) return self.onStatError(err) + if (stat.isDirectory()) return self.redirect(self.path) + self.emit('file', path, stat) + self.send(path, stat) + }) + + function next(err) { + if (self._extensions.length <= i) { + return err + ? self.onStatError(err) + : self.error(404) + } + + var p = path + '.' + self._extensions[i++] + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } +} + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex(path){ + var i = -1; + var self = this; + + function next(err){ + if (++i >= self._index.length) { + if (err) return self.onStatError(err); + return self.error(404); + } + + var p = join(path, self._index[i]); + + debug('stat "%s"', p); + fs.stat(p, function(err, stat){ + if (err) return next(err); + if (stat.isDirectory()) return next(); + self.emit('file', p, stat); + self.send(p, stat); + }); + } + + next(); +}; + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function(path, options){ + // TODO: this is all lame, refactor meeee + var finished = false; + var self = this; + var res = this.res; + var req = this.req; + + // pipe + var stream = fs.createReadStream(path, options); + this.emit('stream', stream); + stream.pipe(res); + + // response finished, done with the fd + onFinished(res, function onfinished(){ + finished = true; + destroy(stream); + }); + + // error handling code-smell + stream.on('error', function onerror(err){ + // request already finished + if (finished) return; + + // clean up stream + finished = true; + destroy(stream); + + // error + self.onStatError(err); + }); + + // end + stream.on('end', function onend(){ + self.emit('end'); + }); +}; + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function(path){ + var res = this.res; + if (res.getHeader('Content-Type')) return; + var type = mime.lookup(path); + var charset = mime.charsets.lookup(type); + debug('content-type %s', type); + res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')); +}; + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader(path, stat){ + var res = this.res; + + this.emit('headers', res, path, stat); + + if (!res.getHeader('Accept-Ranges')) res.setHeader('Accept-Ranges', 'bytes'); + if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + Math.floor(this._maxage / 1000)); + + if (this._lastModified && !res.getHeader('Last-Modified')) { + var modified = stat.mtime.toUTCString() + debug('modified %s', modified) + res.setHeader('Last-Modified', modified) + } + + if (this._etag && !res.getHeader('ETag')) { + var val = etag(stat) + debug('etag %s', val) + res.setHeader('ETag', val) + } +}; + +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ + +function containsDotFile(parts) { + for (var i = 0; i < parts.length; i++) { + if (parts[i][0] === '.') { + return true + } + } + + return false +} + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +function decode(path) { + try { + return decodeURIComponent(path) + } catch (err) { + return -1 + } +} + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +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/5-2/service/node_modules/express/node_modules/send/node_modules/.bin/mime b/5-2/service/node_modules/express/node_modules/send/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/LICENSE b/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/README.md b/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/README.md new file mode 100644 index 0000000..6474bc3 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/README.md @@ -0,0 +1,60 @@ +# Destroy + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Destroy a stream. + +This module is meant to ensure a stream gets destroyed, handling different APIs +and Node.js bugs. + +## API + +```js +var destroy = require('destroy') +``` + +### destroy(stream) + +Destroy the given stream. In most cases, this is identical to a simple +`stream.destroy()` call. The rules are as follows for a given stream: + + 1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()` + and add a listener to the `open` event to call `stream.close()` if it is + fired. This is for a Node.js bug that will leak a file descriptor if + `.destroy()` is called before `open`. + 2. If the `stream` is not an instance of `Stream`, then nothing happens. + 3. If the `stream` has a `.destroy()` method, then call it. + +The function returns the `stream` passed in as the argument. + +## Example + +```js +var destroy = require('destroy') + +var fs = require('fs') +var stream = fs.createReadStream('package.json') + +// ... and later +destroy(stream) +``` + +[npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square +[npm-url]: https://npmjs.org/package/destroy +[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square +[github-url]: https://github.com/stream-utils/destroy/tags +[travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square +[travis-url]: https://travis-ci.org/stream-utils/destroy +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master +[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/destroy +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/index.js b/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/index.js new file mode 100644 index 0000000..6da2d26 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/index.js @@ -0,0 +1,75 @@ +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var ReadStream = require('fs').ReadStream +var Stream = require('stream') + +/** + * Module exports. + * @public + */ + +module.exports = destroy + +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ + +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) + } + + if (!(stream instanceof Stream)) { + return stream + } + + if (typeof stream.destroy === 'function') { + stream.destroy() + } + + return stream +} + +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ + +function destroyReadStream(stream) { + stream.destroy() + + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } + + return stream +} + +/** + * On open handler to close stream. + * @private + */ + +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } +} diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/package.json b/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/package.json new file mode 100644 index 0000000..f7f3f16 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/destroy/package.json @@ -0,0 +1,72 @@ +{ + "name": "destroy", + "description": "destroy a stream if possible", + "version": "1.0.4", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/destroy.git" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4" + }, + "scripts": { + "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" + }, + "files": [ + "index.js", + "LICENSE" + ], + "keywords": [ + "stream", + "streams", + "destroy", + "cleanup", + "leak", + "fd" + ], + "gitHead": "86edea01456f5fa1027f6a47250c34c713cbcc3b", + "bugs": { + "url": "https://github.com/stream-utils/destroy/issues" + }, + "homepage": "https://github.com/stream-utils/destroy", + "_id": "destroy@1.0.4", + "_shasum": "978857442c44749e4206613e37946205826abd80", + "_from": "destroy@>=1.0.4 <1.1.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" + } + ], + "dist": { + "shasum": "978857442c44749e4206613e37946205826abd80", + "tarball": "http://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md new file mode 100644 index 0000000..4c7087d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md @@ -0,0 +1,76 @@ +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/README.md b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/README.md new file mode 100644 index 0000000..520271e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/README.md @@ -0,0 +1,63 @@ +# http-errors + +[![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] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Example + +```js +var createError = require('http-errors'); + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')); + next(); +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +### Error Properties + +- `message` +- `status` and `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + +```js +var err = createError(404, 'This video does not exist!'); +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### new createError\[code || name\](\[msg]\)) + +```js +var err = new createError.NotFound(); +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/http-errors.svg?style=flat +[npm-url]: https://npmjs.org/package/http-errors +[node-version-image]: https://img.shields.io/node/v/http-errors.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/http-errors.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/http-errors +[coveralls-image]: https://img.shields.io/coveralls/jshttp/http-errors.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors +[downloads-image]: https://img.shields.io/npm/dm/http-errors.svg?style=flat +[downloads-url]: https://npmjs.org/package/http-errors diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/index.js b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/index.js new file mode 100644 index 0000000..d84b114 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/index.js @@ -0,0 +1,120 @@ + +var statuses = require('statuses'); +var inherits = require('inherits'); + +function toIdentifier(str) { + return str.split(' ').map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }).join('').replace(/[^ _0-9a-z]/gi, '') +} + +exports = module.exports = function httpError() { + // so much arity going on ~_~ + var err; + var msg; + var status = 500; + var props = {}; + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (arg instanceof Error) { + err = arg; + status = err.status || err.statusCode || status; + continue; + } + switch (typeof arg) { + case 'string': + msg = arg; + break; + case 'number': + status = arg; + break; + case 'object': + props = arg; + break; + } + } + + if (typeof status !== 'number' || !statuses[status]) { + status = 500 + } + + // constructor + var HttpError = exports[status] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, httpError) + } + + if (!HttpError || !(err instanceof HttpError)) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err; +}; + +// create generic error objects +var codes = statuses.codes.filter(function (num) { + return num >= 400; +}); + +codes.forEach(function (code) { + var name = toIdentifier(statuses[code]) + var className = name.match(/Error$/) ? name : name + 'Error' + + if (code >= 500) { + var ServerError = function ServerError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ServerError) + self.__proto__ = ServerError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ServerError, Error); + ServerError.prototype.status = + ServerError.prototype.statusCode = code; + ServerError.prototype.expose = false; + exports[code] = + exports[name] = ServerError + return; + } + + var ClientError = function ClientError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ClientError) + self.__proto__ = ClientError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ClientError, Error); + ClientError.prototype.status = + ClientError.prototype.statusCode = code; + ClientError.prototype.expose = true; + exports[code] = + exports[name] = ClientError + return; +}); + +// backwards-compatibility +exports["I'mateapot"] = exports.ImATeapot diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +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/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +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/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +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/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json new file mode 100644 index 0000000..93d5078 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json @@ -0,0 +1,50 @@ +{ + "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.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "_id": "inherits@2.0.1", + "dist": { + "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/inherits#readme" +} diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +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/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/package.json b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/package.json new file mode 100644 index 0000000..41f845d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/http-errors/package.json @@ -0,0 +1,85 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "1.3.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Alan Plum", + "email": "me@pluma.io" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/http-errors.git" + }, + "dependencies": { + "inherits": "~2.0.1", + "statuses": "1" + }, + "devDependencies": { + "istanbul": "0", + "mocha": "1" + }, + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ], + "gitHead": "89a8502b40d5dd42da2908f265275e2eeb8d0699", + "bugs": { + "url": "https://github.com/jshttp/http-errors/issues" + }, + "homepage": "https://github.com/jshttp/http-errors", + "_id": "http-errors@1.3.1", + "_shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "_from": "http-errors@>=1.3.1 <1.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "egeste", + "email": "npm@egeste.net" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "tarball": "http://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/mime/.npmignore b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/.npmignore new file mode 100644 index 0000000..e69de29 diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/mime/LICENSE b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/LICENSE new file mode 100644 index 0000000..451fc45 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/mime/README.md b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/README.md new file mode 100644 index 0000000..506fbe5 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/README.md @@ -0,0 +1,90 @@ +# mime + +Comprehensive MIME type mapping API based on mime-db module. + +## Install + +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. + +```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.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + +```js +mime.extension('text/html'); // => 'html' +mime.extension('application/octet-stream'); // => 'bin' +``` + +### mime.charsets.lookup() + +Map mime-type to charset + +```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 + +Custom type mappings can be added on a per-project basis via the following APIs. + +### mime.define() + +Add custom mime/extension mappings + +```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' +``` + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + +```js +mime.extension('text/x-some-format'); // => 'x-sf' +``` + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + +```js +mime.load('./my_project.types'); +``` +The .types file format is simple - See the `types` dir for examples. diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/mime/build/build.js b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/build/build.js new file mode 100644 index 0000000..ed5313e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/build/build.js @@ -0,0 +1,11 @@ +var db = require('mime-db'); + +var mapByType = {}; +Object.keys(db).forEach(function(key) { + var extensions = db[key].extensions; + if (extensions) { + mapByType[key] = extensions; + } +}); + +console.log(JSON.stringify(mapByType)); diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/mime/build/test.js b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/build/test.js new file mode 100644 index 0000000..58b9ba7 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/build/test.js @@ -0,0 +1,57 @@ +/** + * Usage: node test.js + */ + +var mime = require('../mime'); +var assert = require('assert'); +var path = require('path'); + +// +// Test mime lookups +// + +assert.equal('text/plain', mime.lookup('text.txt')); // normal file +assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase +assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file +assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file +assert.equal('text/plain', mime.lookup('.txt')); // nameless +assert.equal('text/plain', mime.lookup('txt')); // extension-only +assert.equal('text/plain', mime.lookup('/txt')); // extension-less () +assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less +assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized +assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +assert.equal('txt', mime.extension(mime.types.text)); +assert.equal('html', mime.extension(mime.types.htm)); +assert.equal('bin', mime.extension('application/octet-stream')); +assert.equal('bin', mime.extension('application/octet-stream ')); +assert.equal('html', mime.extension(' text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html; charset=UTF-8 ')); +assert.equal('html', mime.extension('text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html ; charset=UTF-8')); +assert.equal('html', mime.extension('text/html;charset=UTF-8')); +assert.equal('html', mime.extension('text/Html;charset=UTF-8')); +assert.equal(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +assert.equal('application/font-woff', mime.lookup('file.woff')); +assert.equal('application/octet-stream', mime.lookup('file.buffer')); +assert.equal('audio/mp4', mime.lookup('file.m4a')); +assert.equal('font/opentype', mime.lookup('file.otf')); + +// +// Test charsets +// + +assert.equal('UTF-8', mime.charsets.lookup('text/plain')); +assert.equal(undefined, mime.charsets.lookup(mime.types.js)); +assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +console.log('\nAll tests passed'); diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/mime/cli.js b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/cli.js new file mode 100755 index 0000000..20b1ffe --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/cli.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node + +var mime = require('./mime.js'); +var file = process.argv[2]; +var type = mime.lookup(file); + +process.stdout.write(type + '\n'); + diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/mime/mime.js b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/mime.js new file mode 100644 index 0000000..341b6a5 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/mime.js @@ -0,0 +1,108 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts]) { + console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Define built-in types +mime.define(require('./types.json')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/mime/package.json b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/package.json new file mode 100644 index 0000000..31e7669 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/package.json @@ -0,0 +1,73 @@ +{ + "author": { + "name": "Robert Kieffer", + "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", + "email": "benjamin@benjaminthomas.org", + "url": "http://github.com/bentomas" + } + ], + "description": "A comprehensive library for mime-type mapping", + "licenses": [ + { + "type": "MIT", + "url": "https://raw.github.com/broofa/node-mime/master/LICENSE" + } + ], + "dependencies": {}, + "devDependencies": { + "mime-db": "^1.2.0" + }, + "keywords": [ + "util", + "mime" + ], + "main": "mime.js", + "name": "mime", + "repository": { + "url": "git+https://github.com/broofa/node-mime.git", + "type": "git" + }, + "version": "1.3.4", + "gitHead": "1628f6e0187095009dcef4805c3a49706f137974", + "bugs": { + "url": "https://github.com/broofa/node-mime/issues" + }, + "homepage": "https://github.com/broofa/node-mime", + "_id": "mime@1.3.4", + "_shasum": "115f9e3b6b3daf2959983cb38f149a2d40eb5d53", + "_from": "mime@1.3.4", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "broofa", + "email": "robert@broofa.com" + }, + "maintainers": [ + { + "name": "broofa", + "email": "robert@broofa.com" + }, + { + "name": "bentomas", + "email": "benjamin@benjaminthomas.org" + } + ], + "dist": { + "shasum": "115f9e3b6b3daf2959983cb38f149a2d40eb5d53", + "tarball": "http://registry.npmjs.org/mime/-/mime-1.3.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime/-/mime-1.3.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/mime/types.json b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/types.json new file mode 100644 index 0000000..c674b1c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/mime/types.json @@ -0,0 +1 @@ +{"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomsvc+xml":["atomsvc"],"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/cu-seeme":["cu"],"application/dash+xml":["mdp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/font-tdpfr":["pfr"],"application/font-woff":["woff"],"application/font-woff2":["woff2"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/java-archive":["jar"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","buffer"],"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/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"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/postscript":["ai","eps","ps"],"application/prs.cww":["cww"],"application/pskc+xml":["pskcxml"],"application/rdf+xml":["rdf"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"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-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"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.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"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.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.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"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.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.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"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.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"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.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"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.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"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.gmx":["gmx"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"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+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"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.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.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"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.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.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.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"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.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"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-officetheme":["thmx"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["stl"],"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-project":["mpp","mpt"],"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.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"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.n-gage.data":["ngdat"],"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.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.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"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.sailingtracker.track":["st"],"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.teacher":["teacher"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"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.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.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"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.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.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"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.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/voicexml+xml":["vxml"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"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-chrome-extension":["crx"],"application/x-conference":["nsc"],"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-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-otf":["otf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-ttf":["ttf","ttc"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"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-hdf":["hdf"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["iso"],"application/x-java-jnlp-file":["jnlp"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"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-web-app-manifest+json":["webapp"],"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/xaml+xml":["xaml"],"application/xcap-diff+xml":["xdf"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xml":["xml","xsl","xsd"],"application/xml-dtd":["dtd"],"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/adpcm":["adp"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mp4":["mp4a","m4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"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-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-xyz":["xyz"],"font/opentype":["otf"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/g3fax":["g3"],"image/gif":["gif"],"image/ief":["ief"],"image/jpeg":["jpeg","jpg","jpe"],"image/ktx":["ktx"],"image/png":["png"],"image/prs.btif":["btif"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/tiff":["tiff","tif"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["sub"],"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.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"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/rfc822":["eml","mime"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.vtu":["vtu"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["x3db","x3dbz"],"model/x3d+vrml":["x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee"],"text/css":["css"],"text/csv":["csv"],"text/hjson":["hjson"],"text/html":["html","htm"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/prs.lines.tag":["dsc"],"text/richtext":["rtx"],"text/sgml":["sgml","sgm"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"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.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/vtt":["vtt"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["markdown","md","mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-pascal":["p","pas"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"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/5-2/service/node_modules/express/node_modules/send/node_modules/ms/.npmignore b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/ms/History.md b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/ms/LICENSE b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/5-2/service/node_modules/express/node_modules/send/node_modules/ms/README.md b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/ms/index.js b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/5-2/service/node_modules/express/node_modules/send/node_modules/ms/package.json b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/LICENSE b/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/README.md b/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/README.md new file mode 100644 index 0000000..f6ae24c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/README.md @@ -0,0 +1,114 @@ +# Statuses + +[![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] + +HTTP status utility for node. + +## API + +```js +var status = require('statuses'); +``` + +### var code = status(Integer || String) + +If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown. + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status('forbidden') // => 403 +status('Forbidden') // => 403 +status(306) // throws, as it's not supported by node.js +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### var msg = status[code] + +Map of `code` to `status message`. `undefined` for invalid `code`s. + +```js +status[404] // => 'Not Found' +``` + +### var code = status[msg] + +Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s. + +```js +status['not found'] // => 404 +status['Not Found'] // => 404 +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +### statuses/codes.json + +```js +var codes = require('statuses/codes.json'); +``` + +This is a JSON file of the status codes +taken from `require('http').STATUS_CODES`. +This is saved so that codes are consistent even in older node.js versions. +For example, `308` will be added in v0.12. + +## Adding Status Codes + +The status codes are primarily sourced from http://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv. +Additionally, custom codes are added from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes. +These are added manually in the `lib/*.json` files. +If you would like to add a status code, add it to the appropriate JSON file. + +To rebuild `codes.json`, run the following: + +```bash +# update src/iana.json +npm run update +# build codes.json +npm run build +``` + +[npm-image]: https://img.shields.io/npm/v/statuses.svg?style=flat +[npm-url]: https://npmjs.org/package/statuses +[node-version-image]: http://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/statuses.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/statuses +[coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[downloads-image]: http://img.shields.io/npm/dm/statuses.svg?style=flat +[downloads-url]: https://npmjs.org/package/statuses diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/codes.json b/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/codes.json new file mode 100644 index 0000000..4c45a88 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/codes.json @@ -0,0 +1,64 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "(Unused)", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} \ No newline at end of file diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/index.js b/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/index.js new file mode 100644 index 0000000..b06182d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/index.js @@ -0,0 +1,60 @@ + +var codes = require('./codes.json'); + +module.exports = status; + +// [Integer...] +status.codes = Object.keys(codes).map(function (code) { + code = ~~code; + var msg = codes[code]; + status[code] = msg; + status[msg] = status[msg.toLowerCase()] = code; + return code; +}); + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true, +}; + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true, +}; + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true, +}; + +function status(code) { + if (typeof code === 'number') { + if (!status[code]) throw new Error('invalid status code: ' + code); + return code; + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string'); + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n); + return n; + } + + n = status[code.toLowerCase()]; + if (!n) throw new Error('invalid status message: "' + code + '"'); + return n; +} diff --git a/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/package.json b/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/package.json new file mode 100644 index 0000000..81aba72 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/node_modules/statuses/package.json @@ -0,0 +1,84 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "1.2.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/statuses.git" + }, + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "0.0.6", + "istanbul": "0", + "mocha": "1", + "stream-to-array": "2" + }, + "scripts": { + "build": "node scripts/build.js", + "update": "node scripts/update.js", + "test": "mocha --reporter spec --bail --check-leaks", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks" + }, + "gitHead": "49e6ac7ae4c63ee8186f56cb52112a7eeda28ed7", + "bugs": { + "url": "https://github.com/jshttp/statuses/issues" + }, + "homepage": "https://github.com/jshttp/statuses", + "_id": "statuses@1.2.1", + "_shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "_from": "statuses@>=1.2.1 <1.3.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "tarball": "http://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/send/package.json b/5-2/service/node_modules/express/node_modules/send/package.json new file mode 100644 index 0000000..38fcf6f --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/send/package.json @@ -0,0 +1,89 @@ +{ + "name": "send", + "description": "Better streaming static file server with Range and conditional-GET support", + "version": "0.13.1", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/send.git" + }, + "keywords": [ + "static", + "file", + "server" + ], + "dependencies": { + "debug": "~2.2.0", + "depd": "~1.1.0", + "destroy": "~1.0.4", + "escape-html": "~1.0.3", + "etag": "~1.7.0", + "fresh": "0.3.0", + "http-errors": "~1.3.1", + "mime": "1.3.4", + "ms": "0.7.1", + "on-finished": "~2.3.0", + "range-parser": "~1.0.3", + "statuses": "~1.2.1" + }, + "devDependencies": { + "after": "0.8.1", + "istanbul": "0.4.2", + "mocha": "2.3.4", + "supertest": "1.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --check-leaks --reporter spec --bail", + "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": "dbce43fc7102c14b475c25cde918b726063cc991", + "bugs": { + "url": "https://github.com/pillarjs/send/issues" + }, + "homepage": "https://github.com/pillarjs/send", + "_id": "send@0.13.1", + "_shasum": "a30d5f4c82c8a9bae9ad00a1d9b1bdbe6f199ed7", + "_from": "send@0.13.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "a30d5f4c82c8a9bae9ad00a1d9b1bdbe6f199ed7", + "tarball": "http://registry.npmjs.org/send/-/send-0.13.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/send/-/send-0.13.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/serve-static/HISTORY.md b/5-2/service/node_modules/express/node_modules/serve-static/HISTORY.md new file mode 100644 index 0000000..da30741 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/serve-static/HISTORY.md @@ -0,0 +1,303 @@ +1.10.2 / 2016-01-19 +=================== + + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.10.1 / 2016-01-16 +=================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + +1.10.0 / 2015-06-17 +=================== + + * Add `fallthrough` option + - Allows declaring this middleware is the final destination + - Provides better integration with Express patterns + * Fix reading options from options prototype + * Improve the default redirect response headers + * deps: escape-html@1.0.2 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * Fix potential open redirect when mounted at root + +1.7.1 / 2014-10-22 +================== + + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +1.7.0 / 2014-10-15 +================== + + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - 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 +================== + + * Fix redirect loop when index file serving disabled + +1.6.3 / 2014-09-24 +================== + + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +1.6.2 / 2014-09-15 +================== + + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +1.6.1 / 2014-09-07 +================== + + * deps: send@0.9.1 + - deps: fresh@0.2.4 + +1.6.0 / 2014-09-07 +================== + + * deps: send@0.9.0 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + +1.5.4 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +1.5.3 / 2014-08-17 +================== + + * deps: send@0.8.3 + +1.5.2 / 2014-08-14 +================== + + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +1.5.1 / 2014-08-09 +================== + + * Fix parsing of weird `req.originalUrl` values + * deps: parseurl@~1.3.0 + * deps: utils-merge@1.0.0 + +1.5.0 / 2014-08-05 +================== + + * deps: send@0.8.1 + - Add `extensions` option + +1.4.4 / 2014-08-04 +================== + + * deps: send@0.7.4 + - Fix serving index files without root dir + +1.4.3 / 2014-07-29 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + +1.4.2 / 2014-07-27 +================== + + * deps: send@0.7.2 + - deps: depd@0.4.4 + +1.4.1 / 2014-07-26 +================== + + * deps: send@0.7.1 + - deps: depd@0.4.3 + +1.4.0 / 2014-07-21 +================== + + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +1.3.2 / 2014-07-11 +================== + + * deps: send@0.6.0 + - Cap `maxAge` value to 1 year + - deps: debug@1.0.3 + +1.3.1 / 2014-07-09 +================== + + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +1.3.0 / 2014-06-28 +================== + + * Add `setHeaders` option + * Include HTML link in redirect response + * deps: send@0.5.0 + - Accept string for `maxAge` (converted by `ms`) + +1.2.3 / 2014-06-11 +================== + + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +1.2.2 / 2014-06-09 +================== + + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + +1.2.1 / 2014-06-02 +================== + + * use `escape-html` for escaping + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +1.2.0 / 2014-05-29 +================== + + * deps: send@0.4.0 + - Calculate ETag with md5 for reduced collisions + - Fix wrong behavior when index file matches directory + - Ignore stream errors after request ends + - Skip directories in index file search + - deps: debug@0.8.1 + +1.1.0 / 2014-04-24 +================== + + * Accept options directly to `send` module + * deps: send@0.3.0 + +1.0.4 / 2014-04-07 +================== + + * Resolve relative paths at middleware setup + * Use parseurl to parse the URL from request + +1.0.3 / 2014-03-20 +================== + + * Do not rely on connect-like environments + +1.0.2 / 2014-03-06 +================== + + * deps: send@0.2.0 + +1.0.1 / 2014-03-05 +================== + + * Add mime export for back-compat + +1.0.0 / 2014-03-05 +================== + + * Genesis from `connect` diff --git a/5-2/service/node_modules/express/node_modules/serve-static/LICENSE b/5-2/service/node_modules/express/node_modules/serve-static/LICENSE new file mode 100644 index 0000000..d8cce67 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014-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: + +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/5-2/service/node_modules/express/node_modules/serve-static/README.md b/5-2/service/node_modules/express/node_modules/serve-static/README.md new file mode 100644 index 0000000..62104b1 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/serve-static/README.md @@ -0,0 +1,236 @@ +# serve-static + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +## Install + +```sh +$ npm install serve-static +``` + +## API + +```js +var serveStatic = require('serve-static') +``` + +### serveStatic(root, options) + +Create a new middleware function to serve files from within a given root +directory. The file to serve will be determined by combining `req.url` +with the provided root directory. When a file is not found, instead of +sending a 404 response, this module will instead call `next()` to move on +to the next middleware, allowing for stacking and fall-backs. + +#### 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 set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Deny a request for a dotfile and 403/`next()`. + - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. + +The default value is similar to `'ignore'`, with the exception that this +default will not ignore the files within a directory that begins with a dot. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +Set file extension fallbacks. When set, if a file is not found, the given +extensions will be added to the file name and search for. The first that +exists will be served. Example: `['html', 'htm']`. + +The default value is `false`. + +##### fallthrough + +Set the middleware to have client errors fall-through as just unhandled +requests, otherwise forward a client error. The difference is that client +errors like a bad request or a request to a non-existent file will cause +this middleware to simply `next()` to your next middleware when this value +is `true`. When this value is `false`, these errors (even 404s), will invoke +`next(err)`. + +Typically `true` is desired such that multiple physical directories can be +mapped to the same web address or for routes to fill in non-existent files. + +The value `false` can be used if this middleware is mounted at a path that +is designed to be strictly a single file system directory, which allows for +short-circuiting 404s for less overhead. This middleware will also reply to +all methods. + +The default value is `true`. + +##### index + +By default this module will send "index.html" files in response to a request +on a directory. 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. + +##### redirect + +Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. + +##### setHeaders + +Function to set custom headers on response. Alterations to the headers need to +occur synchronously. The function is called as `fn(res, path, stat)`, where +the arguments are: + + - `res` the response object + - `path` the file path that is being sent + - `stat` the stat object of the file that is being sent + +## Examples + +### Serve files with vanilla node.js http server + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', {'index': ['index.html', 'index.htm']}) + +// Create server +var server = http.createServer(function(req, res){ + var done = finalhandler(req, res) + serve(req, res, done) +}) + +// Listen +server.listen(3000) +``` + +### Serve all files as downloads + +```js +var contentDisposition = require('content-disposition') +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { + 'index': false, + 'setHeaders': setHeaders +}) + +// Set header to force download +function setHeaders(res, path) { + res.setHeader('Content-Disposition', contentDisposition(path)) +} + +// Create server +var server = http.createServer(function(req, res){ + var done = finalhandler(req, res) + serve(req, res, done) +}) + +// Listen +server.listen(3000) +``` + +### Serving using express + +#### Simple + +This is a simple example of using Express. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +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 +[npm-url]: https://npmjs.org/package/serve-static +[travis-image]: https://img.shields.io/travis/expressjs/serve-static/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/serve-static +[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 +[downloads-url]: https://npmjs.org/package/serve-static +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://gratipay.com/dougwilson/ diff --git a/5-2/service/node_modules/express/node_modules/serve-static/index.js b/5-2/service/node_modules/express/node_modules/serve-static/index.js new file mode 100644 index 0000000..0a9f494 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/serve-static/index.js @@ -0,0 +1,187 @@ +/*! + * serve-static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var escapeHtml = require('escape-html') +var parseUrl = require('parseurl') +var resolve = require('path').resolve +var send = require('send') +var url = require('url') + +/** + * Module exports. + * @public + */ + +module.exports = serveStatic +module.exports.mime = send.mime + +/** + * @param {string} root + * @param {object} [options] + * @return {function} + * @public + */ + +function serveStatic(root, options) { + if (!root) { + throw new TypeError('root path required') + } + + if (typeof root !== 'string') { + throw new TypeError('root path must be a string') + } + + // copy options object + var opts = Object.create(options || null) + + // fall-though + var fallthrough = opts.fallthrough !== false + + // default redirect + var redirect = opts.redirect !== false + + // headers listener + var setHeaders = opts.setHeaders + + if (setHeaders && typeof setHeaders !== 'function') { + throw new TypeError('option setHeaders must be function') + } + + // setup options for send + opts.maxage = opts.maxage || opts.maxAge || 0 + opts.root = resolve(root) + + // construct directory listener + var onDirectory = redirect + ? createRedirectDirectoryListener() + : createNotFoundDirectoryListener() + + return function serveStatic(req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + if (fallthrough) { + return next() + } + + // method not allowed + res.statusCode = 405 + res.setHeader('Allow', 'GET, HEAD') + res.setHeader('Content-Length', '0') + res.end() + return + } + + var forwardError = !fallthrough + var originalUrl = parseUrl.original(req) + var path = parseUrl(req).pathname + + // make sure redirect occurs at mount + if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { + path = '' + } + + // create send stream + var stream = send(req, path, opts) + + // add directory handler + stream.on('directory', onDirectory) + + // add headers listener + if (setHeaders) { + stream.on('headers', setHeaders) + } + + // add file listener for fallthrough + if (fallthrough) { + stream.on('file', function onFile() { + // once file is determined, always forward error + forwardError = true + }) + } + + // forward errors + stream.on('error', function error(err) { + if (forwardError || !(err.statusCode < 500)) { + next(err) + return + } + + next() + }) + + // pipe + stream.pipe(res) + } +} + +/** + * Collapse all leading slashes into a single slash + * @private + */ +function collapseLeadingSlashes(str) { + for (var i = 0; i < str.length; i++) { + if (str[i] !== '/') { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Create a directory listener that just 404s. + * @private + */ + +function createNotFoundDirectoryListener() { + return function notFound() { + this.error(404) + } +} + +/** + * Create a directory listener that performs a redirect. + * @private + */ + +function createRedirectDirectoryListener() { + return function redirect() { + if (this.hasTrailingSlash()) { + this.error(404) + return + } + + // get original URL + var originalUrl = parseUrl.original(this.req) + + // append trailing slash + originalUrl.path = null + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') + + // reformat the URL + var loc = url.format(originalUrl) + var msg = 'Redirecting to ' + escapeHtml(loc) + '\n' + var res = this.res + + // send redirect response + res.statusCode = 303 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(msg) + } +} diff --git a/5-2/service/node_modules/express/node_modules/serve-static/package.json b/5-2/service/node_modules/express/node_modules/serve-static/package.json new file mode 100644 index 0000000..b789b9a --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/serve-static/package.json @@ -0,0 +1,83 @@ +{ + "name": "serve-static", + "description": "Serve static files", + "version": "1.10.2", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/serve-static.git" + }, + "dependencies": { + "escape-html": "~1.0.3", + "parseurl": "~1.3.1", + "send": "0.13.1" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4", + "supertest": "1.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --reporter spec --bail --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": "aec36c897a33c6c2421fa41cc4947042d67332f6", + "bugs": { + "url": "https://github.com/expressjs/serve-static/issues" + }, + "homepage": "https://github.com/expressjs/serve-static", + "_id": "serve-static@1.10.2", + "_shasum": "feb800d0e722124dd0b00333160c16e9caa8bcb3", + "_from": "serve-static@>=1.10.2 <1.11.0", + "_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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "feb800d0e722124dd0b00333160c16e9caa8bcb3", + "tarball": "http://registry.npmjs.org/serve-static/-/serve-static-1.10.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.10.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/type-is/HISTORY.md b/5-2/service/node_modules/express/node_modules/type-is/HISTORY.md new file mode 100644 index 0000000..e10b426 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/HISTORY.md @@ -0,0 +1,192 @@ +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/5-2/service/node_modules/express/node_modules/type-is/LICENSE b/5-2/service/node_modules/express/node_modules/type-is/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +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: + +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/5-2/service/node_modules/express/node_modules/type-is/README.md b/5-2/service/node_modules/express/node_modules/type-is/README.md new file mode 100644 index 0000000..7a754be --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/README.md @@ -0,0 +1,136 @@ +# type-is + +[![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] + +Infer the content-type of a request. + +### Install + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var is = require('type-is') + +http.createServer(function (req, res) { + var istext = is(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### type = is(request, types) + +`request` is the node HTTP request. `types` is an array of types. + +```js +// req.headers.content-type = 'application/json' + +is(req, ['json']) // 'json' +is(req, ['html', 'json']) // 'json' +is(req, ['application/*']) // 'application/json' +is(req, ['application/json']) // 'application/json' + +is(req, ['html']) // false +``` + +### is.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existance works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + +```js +if (is.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### type = is.is(mediaType, types) + +`mediaType` is the [media type](https://tools.ietf.org/html/rfc6838) string. `types` is an array of types. + +```js +var mediaType = 'application/json' + +is.is(mediaType, ['json']) // 'json' +is.is(mediaType, ['html', 'json']) // 'json' +is.is(mediaType, ['application/*']) // 'application/json' +is.is(mediaType, ['application/json']) // 'application/json' + +is.is(mediaType, ['html']) // false +``` + +### Each type can be: + +- An extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` 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 or the content type is invalid. + +`null` will be returned if the request does not have a body. + +## Examples + +#### Example body parser + +```js +var is = require('type-is'); + +function bodyParser(req, res, next) { + if (!is.hasBody(req)) { + return next() + } + + switch (is(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + break + case 'json': + // parse json body + throw new Error('implement json body parsing') + break + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + break + default: + // 415 error code + res.statusCode = 415 + res.end() + return + } +} +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: https://nodejs.org/en/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[downloads-image]: https://img.shields.io/npm/dm/type-is.svg +[downloads-url]: https://npmjs.org/package/type-is diff --git a/5-2/service/node_modules/express/node_modules/type-is/index.js b/5-2/service/node_modules/express/node_modules/type-is/index.js new file mode 100644 index 0000000..ca2962e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/index.js @@ -0,0 +1,262 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var typer = require('media-typer') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis(value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody(req) { + return req.headers['transfer-encoding'] !== undefined + || !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +function typeofrequest(req, types_) { + var types = types_ + + // no body + if (!hasbody(req)) { + return null + } + + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @private + */ + +function normalize(type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @private + */ + +function mimeMatch(expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // 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) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +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 { + return normalizeType(value) + } catch (err) { + return null + } +} diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md b/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md new file mode 100644 index 0000000..62c2003 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md @@ -0,0 +1,22 @@ +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/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE b/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md b/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md new file mode 100644 index 0000000..d8df623 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md @@ -0,0 +1,81 @@ +# 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/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js b/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js new file mode 100644 index 0000000..07f7295 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js @@ -0,0 +1,270 @@ +/*! + * 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/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json b/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json new file mode 100644 index 0000000..e0f796d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json @@ -0,0 +1,58 @@ +{ + "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": "git+https://github.com/jshttp/media-typer.git" + }, + "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/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..61b54b4 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md @@ -0,0 +1,183 @@ +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +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 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md new file mode 100644 index 0000000..e26295d --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md @@ -0,0 +1,103 @@ +# mime-types + +[![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] + +The ultimate javascript content-type utility. + +Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, + so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db) +- No `.define()` functionality + +Otherwise, the API is compatible. + +## Install + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://github.com/jshttp/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[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/node/v/mime-types.svg +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js new file mode 100644 index 0000000..f7008b2 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js @@ -0,0 +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 + +/** + * 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) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..41a667a --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -0,0 +1,306 @@ +1.21.0 / 2016-01-06 +=================== + + * Add `application/emergencycalldata.comment+xml` + * Add `application/emergencycalldata.deviceinfo+xml` + * Add `application/emergencycalldata.providerinfo+xml` + * Add `application/emergencycalldata.serviceinfo+xml` + * Add `application/emergencycalldata.subscriberinfo+xml` + * Add `application/vnd.filmit.zfc` + * Add `application/vnd.google-apps.document` + * Add `application/vnd.google-apps.presentation` + * Add `application/vnd.google-apps.spreadsheet` + * Add `application/vnd.mapbox-vector-tile` + * Add `application/vnd.ms-printdevicecapabilities+xml` + * Add `application/vnd.ms-windows.devicepairing` + * Add `application/vnd.ms-windows.nwprinting.oob` + * Add `application/vnd.tml` + * Add `audio/evs` + +1.20.0 / 2015-11-10 +=================== + + * Add `application/cdni` + * Add `application/csvm+json` + * Add `application/rfc+xml` + * Add `application/vnd.3gpp.access-transfer-events+xml` + * Add `application/vnd.3gpp.srvcc-ext+xml` + * Add `application/vnd.ms-windows.wsd.oob` + * Add `application/vnd.oxli.countgraph` + * Add `application/vnd.pagerduty+json` + * Add `text/x-suse-ymp` + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.3gpp-prose-pc3ch+xml` + * Add `application/vnd.3gpp.srvcc-info+xml` + * Add `application/vnd.apple.pkpass` + * Add `application/vnd.drive+json` + +1.18.0 / 2015-09-03 +=================== + + * Add `application/pkcs12` + * Add `application/vnd.3gpp-prose+xml` + * Add `application/vnd.3gpp.mid-call+xml` + * Add `application/vnd.3gpp.state-and-event-info+xml` + * Add `application/vnd.anki` + * Add `application/vnd.firemonkeys.cloudcell` + * Add `application/vnd.openblox.game+xml` + * Add `application/vnd.openblox.game-binary` + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +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 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md new file mode 100644 index 0000000..7662440 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md @@ -0,0 +1,82 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +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 + +```bash +npm install mime-db +``` + +### 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 +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + 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 can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +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 +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[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 +[node-url]: http://nodejs.org/download/ diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json new file mode 100644 index 0000000..412ba9e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json @@ -0,0 +1,6552 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana" + }, + "application/3gpp-ims+xml": { + "source": "iana" + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana" + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana" + }, + "application/bacnet-xdd+zip": { + "source": "iana" + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana" + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana" + }, + "application/ccxml+xml": { + "source": "iana", + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana" + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana" + }, + "application/cellml+xml": { + "source": "iana" + }, + "application/cfw": { + "source": "iana" + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana" + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana" + }, + "application/cstadata+xml": { + "source": "iana" + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "extensions": ["mdp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana" + }, + "application/dicom": { + "source": "iana" + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana" + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/emergencycalldata.comment+xml": { + "source": "iana" + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana" + }, + "application/emma+xml": { + "source": "iana", + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana" + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana" + }, + "application/epub+zip": { + "source": "iana", + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana" + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false, + "extensions": ["woff"] + }, + "application/font-woff2": { + "compressible": false, + "extensions": ["woff2"] + }, + "application/framework-attributes+xml": { + "source": "iana" + }, + "application/gml+xml": { + "source": "apache", + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana" + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana" + }, + "application/ibe-pkg-reply+xml": { + "source": "iana" + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana" + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana" + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana" + }, + "application/kpml-response+xml": { + "source": "iana" + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana" + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana" + }, + "application/mathml-presentation+xml": { + "source": "iana" + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana" + }, + "application/mbms-deregister+xml": { + "source": "iana" + }, + "application/mbms-envelope+xml": { + "source": "iana" + }, + "application/mbms-msk+xml": { + "source": "iana" + }, + "application/mbms-msk-response+xml": { + "source": "iana" + }, + "application/mbms-protection-description+xml": { + "source": "iana" + }, + "application/mbms-reception-report+xml": { + "source": "iana" + }, + "application/mbms-register+xml": { + "source": "iana" + }, + "application/mbms-register-response+xml": { + "source": "iana" + }, + "application/mbms-schedule+xml": { + "source": "iana" + }, + "application/mbms-user-service-description+xml": { + "source": "iana" + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana" + }, + "application/media_control+xml": { + "source": "iana" + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mods+xml": { + "source": "iana", + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana" + }, + "application/mrb-publish+xml": { + "source": "iana" + }, + "application/msc-ivr+xml": { + "source": "iana" + }, + "application/msc-mixer+xml": { + "source": "iana" + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "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", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana" + }, + "application/parityfec": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana" + }, + "application/pidf-diff+xml": { + "source": "iana" + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana" + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/provenance+xml": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana" + }, + "application/pskc+xml": { + "source": "iana", + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf"] + }, + "application/reginfo+xml": { + "source": "iana", + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana" + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana" + }, + "application/rls-services+xml": { + "source": "iana", + "extensions": ["rs"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana" + }, + "application/samlmetadata+xml": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana" + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/sep+xml": { + "source": "iana" + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana" + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana" + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "extensions": ["ssml"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/ttml+xml": { + "source": "iana" + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana" + }, + "application/urc-ressheet+xml": { + "source": "iana" + }, + "application/urc-targetdesc+xml": { + "source": "iana" + }, + "application/urc-uisocketdesc+xml": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana" + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana" + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana" + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana" + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "extensions": ["mpkg"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avistar+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "extensions": ["cdxml"] + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana" + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana" + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana" + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume-movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana" + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana" + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana" + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana" + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana" + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana" + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana" + }, + "application/vnd.etsi.cug+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana" + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana" + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana" + }, + "application/vnd.etsi.sci+xml": { + "source": "iana" + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana" + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana" + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana" + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana" + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana" + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana" + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana" + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana" + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana" + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+xml": { + "source": "iana", + "extensions": ["lasxml"] + }, + "application/vnd.liberty-request+xml": { + "source": "iana" + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana" + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana" + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana" + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache" + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana" + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana" + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana" + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana" + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana" + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana" + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana" + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana" + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana" + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana" + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana" + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana" + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana" + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana" + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana" + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana" + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana" + }, + "application/vnd.omads-email+xml": { + "source": "iana" + }, + "application/vnd.omads-file+xml": { + "source": "iana" + }, + "application/vnd.omads-folder+xml": { + "source": "iana" + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana" + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "apache", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "apache", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "apache", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana" + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana" + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos+xml": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "apache" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana" + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana" + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana" + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana" + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana" + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana" + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana" + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana" + }, + "application/vnd.wv.ssp+xml": { + "source": "iana" + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana" + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "extensions": ["vxml"] + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/watcherinfo+xml": { + "source": "iana" + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-otf": { + "source": "apache", + "compressible": true, + "extensions": ["otf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-ttf": { + "source": "apache", + "compressible": true, + "extensions": ["ttf","ttc"] + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "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, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "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, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana" + }, + "application/xaml+xml": { + "source": "apache", + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana" + }, + "application/xcap-caps+xml": { + "source": "iana" + }, + "application/xcap-diff+xml": { + "source": "iana", + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana" + }, + "application/xcap-error+xml": { + "source": "iana" + }, + "application/xcap-ns+xml": { + "source": "iana" + }, + "application/xcon-conference-info+xml": { + "source": "iana" + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana" + }, + "application/xenc+xml": { + "source": "iana", + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache" + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana" + }, + "application/xmpp+xml": { + "source": "iana" + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yin+xml": { + "source": "iana", + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana" + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4a","m4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/opentype": { + "compressible": true, + "extensions": ["otf"] + }, + "image/bmp": { + "source": "apache", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/fits": { + "source": "iana" + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jp2": { + "source": "iana" + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana" + }, + "image/jpx": { + "source": "iana" + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana" + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana" + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tiff","tif"] + }, + "image/tiff-fx": { + "source": "iana" + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana" + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana" + }, + "image/vnd.valve.source.texture": { + "source": "iana" + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "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"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana" + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana" + }, + "message/global-delivery-status": { + "source": "iana" + }, + "message/global-disposition-notification": { + "source": "iana" + }, + "message/global-headers": { + "source": "iana" + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana" + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana" + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hjson": { + "extensions": ["hjson"] + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana" + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["markdown","md","mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "apache" + }, + "video/3gpp": { + "source": "apache", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "apache" + }, + "video/3gpp2": { + "source": "apache", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "apache" + }, + "video/bt656": { + "source": "apache" + }, + "video/celb": { + "source": "apache" + }, + "video/dv": { + "source": "apache" + }, + "video/h261": { + "source": "apache", + "extensions": ["h261"] + }, + "video/h263": { + "source": "apache", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "apache" + }, + "video/h263-2000": { + "source": "apache" + }, + "video/h264": { + "source": "apache", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "apache" + }, + "video/h264-svc": { + "source": "apache" + }, + "video/jpeg": { + "source": "apache", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "apache" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "apache", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "apache" + }, + "video/mp2p": { + "source": "apache" + }, + "video/mp2t": { + "source": "apache", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "apache", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "apache" + }, + "video/mpeg": { + "source": "apache", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "apache" + }, + "video/mpv": { + "source": "apache" + }, + "video/nv": { + "source": "apache" + }, + "video/ogg": { + "source": "apache", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "apache" + }, + "video/pointer": { + "source": "apache" + }, + "video/quicktime": { + "source": "apache", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raw": { + "source": "apache" + }, + "video/rtp-enc-aescm128": { + "source": "apache" + }, + "video/rtx": { + "source": "apache" + }, + "video/smpte292m": { + "source": "apache" + }, + "video/ulpfec": { + "source": "apache" + }, + "video/vc1": { + "source": "apache" + }, + "video/vnd.cctv": { + "source": "apache" + }, + "video/vnd.dece.hd": { + "source": "apache", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "apache", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "apache" + }, + "video/vnd.dece.pd": { + "source": "apache", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "apache", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "apache", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "apache" + }, + "video/vnd.directv.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dvb.file": { + "source": "apache", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "apache", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "apache" + }, + "video/vnd.motorola.video": { + "source": "apache" + }, + "video/vnd.motorola.videop": { + "source": "apache" + }, + "video/vnd.mpegurl": { + "source": "apache", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "apache", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "apache" + }, + "video/vnd.nokia.videovoip": { + "source": "apache" + }, + "video/vnd.objectvideo": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "apache" + }, + "video/vnd.sealed.mpeg4": { + "source": "apache" + }, + "video/vnd.sealed.swf": { + "source": "apache" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "apache" + }, + "video/vnd.uvvu.mp4": { + "source": "apache", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "apache", + "extensions": ["viv"] + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json new file mode 100644 index 0000000..e6c9732 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json @@ -0,0 +1,94 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.21.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "devDependencies": { + "bluebird": "3.1.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "1.0.1", + "gnode": "0.1.1", + "istanbul": "0.4.1", + "mocha": "1.21.5", + "raw-body": "2.1.5", + "stream-to-array": "2.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "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": "9ab92f0a912a602408a64db5741dfef6f82c597f", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "homepage": "https://github.com/jshttp/mime-db", + "_id": "mime-db@1.21.0", + "_shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "_from": "mime-db@>=1.21.0 <1.22.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" + } + ], + "dist": { + "shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json new file mode 100644 index 0000000..2e4d38a --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json @@ -0,0 +1,84 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "dependencies": { + "mime-db": "~1.21.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec test/test.js", + "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": "329f1c77e1a77c8fac59b15038e3808e9e314d96", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "homepage": "https://github.com/jshttp/mime-types", + "_id": "mime-types@2.1.9", + "_shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "_from": "mime-types@>=2.1.9 <2.2.0", + "_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" + } + ], + "dist": { + "shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/type-is/package.json b/5-2/service/node_modules/express/node_modules/type-is/package.json new file mode 100644 index 0000000..26b6fae --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/type-is/package.json @@ -0,0 +1,81 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "1.6.11", + "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": "git+https://github.com/jshttp/type-is.git" + }, + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.9" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "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/" + }, + "keywords": [ + "content", + "type", + "checking" + ], + "gitHead": "8e60e3e78aef84928e0e6c09da950f6950adcdd2", + "bugs": { + "url": "https://github.com/jshttp/type-is/issues" + }, + "homepage": "https://github.com/jshttp/type-is", + "_id": "type-is@1.6.11", + "_shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "_from": "type-is@>=1.6.6 <1.7.0", + "_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": "ritch", + "email": "skawful@gmail.com" + } + ], + "dist": { + "shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "tarball": "http://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/node_modules/utils-merge/.travis.yml b/5-2/service/node_modules/express/node_modules/utils-merge/.travis.yml new file mode 100644 index 0000000..af92b02 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/utils-merge/.travis.yml @@ -0,0 +1,6 @@ +language: "node_js" +node_js: + - "0.4" + - "0.6" + - "0.8" + - "0.10" diff --git a/5-2/service/node_modules/express/node_modules/utils-merge/LICENSE b/5-2/service/node_modules/express/node_modules/utils-merge/LICENSE new file mode 100644 index 0000000..e33bd10 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/utils-merge/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2013 Jared Hanson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-2/service/node_modules/express/node_modules/utils-merge/README.md b/5-2/service/node_modules/express/node_modules/utils-merge/README.md new file mode 100644 index 0000000..2f94e9b --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/utils-merge/README.md @@ -0,0 +1,34 @@ +# utils-merge + +Merges the properties from a source object into a destination object. + +## Install + + $ npm install utils-merge + +## Usage + +```javascript +var a = { foo: 'bar' } + , b = { bar: 'baz' }; + +merge(a, b); +// => { foo: 'bar', bar: 'baz' } +``` + +## Tests + + $ npm install + $ npm test + +[![Build Status](https://secure.travis-ci.org/jaredhanson/utils-merge.png)](http://travis-ci.org/jaredhanson/utils-merge) + +## Credits + + - [Jared Hanson](http://github.com/jaredhanson) + +## License + +[The MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> diff --git a/5-2/service/node_modules/express/node_modules/utils-merge/index.js b/5-2/service/node_modules/express/node_modules/utils-merge/index.js new file mode 100644 index 0000000..4265c69 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/utils-merge/index.js @@ -0,0 +1,23 @@ +/** + * Merge object b with object a. + * + * var a = { foo: 'bar' } + * , b = { bar: 'baz' }; + * + * merge(a, b); + * // => { foo: 'bar', bar: 'baz' } + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api public + */ + +exports = module.exports = function(a, b){ + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; +}; diff --git a/5-2/service/node_modules/express/node_modules/utils-merge/package.json b/5-2/service/node_modules/express/node_modules/utils-merge/package.json new file mode 100644 index 0000000..2f9660e --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/utils-merge/package.json @@ -0,0 +1,60 @@ +{ + "name": "utils-merge", + "version": "1.0.0", + "description": "merge() utility function", + "keywords": [ + "util" + ], + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/utils-merge.git" + }, + "bugs": { + "url": "http://github.com/jaredhanson/utils-merge/issues" + }, + "author": { + "name": "Jared Hanson", + "email": "jaredhanson@gmail.com", + "url": "http://www.jaredhanson.net/" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://www.opensource.org/licenses/MIT" + } + ], + "main": "./index", + "dependencies": {}, + "devDependencies": { + "mocha": "1.x.x", + "chai": "1.x.x" + }, + "scripts": { + "test": "mocha --reporter spec --require test/bootstrap/node test/*.test.js" + }, + "engines": { + "node": ">= 0.4.0" + }, + "_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#readme" +} diff --git a/5-2/service/node_modules/express/node_modules/vary/HISTORY.md b/5-2/service/node_modules/express/node_modules/vary/HISTORY.md new file mode 100644 index 0000000..cddbcd4 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/vary/HISTORY.md @@ -0,0 +1,23 @@ +1.0.1 / 2015-07-08 +================== + + * Fix setting empty header from empty `field` + * perf: enable strict mode + * perf: remove argument reassignments + +1.0.0 / 2014-08-10 +================== + + * Accept valid `Vary` header string as `field` + * Add `vary.append` for low-level string manipulation + * Move to `jshttp` orgainzation + +0.1.0 / 2014-06-05 +================== + + * Support array of fields to set + +0.0.0 / 2014-06-04 +================== + + * Initial release diff --git a/5-2/service/node_modules/express/node_modules/vary/LICENSE b/5-2/service/node_modules/express/node_modules/vary/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/vary/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-2/service/node_modules/express/node_modules/vary/README.md b/5-2/service/node_modules/express/node_modules/vary/README.md new file mode 100644 index 0000000..5966542 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/vary/README.md @@ -0,0 +1,91 @@ +# vary + +[![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] + +Manipulate the HTTP Vary header + +## Installation + +```sh +$ npm install vary +``` + +## API + +```js +var vary = require('vary') +``` + +### vary(res, field) + +Adds the given header `field` to the `Vary` response header of `res`. +This can be a string of a single field, a string of a valid `Vary` +header, or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. + +```js +// Append "Origin" to the Vary header of the response +vary(res, 'Origin') +``` + +### vary.append(header, field) + +Adds the given header `field` to the `Vary` response header string `header`. +This can be a string of a single field, a string of a valid `Vary` header, +or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. The new header string is returned. + +```js +// Get header string appending "Origin" to "Accept, User-Agent" +vary.append('Accept, User-Agent', 'Origin') +``` + +## Examples + +### Updating the Vary header when content is based on it + +```js +var http = require('http') +var vary = require('vary') + +http.createServer(function onRequest(req, res) { + // about to user-agent sniff + vary(res, 'User-Agent') + + var ua = req.headers['user-agent'] || '' + var isMobile = /mobi|android|touch|mini/i.test(ua) + + // serve site, depending on isMobile + res.setHeader('Content-Type', 'text/html') + res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') +}) +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/vary.svg +[npm-url]: https://npmjs.org/package/vary +[node-version-image]: https://img.shields.io/node/v/vary.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg +[travis-url]: https://travis-ci.org/jshttp/vary +[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/vary +[downloads-image]: https://img.shields.io/npm/dm/vary.svg +[downloads-url]: https://npmjs.org/package/vary diff --git a/5-2/service/node_modules/express/node_modules/vary/index.js b/5-2/service/node_modules/express/node_modules/vary/index.js new file mode 100644 index 0000000..e818dbb --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/vary/index.js @@ -0,0 +1,117 @@ +/*! + * vary + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + */ + +module.exports = vary; +module.exports.append = append; + +/** + * Variables. + */ + +var separators = /[\(\)<>@,;:\\"\/\[\]\?=\{\}\u0020\u0009]/; + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @api public + */ + +function append(header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required'); + } + + if (!field) { + throw new TypeError('field argument is required'); + } + + // get fields array + var fields = !Array.isArray(field) + ? parse(String(field)) + : field; + + // assert on invalid fields + for (var i = 0; i < fields.length; i++) { + if (separators.test(fields[i])) { + throw new TypeError('field argument contains an invalid header'); + } + } + + // existing, unspecified vary + if (header === '*') { + return header; + } + + // enumerate current values + var val = header; + var vals = parse(header.toLowerCase()); + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*'; + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase(); + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld); + val = val + ? val + ', ' + fields[i] + : fields[i]; + } + } + + return val; +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @api private + */ + +function parse(header) { + return header.trim().split(/ *, */); +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @api public + */ + +function vary(res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required'); + } + + // get existing header + var val = res.getHeader('Vary') || '' + var header = Array.isArray(val) + ? val.join(', ') + : String(val); + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val); + } +} diff --git a/5-2/service/node_modules/express/node_modules/vary/package.json b/5-2/service/node_modules/express/node_modules/vary/package.json new file mode 100644 index 0000000..8e1bee4 --- /dev/null +++ b/5-2/service/node_modules/express/node_modules/vary/package.json @@ -0,0 +1,72 @@ +{ + "name": "vary", + "description": "Manipulate the HTTP Vary header", + "version": "1.0.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "http", + "res", + "vary" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/vary.git" + }, + "devDependencies": { + "istanbul": "0.3.17", + "mocha": "2.2.5", + "supertest": "1.0.1" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "650282ff8e614731837040a23e10f51c20728392", + "bugs": { + "url": "https://github.com/jshttp/vary/issues" + }, + "homepage": "https://github.com/jshttp/vary", + "_id": "vary@1.0.1", + "_shasum": "99e4981566a286118dfb2b817357df7993376d10", + "_from": "vary@>=1.0.1 <1.1.0", + "_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": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "99e4981566a286118dfb2b817357df7993376d10", + "tarball": "http://registry.npmjs.org/vary/-/vary-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/vary/-/vary-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/express/package.json b/5-2/service/node_modules/express/package.json new file mode 100644 index 0000000..66d0e95 --- /dev/null +++ b/5-2/service/node_modules/express/package.json @@ -0,0 +1,143 @@ +{ + "name": "express", + "description": "Fast, unopinionated, minimalist web framework", + "version": "4.13.4", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "Ciaran Jessup", + "email": "ciaranj@gmail.com" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Guillermo Rauch", + "email": "rauchg@gmail.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com" + }, + { + "name": "Roman Shtylman", + "email": "shtylman+expressjs@gmail.com" + }, + { + "name": "Young Jae Sim", + "email": "hanul@hanul.me" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/express.git" + }, + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "rest", + "restful", + "router", + "app", + "api" + ], + "dependencies": { + "accepts": "~1.2.12", + "array-flatten": "1.1.1", + "content-disposition": "0.5.1", + "content-type": "~1.0.1", + "cookie": "0.1.5", + "cookie-signature": "1.0.6", + "debug": "~2.2.0", + "depd": "~1.1.0", + "escape-html": "~1.0.3", + "etag": "~1.7.0", + "finalhandler": "0.4.1", + "fresh": "0.3.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.1", + "path-to-regexp": "0.1.7", + "proxy-addr": "~1.0.10", + "qs": "4.0.0", + "range-parser": "~1.0.3", + "send": "0.13.1", + "serve-static": "~1.10.2", + "type-is": "~1.6.6", + "utils-merge": "1.0.0", + "vary": "~1.0.1" + }, + "devDependencies": { + "after": "0.8.1", + "ejs": "2.3.4", + "istanbul": "0.4.2", + "marked": "0.3.5", + "mocha": "2.3.4", + "should": "7.1.1", + "supertest": "1.1.0", + "body-parser": "~1.14.2", + "connect-redis": "~2.4.1", + "cookie-parser": "~1.4.1", + "cookie-session": "~1.2.0", + "express-session": "~1.13.0", + "jade": "~1.11.0", + "method-override": "~2.3.5", + "morgan": "~1.6.1", + "multiparty": "~4.1.2", + "vhost": "~3.0.1" + }, + "engines": { + "node": ">= 0.10.0" + }, + "files": [ + "LICENSE", + "History.md", + "Readme.md", + "index.js", + "lib/" + ], + "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/" + }, + "gitHead": "193bed2649c55c1fd362e46cd4702c773f3e7434", + "bugs": { + "url": "https://github.com/expressjs/express/issues" + }, + "homepage": "https://github.com/expressjs/express", + "_id": "express@4.13.4", + "_shasum": "3c0b76f3c77590c8345739061ec0bd3ba067ec24", + "_from": "express@*", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "3c0b76f3c77590c8345739061ec0bd3ba067ec24", + "tarball": "http://registry.npmjs.org/express/-/express-4.13.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/express/-/express-4.13.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/mongoose/.eslintignore b/5-2/service/node_modules/mongoose/.eslintignore new file mode 100644 index 0000000..235bdcd --- /dev/null +++ b/5-2/service/node_modules/mongoose/.eslintignore @@ -0,0 +1,3 @@ +docs/ +bin/ +test/triage/ diff --git a/5-2/service/node_modules/mongoose/.eslintrc.yml b/5-2/service/node_modules/mongoose/.eslintrc.yml new file mode 100644 index 0000000..c16c336 --- /dev/null +++ b/5-2/service/node_modules/mongoose/.eslintrc.yml @@ -0,0 +1,31 @@ +extends: 'eslint:recommended' + +env: + node: true + mocha: true + +rules: + comma-style: 2 + consistent-this: + - 2 + - _this + indent: + - 2 + - 2 + - SwitchCase: 1 + VariableDeclarator: 2 + keyword-spacing: 2 + no-console: 0 + no-multi-spaces: 2 + no-spaced-func: 2 + no-trailing-spaces: 2 + quotes: + - 2 + - single + semi: 2 + space-before-blocks: 2 + space-before-function-paren: + - 2 + - never + space-infix-ops: 2 + space-unary-ops: 2 diff --git a/5-2/service/node_modules/mongoose/.npmignore b/5-2/service/node_modules/mongoose/.npmignore new file mode 100644 index 0000000..377d63f --- /dev/null +++ b/5-2/service/node_modules/mongoose/.npmignore @@ -0,0 +1,16 @@ +lib-cov +**.swp +*.sw* +*.orig +.DS_Store +node_modules/ +benchmarks/ +docs/ +test/ +Makefile +CNAME +index.html +index.jade +bin/ +karma.*.js +format_deps.js diff --git a/5-2/service/node_modules/mongoose/.travis.yml b/5-2/service/node_modules/mongoose/.travis.yml new file mode 100644 index 0000000..05a3e8d --- /dev/null +++ b/5-2/service/node_modules/mongoose/.travis.yml @@ -0,0 +1,13 @@ +language: node_js +sudo: false +node_js: + - "5" + - "4" + - "0.12" + - "0.10" + - "iojs" +before_script: + - wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.6.11.tgz + - tar -zxvf mongodb-linux-x86_64-2.6.11.tgz + - mkdir -p ./data/db + - ./mongodb-linux-x86_64-2.6.11/bin/mongod --fork --nopreallocj --dbpath ./data/db --syslog --port 27017 diff --git a/5-2/service/node_modules/mongoose/CONTRIBUTING.md b/5-2/service/node_modules/mongoose/CONTRIBUTING.md new file mode 100644 index 0000000..02f24b7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/CONTRIBUTING.md @@ -0,0 +1,51 @@ +## Contributing to Mongoose + +If you have a question about Mongoose (not a bug report) please post it to either [StackOverflow](http://stackoverflow.com/questions/tagged/mongoose), our [Google Group](http://groups.google.com/group/mongoose-orm), or on the #mongoosejs irc channel on freenode. + +### Reporting bugs + +- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new). + - Please describe the issue you are experiencing, along with any associated stack trace. + - Please post code that reproduces the issue, the version of mongoose, node version, and mongodb version. + - _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_. + +### Requesting new features + +- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new). +- Please describe a use case for it +- it would be ideal to include test cases as well + +### Fixing bugs / Adding features + +- Before starting to write code, look for existing [issues](https://github.com/learnboost/mongoose/issues). That way you avoid working on something that might not be of interest or that has been addressed already in a different branch. You can create a new issue [here](https://github.com/learnboost/mongoose/issues/new). + - _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_. +- Fork the [repo](https://github.com/Automattic/mongoose) _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 + - inline documentation for new methods, class members, etc. + - 1 space between conditionals/functions, and their parenthesis and curly braces + - `if (..) {` + - `for (..) {` + - `while (..) {` + - `function(err) {` +- Write tests and make sure they pass (tests are in the [test](https://github.com/Automattic/mongoose/tree/master/test) directory). + +### Running the tests +- Open a terminal and navigate to the root of the project +- execute `npm install` to install the necessary dependencies +- execute `npm test` to run the tests (we're using [mocha](http://mochajs.org/)) + - or to execute a single test `npm test -- -g 'some regexp that matches the test description'` + - any mocha flags can be specified with `-- ` + +### Documentation + +To contribute to the [API documentation](http://mongoosejs.com/docs/api.html) just make your changes to the inline documentation of the appropriate [source code](https://github.com/Automattic/mongoose/tree/master/lib) 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. + +To contribute to the [guide](http://mongoosejs.com/docs/guide.html) or [quick start](http://mongoosejs.com/docs/index.html) docs, make your changes to the appropriate `.jade` files in the [docs](https://github.com/Automattic/mongoose/tree/master/docs) directory of the master branch and submit a pull request. Again, the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button might work for you here. + +If you'd like to preview your documentation changes, first commit your changes to your local master branch, then execute `make docs` from the project root, which switches to the gh-pages branch, merges from the master branch and builds all the static pages for you. Now execute `node static.js` from the project root which will launch a local webserver where you can browse the documentation site locally. If all looks good, submit a [pull request](https://help.github.com/articles/using-pull-requests/) to the master branch with your changes. + +### Plugins website + +The [plugins](http://plugins.mongoosejs.com/) site is also an [open source project](https://github.com/aheckmann/mongooseplugins) that you can get involved with. Feel free to fork and improve it as well! diff --git a/5-2/service/node_modules/mongoose/History.md b/5-2/service/node_modules/mongoose/History.md new file mode 100644 index 0000000..81e18b9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/History.md @@ -0,0 +1,2887 @@ +4.4.3 / 2016-02-09 +================== + * fix: upgrade to mongodb 2.1.6 to remove kerberos log output #3861 #3860 [cartuchogl](https://github.com/cartuchogl) + * fix: require('mongoose') is no longer a pseudo-promise #3856 + * fix(query): update casting for single nested docs #3820 + * fix(populate): deep populating multiple paths with same options #3808 + * docs(middleware): clarify save/validate hook order #1149 + +4.4.2 / 2016-02-05 +================== + * fix(aggregate): handle calling .cursor() with no options #3855 + * fix: upgrade mongodb driver to 2.1.5 for GridFS memory leak fix #3854 + * docs: fix schematype.html conflict #3853 #3850 #3843 + * fix(model): bluebird unhandled rejection with ensureIndexes() on init #3837 + * docs: autoIndex option for createConnection #3805 + +4.4.1 / 2016-02-03 +================== + * fix: linting broke some cases where we use `== null` as shorthand #3852 + * docs: fix up schematype.html conflict #3848 #3843 [mynameiscoffey](https://github.com/mynameiscoffey) + * fix: backwards breaking change with `.connect()` return value #3847 + * docs: downgrade dox and highlight.js to fix docs build #3845 + * docs: clean up typo #3842 [Flash-](https://github.com/Flash-) + * fix(document): storeShard handles undefined values #3841 + * chore: more linting #3838 [TrejGun](https://github.com/TrejGun) + * fix(schema): handle `text: true` as a way to declare a text index #3824 + +4.4.0 / 2016-02-02 +================== + * docs: fix expireAfterSeconds index option name #3831 [Flash-](https://github.com/Flash-) + * chore: run lint after test #3829 [ChristianMurphy](https://github.com/ChristianMurphy) + * chore: use power-assert instead of assert #3828 [TrejGun](https://github.com/TrejGun) + * chore: stricter lint #3827 [TrejGun](https://github.com/TrejGun) + * feat(types): casting moment to date #3813 [TrejGun](https://github.com/TrejGun) + * chore: comma-last lint for test folder #3810 [ChristianMurphy](https://github.com/ChristianMurphy) + * fix: upgrade async mpath, mpromise, muri, and sliced #3801 [TrejGun](https://github.com/TrejGun) + * fix(query): geo queries now return proper ES2015 promises #3800 [TrejGun](https://github.com/TrejGun) + * perf(types): use `Object.defineProperties()` for array #3799 [TrejGun](https://github.com/TrejGun) + * fix(model): mapReduce, ensureIndexes, remove, and save properly return ES2015 promises #3795 #3628 #3595 [TrejGun](https://github.com/TrejGun) + * docs: fixed dates in History.md #3791 [Jokero](https://github.com/Jokero) + * feat: connect, open, openSet, and disconnect return ES2015 promises #3790 #3622 [TrejGun](https://github.com/TrejGun) + * feat: custom type for int32 via mongoose-int32 npm package #3652 #3102 + * feat: basic custom schema type API #995 + * feat(model): `insertMany()` for more performant bulk inserts #723 + +4.3.7 / 2016-01-23 +================== + * docs: grammar fix in timestamps docs #3786 [zclancy](https://github.com/zclancy) + * fix(document): setting nested populated docs #3783 [slamuu](https://github.com/slamuu) + * fix(document): don't call post save hooks twice for pushed docs #3780 + * fix(model): handle `_id=0` correctly #3776 + * docs(middleware): async post hooks #3770 + * docs: remove confusing sentence #3765 [marcusmellis89](https://github.com/marcusmellis89) + +3.8.39 / 2016-01-15 +=================== + * fixed; casting a number to a buffer #3764 + * fixed; enumerating virtual property with nested objects #3743 [kusold](https://github.com/kusold) + +4.3.6 / 2016-01-15 +================== + * fix(types): casting a number to a buffer #3764 + * fix: add "listener" to reserved keywords #3759 + * chore: upgrade uglify #3757 [ChristianMurphy](https://github.com/ChristianMurphy) + * fix: broken execPopulate() in 4.3.5 #3755 #3753 + * fix: ability to remove() a single embedded doc #3754 + * style: comma-last in test folder #3751 [ChristianMurphy](https://github.com/ChristianMurphy) + * docs: clarify versionKey option #3747 + * fix: improve colorization for arrays #3744 [TrejGun](https://github.com/TrejGun) + * fix: webpack build #3713 + +4.3.5 / 2016-01-09 +================== + * fix(query): throw when 4th parameter to update not a function #3741 [kasselTrankos](https://github.com/kasselTrankos) + * fix(document): separate error type for setting an object to a primitive #3735 + * fix(populate): Model.populate returns ES6 promise #3734 + * fix(drivers): re-register event handlers after manual reconnect #3729 + * docs: broken links #3727 + * fix(validation): update validators run array validation #3724 + * docs: clarify the need to use markModified with in-place date ops #3722 + * fix(document): mark correct path as populated when manually populating array #3721 + * fix(aggregate): support for array pipeline argument to append #3718 [dbkup](https://github.com/dbkup) + * docs: clarify `.connect()` callback #3705 + * fix(schema): properly validate nested single nested docs #3702 + * fix(types): handle setting documentarray of wrong type #3701 + * docs: broken links #3700 + * fix(drivers): debug output properly displays '0' #3689 + +3.8.38 / 2016-01-07 +=================== + * fixed; aggregate.append an array #3730 [dbkup](https://github.com/dbkup) + +4.3.4 / 2015-12-23 +================== + * fix: upgrade mongodb driver to 2.1.2 for repl set error #3712 [sansmischevia](https://github.com/sansmischevia) + * docs: validation docs typo #3709 [ivanmaeder](https://github.com/ivanmaeder) + * style: remove unused variables #3708 [ChristianMurphy](https://github.com/ChristianMurphy) + * fix(schema): duck-typing for schemas #3703 [mgcrea](https://github.com/mgcrea) + * docs: connection sample code issue #3697 + * fix(schema): duck-typing for schemas #3693 [mgcrea](https://github.com/mgcrea) + * docs: clarify id schema option #3638 + +4.3.3 / 2015-12-18 +================== + * fix(connection): properly support 'replSet' as well as 'replset' #3688 [taxilian](https://github.com/taxilian) + * fix(document): single nested doc pre hooks called before nested doc array #3687 [aliatsis](https://github.com/aliatsis) + +4.3.2 / 2015-12-17 +================== + * fix(document): .set() into single nested schemas #3686 + * fix(connection): support 'replSet' as well as 'replset' option #3685 + * fix(document): bluebird unhandled rejection when validating doc arrays #3681 + * fix(document): hooks for doc arrays in single nested schemas #3680 + * fix(document): post hooks for single nested schemas #3679 + * fix: remove unused npm module #3674 [sybarite](https://github.com/sybarite) + * fix(model): don't swallow exceptions in nested doc save callback #3671 + * docs: update keepAlive info #3667 [ChrisZieba](https://github.com/ChrisZieba) + * fix(document): strict 'throw' throws a specific mongoose error #3662 + * fix: flakey test #3332 + * fix(query): more robust check for RegExp #2969 + +4.3.1 / 2015-12-11 +================== + * feat(aggregate): `.sample()` helper #3665 + * fix(query): bitwise query operators with buffers #3663 + * docs(migration): clarify `new` option and findByIdAndUpdate #3661 + +4.3.0 / 2015-12-09 +================== + * feat(query): support for mongodb 3.2 bitwise query operators #3660 + * style: use comma-last style consistently #3657 [ChristianMurphy](https://github.com/ChristianMurphy) + * feat: upgrade mongodb driver to 2.1.0 for full MongoDB 3.2 support #3656 + * feat(aggregate): `.lookup()` helper #3532 + +4.2.10 / 2015-12-08 +=================== + * fixed; upgraded marked #3653 [ChristianMurphy](https://github.com/ChristianMurphy) + * docs; cross-db populate #3648 + * docs; update mocha URL #3646 [ojhaujjwal](https://github.com/ojhaujjwal) + * fixed; call close callback asynchronously #3645 + * docs; virtuals.html issue #3644 [Psarna94](https://github.com/Psarna94) + * fixed; single embedded doc casting on init #3642 + * docs; validation docs improvements #3640 + +4.2.9 / 2015-12-02 +================== + * docs; defaults docs #3625 + * fix; nested numeric keys causing an embedded document crash #3623 + * fix; apply path getters before virtual getters #3618 + * fix; casting for arrays in single nested schemas #3616 + +4.2.8 / 2015-11-25 +================== + * docs; clean up README links #3612 [ReadmeCritic](https://github.com/ReadmeCritic) + * fix; ESLint improvements #3605 [ChristianMurphy](https://github.com/ChristianMurphy) + * fix; assigning single nested subdocs #3601 + * docs; describe custom logging functions in `mongoose.set()` docs #3557 + +4.2.7 / 2015-11-20 +================== + * fixed; readPreference connection string option #3600 + * fixed; pulling from manually populated arrays #3598 #3579 + * docs; FAQ about OverwriteModelError #3597 [stcruy](https://github.com/stcruy) + * fixed; setting single embedded schemas to null #3596 + * fixed; indexes for single embedded schemas #3594 + * docs; clarify projection for `findOne()` #3593 [gunar](https://github.com/gunar) + * fixed; .ownerDocument() method on single embedded schemas #3589 + * fixed; properly throw casterror for query on single embedded schema #3580 + * upgraded; mongodb driver -> 2.0.49 for reconnect issue fix #3481 + +4.2.6 / 2015-11-16 +================== + * fixed; ability to manually populate an array #3575 + * docs; clarify `isAsync` parameter to hooks #3573 + * fixed; use captureStackTrace if possible instead #3571 + * fixed; crash with buffer and update validators #3565 [johnpeb](https://github.com/johnpeb) + * fixed; update casting with operators overwrite: true #3564 + * fixed; validation with single embedded docs #3562 + * fixed; inline docs inherit parents $type key #3560 + * docs; bad grammar in populate docs #3559 [amaurymedeiros](https://github.com/amaurymedeiros) + * fixed; properly handle populate option for find() #2321 + +3.8.37 / 2015-11-16 +=================== + * fixed; use retainKeyOrder for cloning update op #3572 + +4.2.5 / 2015-11-09 +================== + * fixed; handle setting fields in pre update hooks with exec #3549 + * upgraded; ESLint #3547 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; bluebird unhandled rejections with cast errors and .exec #3543 + * fixed; min/max validators handling undefined #3539 + * fixed; standalone mongos connections #3537 + * fixed; call `.toObject()` when setting a single nested doc #3535 + * fixed; single nested docs now have methods #3534 + * fixed; single nested docs with .create() #3533 #3521 [tusbar](https://github.com/tusbar) + * docs; deep populate docs #3528 + * fixed; deep populate schema ref handling #3507 + * upgraded; mongodb driver -> 2.0.48 for sort overflow issue #3493 + * docs; clarify default ids for discriminators #3482 + * fixed; properly support .update(doc) #3221 + +4.2.4 / 2015-11-02 +================== + * fixed; upgraded `ms` package for security vulnerability #3254 [fhemberger](https://github.com/fhemberger) + * fixed; ESlint rules #3517 [ChristianMurphy](https://github.com/ChristianMurphy) + * docs; typo in aggregation docs #3513 [rafakato](https://github.com/rafakato) + * fixed; add `dontThrowCastError` option to .update() for promises #3512 + * fixed; don't double-cast buffers in node 4.x #3510 #3496 + * fixed; population with single embedded schemas #3501 + * fixed; pre('set') hooks work properly #3479 + * docs; promises guide #3441 + +4.2.3 / 2015-10-26 +================== + * docs; remove unreferenced function in middleware.jade #3506 + * fixed; handling auth with no username/password #3500 #3498 #3484 [mleanos](https://github.com/mleanos) + * fixed; more ESlint rules #3491 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; swallowing exceptions in save callback #3478 + * docs; fixed broken links in subdocs guide #3477 + * fixed; casting booleans to numbers #3475 + * fixed; report CastError for subdoc arrays in findOneAndUpdate #3468 + * fixed; geoNear returns ES6 promise #3458 + +4.2.2 / 2015-10-22 +================== + * fixed; go back to old pluralization code #3490 + +4.2.1 / 2015-10-22 +================== + * fixed; pluralization issues #3492 [ChristianMurphy](https://github.com/ChristianMurphy) + +4.2.0 / 2015-10-22 +================== + * added; support for skipVersioning for document arrays #3467 [chazmo03](https://github.com/chazmo03) + * added; ability to customize schema 'type' key #3459 #3245 + * fixed; writeConcern for index builds #3455 + * added; emit event when individual index build starts #3440 [objectiveSee](https://github.com/objectiveSee) + * added; 'context' option for update validators #3430 + * refactor; pluralization now in separate pluralize-mongoose npm module #3415 [ChristianMurphy](https://github.com/ChristianMurphy) + * added; customizable error validation messages #3406 [geronime](https://github.com/geronime) + * added; support for passing 'minimize' option to update #3381 + * added; ability to customize debug logging format #3261 + * added; baseModelName property for discriminator models #3202 + * added; 'emitIndexErrors' option #3174 + * added; 'async' option for aggregation cursor to support buffering #3160 + * added; ability to skip validation for individual save() calls #2981 + * added; single embedded schema support #2689 #585 + * added; depopulate function #2509 + +4.1.12 / 2015-10-19 +=================== + * docs; use readPreference instead of slaveOk for Query.setOptions docs #3471 [buunguyen](https://github.com/buunguyen) + * fixed; more helpful error when regexp contains null bytes #3456 + * fixed; x509 auth issue #3454 [NoxHarmonium](https://github.com/NoxHarmonium) + +3.8.36 / 2015-10-18 +=================== + * fixed; Make array props non-enumerable #3461 [boblauer](https://github.com/boblauer) + +4.1.11 / 2015-10-12 +=================== + * fixed; update timestamps for update() if they're enabled #3450 [isayme](https://github.com/isayme) + * fixed; unit test error on node 0.10 #3449 [isayme](https://github.com/isayme) + * docs; timestamp option docs #3448 [isayme](https://github.com/isayme) + * docs; fix unexpected indent #3443 [isayme](https://github.com/isayme) + * fixed; use ES6 promises for Model.prototype.remove() #3442 + * fixed; don't use unused 'safe' option for index builds #3439 + * fixed; elemMatch casting bug #3437 #3435 [DefinitelyCarter](https://github.com/DefinitelyCarter) + * docs; schema.index docs #3434 + * fixed; exceptions in save() callback getting swallowed on mongodb 2.4 #3371 + +4.1.10 / 2015-10-05 +=================== + * docs; improve virtuals docs to explain virtuals schema option #3433 [zoyaH](https://github.com/zoyaH) + * docs; MongoDB server version compatibility guide #3427 + * docs; clarify that findById and findByIdAndUpdate fire hooks #3422 + * docs; clean up Model.save() docs #3420 + * fixed; properly handle projection with just id #3407 #3412 + * fixed; infinite loop when database document is corrupted #3405 + * docs; clarify remove middleware #3388 + +4.1.9 / 2015-09-28 +================== + * docs; minlength and maxlength string validation docs #3368 #3413 [cosmosgenius](https://github.com/cosmosgenius) + * fixed; linting for infix operators #3397 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; proper casting for $all #3394 + * fixed; unhandled rejection warnings with .create() #3391 + * docs; clarify update validators on paths that aren't explicitly set #3386 + * docs; custom validator examples #2778 + +4.1.8 / 2015-09-21 +================== + * docs; fixed typo in example #3390 [kmctown](https://github.com/kmctown) + * fixed; error in toObject() #3387 [guumaster](https://github.com/guumaster) + * fixed; handling for casting null dates #3383 [alexmingoia](https://github.com/alexmingoia) + * fixed; passing composite ids to `findByIdAndUpdate` #3380 + * fixed; linting #3376 #3375 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; added NodeJS v4 to Travis #3374 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; casting $elemMatch inside of $not #3373 [gaguirre](https://github.com/gaguirre) + * fixed; handle case where $slice is 0 #3369 + * fixed; avoid running getters if path is populated #3357 + * fixed; cast documents to objects when setting to a nested path #3346 + +4.1.7 / 2015-09-14 +================== + * docs; typos in SchemaType documentation #3367 [jasson15](https://github.com/jasson15) + * fixed; MONGOOSE_DRIVER_PATH env variable again #3360 + * docs; added validateSync docs #3353 + * fixed; set findOne op synchronously in query #3344 + * fixed; handling for `.pull()` on a documentarray without an id #3341 + * fixed; use natural order for cloning update conditions #3338 + * fixed; issue with strict mode casting for mixed type updates #3337 + +4.1.6 / 2015-09-08 +================== + * fixed; MONGOOSE_DRIVER_PATH env variable #3345 [g13013](https://github.com/g13013) + * docs; global autoIndex option #3335 [albertorestifo](https://github.com/albertorestifo) + * docs; model documentation typos #3330 + * fixed; report reason for CastError #3320 + * fixed; .populate() no longer returns true after re-assigning #3308 + * fixed; discriminators with aggregation geoNear #3304 + * docs; discriminator docs #2743 + +4.1.5 / 2015-09-01 +================== + * fixed; document.remove() removing all docs #3326 #3325 + * fixed; connect() checks for rs_name in options #3299 + * docs; examples for schema.set() #3288 + * fixed; checkKeys issue with bluebird #3286 [gregthegeek](https://github.com/gregthegeek) + +4.1.4 / 2015-08-31 +================== + * fixed; ability to set strict: false for update #3305 + * fixed; .create() properly uses ES6 promises #3297 + * fixed; pre hooks on nested subdocs #3291 #3284 [aliatsis](https://github.com/aliatsis) + * docs; remove unclear text in .remove() docs #3282 + * fixed; pre hooks called twice for 3rd-level nested doc #3281 + * fixed; nested transforms #3279 + * upgraded; mquery -> 1.6.3 #3278 #3272 + * fixed; don't swallow callback errors by default #3273 #3222 + * fixed; properly get nested paths from nested schemas #3265 + * fixed; remove() with id undefined deleting all docs #3260 [thanpolas](https://github.com/thanpolas) + * fixed; handling for non-numeric projections #3256 + * fixed; findById with id undefined returning first doc #3255 + * fixed; use retainKeyOrder for update #3215 + * added; passRawResult option to findOneAndUpdate for backwards compat #3173 + +4.1.3 / 2015-08-16 +================== + * fixed; getUpdate() in pre update hooks #3520 [gregthegeek](https://github.com/gregthegeek) + * fixed; handleArray() ensures arg is an array #3238 [jloveridge](https://github.com/jloveridge) + * fixed; refresh required path cache when recreating docs #3199 + * fixed; $ operator on unwind aggregation helper #3197 + * fixed; findOneAndUpdate() properly returns raw result as third arg to callback #3173 + * fixed; querystream with dynamic refs #3108 + +3.8.35 / 2015-08-14 +=================== + * fixed; handling for minimize on nested objects #2930 + * fixed; don't crash when schema.path.options undefined #1824 + +4.1.2 / 2015-08-10 +================== + * fixed; better handling for Jade templates #3241 [kbadk](https://github.com/kbadk) + * added; ESlint trailing spaces #3234 [ChristianMurphy](https://github.com/ChristianMurphy) + * added; ESlint #3191 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; properly emit event on disconnect #3183 + * fixed; copy options properly using Query.toConstructor() #3176 + * fixed; setMaxListeners() issue in browser build #3170 + * fixed; node driver -> 2.0.40 to not store undefined keys as null #3169 + * fixed; update validators handle positional operator #3167 + * fixed; handle $all + $elemMatch query casting #3163 + * fixed; post save hooks don't swallow extra args #3155 + * docs; spelling mistake in index.jade #3154 + * fixed; don't crash when toObject() has no fields #3130 + * fixed; apply toObject() recursively for find and update queries #3086 [naoina](https://github.com/naoina) + +4.1.1 / 2015-08-03 +================== + * fixed; aggregate exec() crash with no callback #3212 #3198 [jpgarcia](https://github.com/jpgarcia) + * fixed; pre init hooks now properly synchronous #3207 [burtonjc](https://github.com/burtonjc) + * fixed; updateValidators doesn't flatten dates #3206 #3194 [victorkohl](https://github.com/victorkohl) + * fixed; default fields don't make document dirty between saves #3205 [burtonjc](https://github.com/burtonjc) + * fixed; save passes 0 as numAffected rather than undefined when no change #3195 [burtonjc](https://github.com/burtonjc) + * fixed; better handling for positional operator in update #3185 + * fixed; use Travis containers #3181 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; leaked variable #3180 [ChristianMurphy](https://github.com/ChristianMurphy) + +4.1.0 / 2015-07-24 +================== + * added; `schema.queue()` now public #3193 + * added; raw result as third parameter to findOneAndX callback #3173 + * added; ability to run validateSync() on only certain fields #3153 + * added; subPopulate #3103 [timbur](https://github.com/timbur) + * added; $isDefault function on documents #3077 + * added; additional properties for built-in validator messages #3063 [KLicheR](https://github.com/KLicheR) + * added; getQuery() and getUpdate() functions for Query #3013 + * added; export DocumentProvider #2996 + * added; ability to remove path from schema #2993 [JohnnyEstilles](https://github.com/JohnnyEstilles) + * added; .explain() helper for aggregate #2714 + * added; ability to specify which ES6-compatible promises library mongoose uses #2688 + * added; export Aggregate #1910 + +4.0.8 / 2015-07-20 +================== + * fixed; assignment with document arrays #3178 [rosston](https://github.com/rosston) + * docs; remove duplicate paragraph #3164 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * docs; improve findOneAndXYZ parameter descriptions #3159 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * docs; add findOneAndRemove to list of supported middleware #3158 + * docs; clarify ensureIndex #3156 + * fixed; refuse to save/remove document without id #3118 + * fixed; hooks next() no longer accidentally returns promise #3104 + * fixed; strict mode for findOneAndUpdate #2947 + * added; .min.js.gz file for browser component #2806 + +3.8.34 / 2015-07-20 +=================== + * fixed; allow using $rename #3171 + * fixed; no longer modifies update arguments #3008 + +4.0.7 / 2015-07-11 +================== + * fixed; documentarray id method when using object id #3157 [siboulet](https://github.com/siboulet) + * docs; improve findById docs #3147 + * fixed; update validators handle null properly #3136 [odeke-em](https://github.com/odeke-em) + * docs; jsdoc syntax errors #3128 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * docs; fix typo #3126 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * docs; proper formatting in queries.jade #3121 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * docs; correct example for string maxlength validator #3111 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * fixed; setDefaultsOnInsert with arrays #3107 + * docs; LearnBoost -> Automattic in package.json #3099 + * docs; pre update hook example #3094 [danpe](https://github.com/danpe) + * docs; clarify query middleware example #3051 + * fixed; ValidationErrors in strict mode #3046 + * fixed; set findOneAndUpdate properties before hooks run #3024 + +3.8.33 / 2015-07-10 +=================== + * upgraded; node driver -> 1.4.38 + * fixed; dont crash when `match` validator undefined + +4.0.6 / 2015-06-21 +================== + * upgraded; node driver -> 2.0.34 #3087 + * fixed; apply setters on addToSet, etc #3067 [victorkohl](https://github.com/victorkohl) + * fixed; missing semicolons #3065 [sokolikp](https://github.com/sokolikp) + * fixed; proper handling for async doc hooks #3062 [gregthegeek](https://github.com/gregthegeek) + * fixed; dont set failed populate field to null if other docs are successfully populated #3055 [eloytoro](https://github.com/eloytoro) + * fixed; setDefaultsOnInsert with document arrays #3034 [taxilian](https://github.com/taxilian) + * fixed; setters fired on array items #3032 + * fixed; stop validateSync() on first error #3025 [victorkohl](https://github.com/victorkohl) + * docs; improve query docs #3016 + * fixed; always exclude _id when its deselected #3010 + * fixed; enum validator kind property #3009 + * fixed; mquery collection names #3005 + * docs; clarify mongos option #3000 + * docs; clarify that query builder has a .then() #2995 + * fixed; race condition in dynamic ref #2992 + +3.8.31 / 2015-06-20 +=================== + * fixed; properly handle text search with discriminators and $meta #2166 + +4.0.5 / 2015-06-05 +================== + * fixed; ObjectIds and buffers when mongodb driver is a sibling dependency #3050 #3048 #3040 #3031 #3020 #2988 #2951 + * fixed; warn user when 'increment' is used in schema #3039 + * fixed; setDefaultsOnInsert with array in schema #3035 + * fixed; dont use default Object toString to cast to string #3030 + * added; npm badge #3020 [odeke-em](https://github.com/odeke-em) + * fixed; proper handling for calling .set() with a subdoc #2782 + * fixed; dont throw cast error when using $rename on non-string path #1845 + +3.8.30 / 2015-06-05 +=================== + * fixed; enable users to set all options with tailable() #2883 + +4.0.4 / 2015-05-28 +================== + * docs; findAndModify new parameter correct default value #3012 [JonForest](https://github.com/JonForest) + * docs; clarify pluralization rules #2999 [anonmily](https://github.com/anonmily) + * fix; discriminators with schema methods #2978 + * fix; make `isModified` a schema reserved keyword #2975 + * fix; properly fire setters when initializing path with object #2943 + * fix; can use `setDefaultsOnInsert` without specifying `runValidators` #2938 + * fix; always set validation errors `kind` property #2885 + * upgraded; node driver -> 2.0.33 #2865 + +3.8.29 / 2015-05-27 +=================== + * fixed; Handle JSON.stringify properly for nested docs #2990 + +4.0.3 / 2015-05-13 +================== + * upgraded; mquery -> 1.5.1 #2983 + * docs; clarify context for query middleware #2974 + * docs; fix missing type -> kind rename in History.md #2961 + * fixed; broken ReadPreference include on Heroku #2957 + * docs; correct form for cursor aggregate option #2955 + * fixed; sync post hooks now properly called after function #2949 #2925 + * fixed; fix sub-doc validate() function #2929 + * upgraded; node driver -> 2.0.30 #2926 + * docs; retainKeyOrder for save() #2924 + * docs; fix broken class names #2913 + * fixed; error when using node-clone on a doc #2909 + * fixed; no more hard references to bson #2908 #2906 + * fixed; dont overwrite array values #2907 [naoina](https://github.com/naoina) + * fixed; use readPreference=primary for findOneAndUpdate #2899 #2823 + * docs; clarify that update validators only run on $set and $unset #2889 + * fixed; set kind consistently for built-in validators #2885 + * docs; single field populated documents #2884 + * fixed; nested objects are now enumerable #2880 [toblerpwn](https://github.com/toblerpwn) + * fixed; properly populate field when ref, lean, stream used together #2841 + * docs; fixed migration guide jade error #2807 + +3.8.28 / 2015-05-12 +=================== + * fixed; proper handling for toJSON options #2910 + * fixed; dont attach virtuals to embedded docs in update() #2046 + +4.0.2 / 2015-04-23 +================== + * fixed; error thrown when calling .validate() on subdoc not in an array #2902 + * fixed; rename define() to play nice with webpack #2900 [jspears](https://github.com/jspears) + * fixed; pre validate called twice with discriminators #2892 + * fixed; .inspect() on mongoose.Types #2875 + * docs; correct callback params for Model.update #2872 + * fixed; setDefaultsOnInsert now works when runValidators not specified #2870 + * fixed; Document now wraps EventEmitter.addListener #2867 + * fixed; call non-hook functions in schema queue #2856 + * fixed; statics can be mocked out for tests #2848 [ninelb](https://github.com/ninelb) + * upgraded; mquery 1.4.0 for bluebird bug fix #2846 + * fixed; required validators run first #2843 + * docs; improved docs for new option to findAndMody #2838 + * docs; populate example now uses correct field #2837 [swilliams](https://github.com/swilliams) + * fixed; pre validate changes causing VersionError #2835 + * fixed; get path from correct place when setting CastError #2832 + * docs; improve docs for Model.update() function signature #2827 [irnc](https://github.com/irnc) + * fixed; populating discriminators #2825 [chetverikov](https://github.com/chetverikov) + * fixed; discriminators with nested schemas #2821 + * fixed; CastErrors with embedded docs #2819 + * fixed; post save hook context #2816 + * docs; 3.8.x -> 4.x migration guide #2807 + * fixed; proper _distinct copying for query #2765 [cdelauder](https://github.com/cdelauder) + +3.8.27 / 2015-04-22 +=================== + * fixed; dont duplicate db calls on Q.ninvoke() #2864 + * fixed; Model.find arguments naming in docs #2828 + * fixed; Support ipv6 in connection strings #2298 + +3.8.26 / 2015-04-07 +=================== + * fixed; TypeError when setting date to undefined #2833 + * fixed; handle CastError properly in distinct() with no callback #2786 + * fixed; broken links in queries docs #2779 + * fixed; dont mark buffer as modified when setting type initially #2738 + * fixed; dont crash when using slice with populate #1934 + +4.0.1 / 2015-03-28 +================== + * fixed; properly handle empty cast doc in update() with promises #2796 + * fixed; unstable warning #2794 + * fixed; findAndModify docs now show new option is false by default #2793 + +4.0.0 / 2015-03-25 +================== + * fixed; on-the-fly schema docs typo #2783 [artiifix](https://github.com/artiifix) + * fixed; cast error validation handling #2775 #2766 #2678 + * fixed; discriminators with populate() #2773 #2719 [chetverikov](https://github.com/chetverikov) + * fixed; increment now a reserved path #2709 + * fixed; avoid sending duplicate object ids in populate() #2683 + * upgraded; mongodb to 2.0.24 to properly emit reconnect event multiple times #2656 + +4.0.0-rc4 / 2015-03-14 +====================== + * fixed; toObject virtuals schema option handled properly #2751 + * fixed; update validators work on document arrays #2733 + * fixed; check for cast errors on $set #2729 + * fixed; instance field set for all schema types #2727 [csdco](https://github.com/csdco) + * fixed; dont run other validators if required fails #2725 + * fixed; custom getters execute on ref paths #2610 + * fixed; save defaults if they were set when doc was loaded from db #2558 + * fixed; pre validate now runs before pre save #2462 + * fixed; no longer throws errors with --use_strict #2281 + +3.8.25 / 2015-03-13 +=================== + * fixed; debug output reverses order of aggregation keys #2759 + * fixed; $eq is a valid query selector in 3.0 #2752 + * fixed; upgraded node driver to 1.4.32 for handling non-numeric poolSize #2682 + * fixed; update() with overwrite sets _id for nested docs #2658 + * fixed; casting for operators in $elemMatch #2199 + +4.0.0-rc3 / 2015-02-28 +====================== + * fixed; update() pre hooks run before validators #2706 + * fixed; setters not called on arrays of refs #2698 [brandom](https://github.com/brandom) + * fixed; use node driver 2.0.18 for nodejs 0.12 support #2685 + * fixed; comments reference file that no longer exists #2681 + * fixed; populated() returns _id of manually populated doc #2678 + * added; ability to exclude version key in toObject() #2675 + * fixed; dont allow setting nested path to a string #2592 + * fixed; can cast objects with _id field to ObjectIds #2581 + * fixed; on-the-fly schema getters #2360 + * added; strict option for findOneAndUpdate() #1967 + +3.8.24 / 2015-02-25 +=================== + * fixed; properly apply child schema transforms #2691 + * fixed; make copy of findOneAndUpdate options before modifying #2687 + * fixed; apply defaults when parent path is selected #2670 #2629 + * fixed; properly get ref property for nested paths #2665 + * fixed; node driver makes copy of authenticate options before modifying them #2619 + * fixed; dont block process exit when auth fails #2599 + * fixed; remove redundant clone in update() #2537 + +4.0.0-rc2 / 2015-02-10 +====================== + * added; io.js to travis build + * removed; browser build dependencies not installed by default + * added; dynamic refpaths #2640 [chetverikov](https://github.com/chetverikov) + * fixed; dont call child schema transforms on parent #2639 [chetverikov](https://github.com/chetverikov) + * fixed; get rid of remove option if new is set in findAndModify #2598 + * fixed; aggregate all document array validation errors #2589 + * fixed; custom setters called when setting value to undefined #1892 + +3.8.23 / 2015-02-06 +=================== + * fixed; unset opts.remove when upsert is true #2519 + * fixed; array saved as object when path is object in array #2442 + * fixed; inline transforms #2440 + * fixed; check for callback in count() #2204 + * fixed; documentation for selecting fields #1534 + +4.0.0-rc1 / 2015-02-01 +====================== + * fixed; use driver 2.0.14 + * changed; use transform: true by default #2245 + +4.0.0-rc0 / 2015-01-31 +=================== + * fixed; wrong order for distinct() params #2628 + * fixed; handling no query argument to remove() #2627 + * fixed; createModel and discriminators #2623 [ashaffer](https://github.com/ashaffer) + * added; pre('count') middleware #2621 + * fixed; double validation calls on document arrays #2618 + * added; validate() catches cast errors #2611 + * fixed; respect replicaSet parameter in connection string #2609 + * added; can explicitly exclude paths from versioning #2576 [csabapalfi](https://github.com/csabapalfi) + * upgraded; driver to 2.0.15 #2552 + * fixed; save() handles errors more gracefully in ES6 #2371 + * fixed; undefined is now a valid argument to findOneAndUpdate #2272 + * changed; `new` option to findAndModify ops is false by default #2262 + +3.8.22 / 2015-01-24 +=================== + * upgraded; node-mongodb-native to 1.4.28 #2587 [Climax777](https://github.com/Climax777) + * added; additional documentation for validators #2449 + * fixed; stack overflow when creating massive arrays #2423 + * fixed; undefined is a valid id for queries #2411 + * fixed; properly create nested schema index when same schema used twice #2322 + * added; link to plugin generator in docs #2085 [huei90](https://github.com/huei90) + * fixed; optional arguments documentation for findOne() #1971 [nachinius](https://github.com/nachinius) + +3.9.7 / 2014-12-19 +=================== + * added; proper cursors for aggregate #2539 [changyy](https://github.com/changyy) + * added; min/max built-in validators for dates #2531 [bshamblen](https://github.com/bshamblen) + * fixed; save and validate are now reserved keywords #2380 + * added; basic documentation for browser component #2256 + * added; find and findOne hooks (query middleware) #2138 + * fixed; throw a DivergentArrayError when saving positional operator queries #2031 + * added; ability to use options as a document property #1416 + * fixed; document no longer inherits from event emitter and so domain and _events are no longer reserved #1351 + * removed; setProfiling #1349 + +3.8.21 / 2014-12-18 +=================== + * fixed; syntax in index.jade #2517 [elderbas](https://github.com/elderbas) + * fixed; writable statics #2510 #2528 + * fixed; overwrite and explicit $set casting #2515 + +3.9.6 / 2014-12-05 +=================== + * added; correctly run validators on each element of array when entire array is modified #661 #1227 + * added; castErrors in validation #1013 [jondavidjohn](https://github.com/jondavidjohn) + * added; specify text indexes in schema fields #1401 [sr527](https://github.com/sr527) + * added; ability to set field with validators to undefined #1594 [alabid](https://github.com/alabid) + * added; .create() returns an array when passed an array #1746 [alabid](https://github.com/alabid) + * added; test suite and docs for use with co and yield #2177 #2474 + * fixed; subdocument toObject() transforms #2447 [chmanie](https://github.com/chmanie) + * fixed; Model.create() with save errors #2484 + * added; pass options to .save() and .remove() #2494 [jondavidjohn](https://github.com/jondavidjohn) + +3.8.20 / 2014-12-01 +=================== + * fixed; recursive readPref #2490 [kjvalencik](https://github.com/kjvalencik) + * fixed; make sure to copy parameters to update() before modifying #2406 [alabid](https://github.com/alabid) + * fixed; unclear documentation about query callbacks #2319 + * fixed; setting a schema-less field to an empty object #2314 [alabid](https://github.com/alabid) + * fixed; registering statics and methods for discriminators #2167 [alabid](https://github.com/alabid) + +3.9.5 / 2014-11-10 +=================== + * added; ability to disable autoIndex on a per-connection basis #1875 [sr527](https://github.com/sr527) + * fixed; `geoNear()` no longer enforces legacy coordinate pairs - supports GeoJSON #1987 [alabid](https://github.com/alabid) + * fixed; browser component works when minified with mangled variable names #2302 + * fixed; `doc.errors` now cleared before `validate()` called #2302 + * added; `execPopulate()` function to make `doc.populate()` compatible with promises #2317 + * fixed; `count()` no longer throws an error when used with `sort()` #2374 + * fixed; `save()` no longer recursively calls `save()` on populated fields #2418 + +3.8.19 / 2014-11-09 +=================== + * fixed; make sure to not override subdoc _ids on find #2276 [alabid](https://github.com/alabid) + * fixed; exception when comparing two documents when one lacks _id #2333 [slawo](https://github.com/slawo) + * fixed; getters for properties with non-strict schemas #2439 [alabid](https://github.com/alabid) + * fixed; inconsistent URI format in docs #2414 [sr527](https://github.com/sr527) + +3.9.4 / 2014-10-25 +================== + * fixed; statics no longer can be overwritten #2343 [nkcmr](https://github.com/chetverikov) + * added; ability to set single populated paths to documents #1530 + * added; setDefaultsOnInsert and runValidator options for findOneAndUpdate() #860 + +3.8.18 / 2014-10-22 +================== + * fixed; Dont use all toObject options in save #2340 [chetverikov](https://github.com/chetverikov) + +3.9.3 / 2014-10-01 +================= + * added; support for virtuals that return objects #2294 + * added; ability to manually hydrate POJOs into mongoose objects #2292 + * added; setDefaultsOnInsert and runValidator options for update() #860 + +3.8.17 / 2014-09-29 +================== + * fixed; use schema options retainKeyOrder in save() #2274 + * fixed; fix skip in populate when limit is set #2252 + * fixed; fix stack overflow when passing MongooseArray to findAndModify #2214 + * fixed; optimize .length usage in populate #2289 + +3.9.2 / 2014-09-08 +================== + * added; test coverage for browser component #2255 + * added; in-order execution of validators #2243 + * added; custom fields for validators #2132 + * removed; exception thrown when find() used with count() #1950 + +3.8.16 / 2014-09-08 +================== + * fixed; properly remove modified array paths if array has been overwritten #1638 + * fixed; key check errors #1884 + * fixed; make sure populate on an array always returns a Mongoose array #2214 + * fixed; SSL connections with node 0.11 #2234 + * fixed; return sensible strings for promise errors #2239 + +3.9.1 / 2014-08-17 +================== + * added; alpha version of browser-side schema validation #2254 + * added; support passing a function to schemas `required` field #2247 + * added; support for setting updatedAt and createdAt timestamps #2227 + * added; document.validate() returns a promise #2131 + +3.8.15 / 2014-08-17 +================== + * fixed; Replica set connection string example in docs #2246 + * fixed; bubble up parseError event #2229 + * fixed; removed buggy populate cache #2176 + * fixed; dont $inc versionKey if its being $set #1933 + * fixed; cast $or and $and in $pull #1932 + * fixed; properly cast to schema in stream() #1862 + * fixed; memory leak in nested objects #1565 #2211 [devongovett](https://github.com/devongovett) + +3.8.14 / 2014-07-26 +================== + * fixed; stringifying MongooseArray shows nested arrays #2002 + * fixed; use populated doc schema in toObject and toJSON by default #2035 + * fixed; dont crash on arrays containing null #2140 + * fixed; model.update w/ upsert has same return values on .exec and promise #2143 + * fixed; better handling for populate limit with multiple documents #2151 + * fixed; dont prevent users from adding weights to text index #2183 + * fixed; helper for aggregation cursor #2187 + * updated; node-mongodb-native to 1.4.7 + +3.8.13 / 2014-07-15 +================== + * fixed; memory leak with isNew events #2159 + * fixed; docs for overwrite option for update() #2144 + * fixed; storeShard() handles dates properly #2127 + * fixed; sub-doc changes not getting persisted to db after save #2082 + * fixed; populate with _id: 0 actually removes _id instead of setting to undefined #2123 + * fixed; save versionKey on findOneAndUpdate w/ upsert #2122 + * fixed; fix typo in 2.8 docs #2120 [shakirullahi](https://github.com/shakirullahi) + * fixed; support maxTimeMs #2102 [yuukinajima](https://github.com/yuukinajima) + * fixed; support $currentDate #2019 + * fixed; $addToSet handles objects without _ids properly #1973 + * fixed; dont crash on invalid nearSphere query #1874 + +3.8.12 / 2014-05-30 +================== + * fixed; single-server reconnect event fires #1672 + * fixed; sub-docs not saved when pushed into populated array #1794 + * fixed; .set() sometimes converts embedded docs to pojos #1954 [archangel-irk](https://github.com/archangel-irk) + * fixed; sub-doc changes not getting persisted to db after save #2082 + * fixed; custom getter might cause mongoose to mistakenly think a path is dirty #2100 [pgherveou](https://github.com/pgherveou) + * fixed; chainable helper for allowDiskUse option in aggregation #2114 + +3.9.0 (unstable) / 2014-05-22 +================== + * changed; added `domain` to reserved keywords #1338 #2052 [antoinepairet](https://github.com/antoinepairet) + * added; asynchronous post hooks #1977 #2081 [chopachom](https://github.com/chopachom) [JasonGhent](https://github.com/JasonGhent) + * added; using model for population, cross-db populate [mihai-chiorean](https://github.com/mihai-chiorean) + * added; can define a type for schema validators + * added; `doc.remove()` returns a promise #1619 [refack](https://github.com/refack) + * added; internal promises for hooks, pre-save hooks run in parallel #1732 [refack](https://github.com/refack) + * fixed; geoSearch hanging when no results returned #1846 [ghartnett](https://github.com/ghartnett) + * fixed; do not set .type property on ValidationError, use .kind instead #1323 + +3.8.11 / 2014-05-22 +================== + * updated; node-mongodb-native to 1.4.5 + * reverted; #2052, fixes #2097 + +3.8.10 / 2014-05-20 +================== + + * updated; node-mongodb-native to 1.4.4 + * fixed; _.isEqual false negatives bug in js-bson #2070 + * fixed; missing check for schema.options #2014 + * fixed; missing support for $position #2024 + * fixed; options object corruption #2049 + * fixed; improvements to virtuals docs #2055 + * fixed; added `domain` to reserved keywords #2052 #1338 + +3.8.9 / 2014-05-08 +================== + + * updated; mquery to 0.7.0 + * updated; node-mongodb-native to 1.4.3 + * fixed; $near failing against MongoDB 2.6 + * fixed; relying on .options() to determine if collection exists + * fixed; $out aggregate helper + * fixed; all test failures against MongoDB 2.6.1, with caveat #2065 + +3.8.8 / 2014-02-22 +================== + + * fixed; saving Buffers #1914 + * updated; expose connection states for user-land #1926 [yorkie](https://github.com/yorkie) + * updated; mquery to 0.5.3 + * updated; added get / set to reserved path list #1903 [tstrimple](https://github.com/tstrimple) + * docs; README code highlighting, syntax fixes #1930 [IonicaBizau](https://github.com/IonicaBizau) + * docs; fixes link in the doc at #1925 [kapeels](https://github.com/kapeels) + * docs; add a missed word 'hook' for the description of the post-hook api #1924 [ipoval](https://github.com/ipoval) + +3.8.7 / 2014-02-09 +================== + + * fixed; sending safe/read options in Query#exec #1895 + * fixed; findOneAnd..() with sort #1887 + +3.8.6 / 2014-01-30 +================== + + * fixed; setting readPreferences #1895 + +3.8.5 / 2014-01-23 +================== + + * fixed; ssl setting when using URI #1882 + * fixed; findByIdAndUpdate now respects the overwrite option #1809 [owenallenaz](https://github.com/owenallenaz) + +3.8.4 / 2014-01-07 +================== + + * updated; mongodb driver to 1.3.23 + * updated; mquery to 0.4.1 + * updated; mpromise to 0.4.3 + * fixed; discriminators now work when selecting fields #1820 [daemon1981](https://github.com/daemon1981) + * fixed; geoSearch with no results timeout #1846 [ghartnett](https://github.com/ghartnett) + * fixed; infitite recursion in ValidationError #1834 [chetverikov](https://github.com/chetverikov) + +3.8.3 / 2013-12-17 +================== + + * fixed; setting empty array with model.update #1838 + * docs; fix url + +3.8.2 / 2013-12-14 +================== + + * fixed; enum validation of multiple values #1778 [heroicyang](https://github.com/heroicyang) + * fixed; global var leak #1803 + * fixed; post remove now fires on subdocs #1810 + * fixed; no longer set default empty array for geospatial-indexed fields #1668 [shirish87](https://github.com/shirish87) + * fixed; model.stream() not hydrating discriminators correctly #1792 [j](https://github.com/j) + * docs: Stablility -> Stability [nikmartin](https://github.com/nikmartin) + * tests; improve shard error handling + +3.8.1 / 2013-11-19 +================== + + * fixed; mishandling of Dates with minimize/getters #1764 + * fixed; Normalize bugs.email, so `npm` will shut up #1769 [refack](https://github.com/refack) + * docs; Improve the grammar where "lets us" was used #1777 [alexyoung](https://github.com/alexyoung) + * docs; Fix some grammatical issues in the documentation #1777 [alexyoung](https://github.com/alexyoung) + * docs; fix Query api exposure + * docs; fix return description + * docs; Added Notes on findAndUpdate() #1750 [sstadelman](https://github.com/sstadelman) + * docs; Update version number in README #1762 [Fodi69](https://github.com/Fodi69) + +3.8.0 / 2013-10-31 +================== + + * updated; warn when using an unstable version + * updated; error message returned in doc.save() #1595 + * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) + * updated; mquery to 0.3.2 + * updated; mocha to 1.12.0 + * updated; mpromise 0.3.0 + * updated; sliced 0.0.5 + * removed; mongoose.Error.DocumentError (never used) + * removed; namedscope (undocumented and broken) #679 #642 #455 #379 + * changed; no longer offically supporting node 0.6.x + * changed; query.within getter is now a method -> query.within() + * changed; query.intersects getter is now a method -> query.intersects() + * added; custom error msgs for built-in validators #747 + * added; discriminator support #1647 #1003 [j](https://github.com/j) + * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) + * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) + * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) + * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) + * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) + * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) + * added; promise support to model.mapReduce() + * added; promise support to model.ensureIndexes() + * added; promise support to model.populate() + * added; benchmarks [ebensing](https://github.com/ebensing) + * added; publicly exposed connection states #1585 + * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) + * added; query method chain validation + * added; model.update `overwrite` option + * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) + * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) + * added; MongooseBuffer#subtype() + * added; model.create() now returns a promise #1340 + * added; support for `awaitdata` query option + * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) + * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) + * fixed; document.toObject when using `minimize` and `getters` options #1607 [JedWatson](https://github.com/JedWatson) + * fixed; Mixed types can now be required #1722 [Reggino](https://github.com/Reggino) + * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) + * fixed; repopulating modified populated paths #1697 + * fixed; doc.equals() when _id option is set to false #1687 + * fixed; strict mode warnings #1686 + * fixed; $near GeoJSON casting #1683 + * fixed; nearSphere GeoJSON query builder + * fixed; population field selection w/ strings #1669 + * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) + * fixed; handle another versioning edge case #1520 + * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) + * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) + * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) + * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) + * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) + * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) + * fixed; model.remove() removes only what is necessary #1649 + * fixed; update() now only runs with cb or explicit true #1644 + * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) + * fixed; model.update "overwrite" option works as documented + * fixed; query#remove() works as documented + * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) + * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) + * fixed; benchmarks to actually output valid json + * deprecated; promise#addBack (use promise#onResolve) + * deprecated; promise#complete (use promise#fulfill) + * deprecated; promise#addCallback (use promise#onFulFill) + * deprecated; promise#addErrback (use promise#onReject) + * deprecated; query.nearSphere() (use query.near) + * deprecated; query.center() (use query.circle) + * deprecated; query.centerSphere() (use query.circle) + * deprecated; query#slaveOk (use query#read) + * docs; custom validator messages + * docs; 10gen -> MongoDB + * docs; add Date method caveats #1598 + * docs; more validation details + * docs; state which branch is stable/unstable + * docs; mention that middleware does not run on Models + * docs; promise.fulfill() + * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) + * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) + * website; add "show code" for properties + * website; move "show code" links down + * website; update guide + * website; add unstable docs + * website; many improvements + * website; fix copyright #1439 + * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) + * tests; refactor 1703 + * tests; add test generator + * tests; validate formatMessage() throws + * tests; add script for continuously running tests + * tests; fixed versioning tests + * tests; race conditions in tests + * tests; added for nested and/or queries + * tests; close some test connections + * tests; validate db contents + * tests; remove .only + * tests; close some test connections + * tests; validate db contents + * tests; remove .only + * tests; replace deprecated method names + * tests; convert id to string + * tests; fix sharding tests for MongoDB 2.4.5 + * tests; now 4-5 seconds faster + * tests; fix race condition + * make; suppress warning msg in test + * benchmarks; updated for pull requests + * examples; improved and expanded [ebensing](https://github.com/ebensing) + +3.7.4 (unstable) / 2013-10-01 +============================= + + * updated; mquery to 0.3.2 + * removed; mongoose.Error.DocumentError (never used) + * added; custom error msgs for built-in validators #747 + * added; discriminator support #1647 #1003 [j](https://github.com/j) + * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) + * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) + * fixed; repopulating modified populated paths #1697 + * fixed; doc.equals() when _id option is set to false #1687 + * fixed; strict mode warnings #1686 + * fixed; $near GeoJSON casting #1683 + * fixed; nearSphere GeoJSON query builder + * fixed; population field selection w/ strings #1669 + * docs; custom validator messages + * docs; 10gen -> MongoDB + * docs; add Date method caveats #1598 + * docs; more validation details + * website; add "show code" for properties + * website; move "show code" links down + * tests; refactor 1703 + * tests; add test generator + * tests; validate formatMessage() throws + +3.7.3 (unstable) / 2013-08-22 +============================= + + * updated; warn when using an unstable version + * updated; mquery to 0.3.1 + * updated; mocha to 1.12.0 + * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) + * changed; no longer offically supporting node 0.6.x + * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) + * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) + * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) + * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) + * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) + * fixed; handle another versioning edge case #1520 + * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) + * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) + * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) + * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) + * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) + * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) + * make; suppress warning msg in test + * docs; state which branch is stable/unstable + * docs; mention that middleware does not run on Models + * tests; add script for continuously running tests + * tests; fixed versioning tests + * benchmarks; updated for pull requests + +3.7.2 (unstable) / 2013-08-15 +================== + + * fixed; model.remove() removes only what is necessary #1649 + * fixed; update() now only runs with cb or explicit true #1644 + * tests; race conditions in tests + * website; update guide + +3.7.1 (unstable) / 2013-08-13 +============================= + + * updated; driver to 1.3.18 (fixes memory leak) + * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) + * added; promise support to model.mapReduce() + * added; promise support to model.ensureIndexes() + * added; promise support to model.populate() + * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) + * fixed; model.update "overwrite" option works as documented + * fixed; query#remove() works as documented + * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) + * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) + * fixed; benchmarks to actually output valid json + * tests; added for nested and/or queries + * tests; close some test connections + * tests; validate db contents + * tests; remove .only + * tests; close some test connections + * tests; validate db contents + * tests; remove .only + * tests; replace deprecated method names + * tests; convert id to string + * docs; promise.fulfill() + +3.7.0 (unstable) / 2013-08-05 +=================== + + * changed; query.within getter is now a method -> query.within() + * changed; query.intersects getter is now a method -> query.intersects() + * deprecated; promise#addBack (use promise#onResolve) + * deprecated; promise#complete (use promise#fulfill) + * deprecated; promise#addCallback (use promise#onFulFill) + * deprecated; promise#addErrback (use promise#onReject) + * deprecated; query.nearSphere() (use query.near) + * deprecated; query.center() (use query.circle) + * deprecated; query.centerSphere() (use query.circle) + * deprecated; query#slaveOk (use query#read) + * removed; namedscope (undocumented and broken) #679 #642 #455 #379 + * added; benchmarks [ebensing](https://github.com/ebensing) + * added; publicly exposed connection states #1585 + * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) + * added; query method chain validation + * added; model.update `overwrite` option + * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) + * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) + * added; MongooseBuffer#subtype() + * added; model.create() now returns a promise #1340 + * added; support for `awaitdata` query option + * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) + * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) + * updated; integrate mquery #1562 [ebensing](https://github.com/ebensing) + * updated; error msg in doc.save() #1595 + * updated; bump driver to 1.3.15 + * updated; mpromise 0.3.0 + * updated; sliced 0.0.5 + * tests; fix sharding tests for MongoDB 2.4.5 + * tests; now 4-5 seconds faster + * tests; fix race condition + * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) + * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) + * website; add unstable docs + * website; many improvements + * website; fix copyright #1439 + * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) + * examples; improved and expanded [ebensing](https://github.com/ebensing) + +3.6.20 (stable) / 2013-09-23 +=================== + + * fixed; repopulating modified populated paths #1697 + * fixed; doc.equals w/ _id false #1687 + * fixed; strict mode warning #1686 + * docs; near/nearSphere + +3.6.19 (stable) / 2013-09-04 +================== + + * fixed; population field selection w/ strings #1669 + * docs; Date method caveats #1598 + +3.6.18 (stable) / 2013-08-22 +=================== + + * updated; warn when using an unstable version of mongoose + * updated; mocha to 1.12.0 + * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) + * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) + * fixed; properly exclude subdocument fields #1280 [ebensing](https://github.com/ebensing) + * fixed; cast error in findAndModify #1643 [aheuermann](https://github.com/aheuermann) + * website; update guide + * website; added documentation for safe:false and versioning interaction + * docs; mention that middleware dont run on Models + * docs; fix indexes link + * make; suppress warning msg in test + * tests; moar + +3.6.17 / 2013-08-13 +=================== + + * updated; driver to 1.3.18 (fixes memory leak) + * fixed; casting ref docs on creation #1606 + * docs; query options + +3.6.16 / 2013-08-08 +=================== + + * added; publicly expose connection states #1585 + * fixed; limit applies to individual items on population #1490 [ebensing](https://github.com/ebensing) + * fixed; positional operator casting in updates #1572 [ebensing](https://github.com/ebensing) + * updated; MongoDB driver to 1.3.17 + * updated; sliced to 0.0.5 + * website; tweak homepage + * tests; fixed + added + * docs; fix some examples + * docs; multi-mongos support details + * docs; auto open browser after starting static server + +3.6.15 / 2013-07-16 +================== + + * added; mongos failover support #1037 + * updated; make schematype return vals return self #1580 + * docs; add note to model.update #571 + * docs; document third param to document.save callback #1536 + * tests; tweek mongos test timeout + +3.6.14 / 2013-07-05 +=================== + + * updated; driver to 1.3.11 + * fixed; issue with findOneAndUpdate not returning null on upserts #1533 [ebensing](https://github.com/ebensing) + * fixed; missing return statement in SchemaArray#$geoIntersects() #1498 [bsrykt](https://github.com/bsrykt) + * fixed; wrong isSelected() behavior #1521 [kyano](https://github.com/kyano) + * docs; note about toObject behavior during save() + * docs; add callbacks details #1547 [nikmartin](https://github.com/nikmartin) + +3.6.13 / 2013-06-27 +=================== + + * fixed; calling model.distinct without conditions #1541 + * fixed; regression in Query#count() #1542 + * now working on 3.6.13 + +3.6.12 / 2013-06-25 +=================== + + * updated; driver to 1.3.10 + * updated; clearer capped collection error message #1509 [bitmage](https://github.com/bitmage) + * fixed; MongooseBuffer subtype loss during casting #1517 [zedgu](https://github.com/zedgu) + * fixed; docArray#id when doc.id is disabled #1492 + * fixed; docArray#id now supports matches on populated arrays #1492 [pgherveou](https://github.com/pgherveou) + * website; fix example + * website; improve _id disabling example + * website; fix typo #1494 [dejj](https://github.com/dejj) + * docs; added a 'Requesting new features' section #1504 [shovon](https://github.com/shovon) + * docs; improve subtypes description + * docs; clarify _id disabling + * docs: display by alphabetical order the methods list #1508 [nicolasleger](https://github.com/nicolasleger) + * tests; refactor isSelected checks + * tests; remove pointless test + * tests; fixed timeouts + +3.6.11 / 2013-05-15 +=================== + + * updated; driver to 1.3.5 + * fixed; compat w/ Object.create(null) #1484 #1485 + * fixed; cloning objects w/ missing constructors + * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) + * docs; add doc.increment() example + * docs; add $size example + * docs; add "distinct" example + +3.6.10 / 2013-05-09 +================== + + * update driver to 1.3.3 + * fixed; increment() works without other changes #1475 + * website; fix links to posterous + * docs; fix link #1472 + +3.6.9 / 2013-05-02 +================== + + * fixed; depopulation of mixed documents #1471 + * fixed; use of $options in array #1462 + * tests; fix race condition + * docs; fix default example + +3.6.8 / 2013-04-25 +================== + + * updated; driver to 1.3.0 + * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) + * tests; 4-5 seconds faster + +3.6.7 / 2013-04-19 +================== + + * fixed; population regression in 3.6.6 #1444 + +3.6.6 / 2013-04-18 +================== + + * fixed; saving populated new documents #1442 + * fixed; population regession in 3.6.5 #1441 + * website; fix copyright #1439 + +3.6.5 / 2013-04-15 +================== + + * fixed; strict:throw edge case using .set(path, val) + * fixed; schema.pathType() on some numbericAlpha paths + * fixed; numbericAlpha path versioning + * fixed; setting nested mixed paths #1418 + * fixed; setting nested objects with null prop #1326 + * fixed; regression in v3.6 population performance #1426 [vedmalex](https://github.com/vedmalex) + * fixed; read pref typos #1422 [kyano](https://github.com/kyano) + * docs; fix method example + * website; update faq + * website; add more deep links + * website; update poolSize docs + * website; add 3.6 release notes + * website; note about keepAlive + +3.6.4 / 2013-04-03 +================== + + * fixed; +field conflict with $slice #1370 + * fixed; nested deselection conflict #1333 + * fixed; RangeError in ValidationError.toString() #1296 + * fixed; do not save user defined transforms #1415 + * tests; fix race condition + +3.6.3 / 2013-04-02 +================== + + * fixed; setting subdocuments deeply nested fields #1394 + * fixed; regression: populated streams #1411 + * docs; mention hooks/validation with findAndModify + * docs; mention auth + * docs; add more links + * examples; add document methods example + * website; display "see" links for properties + * website; clean up homepage + +3.6.2 / 2013-03-29 +================== + + * fixed; corrupted sub-doc array #1408 + * fixed; document#update returns a Query #1397 + * docs; readpref strategy + +3.6.1 / 2013-03-27 +================== + + * added; populate support to findAndModify varients #1395 + * added; text index type to schematypes + * expose allowed index types as Schema.indexTypes + * fixed; use of `setMaxListeners` as path + * fixed; regression in node 0.6 on docs with > 10 arrays + * fixed; do not alter schema arguments #1364 + * fixed; subdoc#ownerDocument() #1385 + * website; change search id + * website; add search from google [jackdbernier](https://github.com/jackdbernier) + * website; fix link + * website; add 3.5.x docs release + * website; fix link + * docs; fix geometry + * docs; hide internal constructor + * docs; aggregation does not cast arguments #1399 + * docs; querystream options + * examples; added for population + +3.6.0 / 2013-03-18 +================== + + * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) + * changed; Buffer arrays can now contain nulls + * added; QueryStream transform option + * added; support for authSource driver option + * added; {mongoose,db}.modelNames() + * added; $push w/ $slice,$sort support (MongoDB 2.4) + * added; hashed index type (MongoDB 2.4) + * added; support for mongodb 2.4 geojson (MongoDB 2.4) + * added; value at time of validation error + * added; support for object literal schemas + * added; bufferCommands schema option + * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) + * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) + * added; allow adding uncasted docs to populated arrays and properties #570 + * added; doc#populated(path) stores original populated _ids + * added; lean population #1260 + * added; query.populate() now accepts an options object + * added; document#populate(opts, callback) + * added; Model.populate(docs, opts, callback) + * added; support for rich nested path population + * added; doc.array.remove(value) subdoc with _id value support #1278 + * added; optionally allow non-strict sets and updates + * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) + * added; promise#then + * added; promise#end + * fixed; use of `model` as doc property + * fixed; lean population #1382 + * fixed; empty object mixed defaults #1380 + * fixed; populate w/ deselected _id using string syntax + * fixed; attempted save of divergent populated arrays #1334 related + * fixed; better error msg when attempting toObject as property name + * fixed; non population buffer casting from doc + * fixed; setting populated paths #570 + * fixed; casting when added docs to populated arrays #570 + * fixed; prohibit updating arrays selected with $elemMatch #1334 + * fixed; pull / set subdoc combination #1303 + * fixed; multiple bg index creation #1365 + * fixed; manual reconnection to single mongod + * fixed; Constructor / version exposure #1124 + * fixed; CastError race condition + * fixed; no longer swallowing misuse of subdoc#invalidate() + * fixed; utils.clone retains RegExp opts + * fixed; population of non-schema property + * fixed; allow updating versionKey #1265 + * fixed; add EventEmitter props to reserved paths #1338 + * fixed; can now deselect populated doc _ids #1331 + * fixed; properly pass subtype to Binary in MongooseBuffer + * fixed; casting _id from document with non-ObjectId _id + * fixed; specifying schema type edge case { path: [{type: "String" }] } + * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) + * updated; driver to 1.2.14 + * updated; muri to 0.3.1 + * updated; mpromise to 0.2.1 + * updated; mocha 1.8.1 + * updated; mpath to 0.1.1 + * deprecated; pluralization will die in 4.x + * refactor; rename private methods to something unusable as doc properties + * refactor MongooseArray#remove + * refactor; move expires index to SchemaDate #1328 + * refactor; internal document properties #1171 #1184 + * tests; added + * docs; indexes + * docs; validation + * docs; populate + * docs; populate + * docs; add note about stream compatibility with node 0.8 + * docs; fix for private names + * docs; Buffer -> mongodb.Binary #1363 + * docs; auth options + * docs; improved + * website; update FAQ + * website; add more api links + * website; add 3.5.x docs to prior releases + * website; Change mongoose-types to an active repo [jackdbernier](https://github.com/jackdbernier) + * website; compat with node 0.10 + * website; add news section + * website; use T for generic type + * benchmark; make adjustable + +3.6.0rc1 / 2013-03-12 +====================== + + * refactor; rename private methods to something unusable as doc properties + * added; {mongoose,db}.modelNames() + * added; $push w/ $slice,$sort support (MongoDB 2.4) + * added; hashed index type (MongoDB 2.4) + * added; support for mongodb 2.4 geojson (MongoDB 2.4) + * added; value at time of validation error + * added; support for object literal schemas + * added; bufferCommands schema option + * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) + * fixed; lean population #1382 + * fixed; empty object mixed defaults #1380 + * fixed; populate w/ deselected _id using string syntax + * fixed; attempted save of divergent populated arrays #1334 related + * fixed; better error msg when attempting toObject as property name + * fixed; non population buffer casting from doc + * fixed; setting populated paths #570 + * fixed; casting when added docs to populated arrays #570 + * fixed; prohibit updating arrays selected with $elemMatch #1334 + * fixed; pull / set subdoc combination #1303 + * fixed; multiple bg index creation #1365 + * fixed; manual reconnection to single mongod + * fixed; Constructor / version exposure #1124 + * fixed; CastError race condition + * fixed; no longer swallowing misuse of subdoc#invalidate() + * fixed; utils.clone retains RegExp opts + * fixed; population of non-schema property + * fixed; allow updating versionKey #1265 + * fixed; add EventEmitter props to reserved paths #1338 + * fixed; can now deselect populated doc _ids #1331 + * updated; muri to 0.3.1 + * updated; driver to 1.2.12 + * updated; mpromise to 0.2.1 + * deprecated; pluralization will die in 4.x + * docs; Buffer -> mongodb.Binary #1363 + * docs; auth options + * docs; improved + * website; add news section + * benchmark; make adjustable + +3.6.0rc0 / 2013-02-03 +====================== + + * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) + * changed; Buffer arrays can now contain nulls + * fixed; properly pass subtype to Binary in MongooseBuffer + * fixed; casting _id from document with non-ObjectId _id + * fixed; specifying schema type edge case { path: [{type: "String" }] } + * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) + * refactor; move expires index to SchemaDate #1328 + * refactor; internal document properties #1171 #1184 + * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) + * added; allow adding uncasted docs to populated arrays and properties #570 + * added; doc#populated(path) stores original populated _ids + * added; lean population #1260 + * added; query.populate() now accepts an options object + * added; document#populate(opts, callback) + * added; Model.populate(docs, opts, callback) + * added; support for rich nested path population + * added; doc.array.remove(value) subdoc with _id value support #1278 + * added; optionally allow non-strict sets and updates + * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) + * added; promise#then + * added; promise#end + * updated; mocha 1.8.1 + * updated; muri to 0.3.0 + * updated; mpath to 0.1.1 + * updated; docs + +3.5.16 / 2013-08-13 +=================== + + * updated; driver to 1.3.18 + +3.5.15 / 2013-07-26 +================== + + * updated; sliced to 0.0.5 + * updated; driver to 1.3.12 + * fixed; regression in Query#count() due to driver change + * tests; fixed timeouts + * tests; handle differing test uris + +3.5.14 / 2013-05-15 +=================== + + * updated; driver to 1.3.5 + * fixed; compat w/ Object.create(null) #1484 #1485 + * fixed; cloning objects missing constructors + * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) + +3.5.13 / 2013-05-09 +================== + + * update driver to 1.3.3 + * fixed; use of $options in array #1462 + +3.5.12 / 2013-04-25 +=================== + + * updated; driver to 1.3.0 + * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) + * fixed; read pref typos #1422 [kyano](https://github.com/kyano) + +3.5.11 / 2013-04-03 +================== + + * fixed; +field conflict with $slice #1370 + * fixed; RangeError in ValidationError.toString() #1296 + * fixed; nested deselection conflict #1333 + * remove time from Makefile + +3.5.10 / 2013-04-02 +================== + + * fixed; setting subdocuments deeply nested fields #1394 + * fixed; do not alter schema arguments #1364 + +3.5.9 / 2013-03-15 +================== + + * updated; driver to 1.2.14 + * added; support for authSource driver option (mongodb 2.4) + * added; QueryStream transform option (node 0.10 helper) + * fixed; backport for saving required populated buffers + * fixed; pull / set subdoc combination #1303 + * fixed; multiple bg index creation #1365 + * test; added for saveable required populated buffers + * test; added for #1365 + * test; add authSource test + +3.5.8 / 2013-03-12 +================== + + * added; auth option in connection [geoah](https://github.com/geoah) + * fixed; CastError race condition + * docs; add note about stream compatibility with node 0.8 + +3.5.7 / 2013-02-22 +================== + + * updated; driver to 1.2.13 + * updated; muri to 0.3.1 #1347 + * fixed; utils.clone retains RegExp opts #1355 + * fixed; deepEquals RegExp support + * tests; fix a connection test + * website; clean up docs [afshinm](https://github.com/afshinm) + * website; update homepage + * website; migragtion: emphasize impact of strict docs #1264 + +3.5.6 / 2013-02-14 +================== + + * updated; driver to 1.2.12 + * fixed; properly pass Binary subtype + * fixed; add EventEmitter props to reserved paths #1338 + * fixed; use correct node engine version + * fixed; display empty docs as {} in log output #953 follow up + * improved; "bad $within $box argument" error message + * populate; add unscientific benchmark + * website; add stack overflow to help section + * website; use better code font #1336 [risseraka](https://github.com/risseraka) + * website; clarify where help is available + * website; fix source code links #1272 [floatingLomas](https://github.com/floatingLomas) + * docs; be specific about _id schema option #1103 + * docs; add ensureIndex error handling example + * docs; README + * docs; CONTRIBUTING.md + +3.5.5 / 2013-01-29 +================== + + * updated; driver to 1.2.11 + * removed; old node < 0.6x shims + * fixed; documents with Buffer _ids equality + * fixed; MongooseBuffer properly casts numbers + * fixed; reopening closed connection on alt host/port #1287 + * docs; fixed typo in Readme #1298 [rened](https://github.com/rened) + * docs; fixed typo in migration docs [Prinzhorn](https://github.com/Prinzhorn) + * docs; fixed incorrect annotation in SchemaNumber#min [bilalq](https://github.com/bilalq) + * docs; updated + +3.5.4 / 2013-01-07 +================== + + * changed; "_pres" & "_posts" are now reserved pathnames #1261 + * updated; driver to 1.2.8 + * fixed; exception when reopening a replica set. #1263 [ethankan](https://github.com/ethankan) + * website; updated + +3.5.3 / 2012-12-26 +================== + + * added; support for geo object notation #1257 + * fixed; $within query casting with arrays + * fixed; unix domain socket support #1254 + * updated; driver to 1.2.7 + * updated; muri to 0.0.5 + +3.5.2 / 2012-12-17 +================== + + * fixed; using auth with replica sets #1253 + +3.5.1 / 2012-12-12 +================== + + * fixed; regression when using subdoc with `path` as pathname #1245 [daeq](https://github.com/daeq) + * fixed; safer db option checks + * updated; driver to 1.2.5 + * website; add more examples + * website; clean up old docs + * website; fix prev release urls + * docs; clarify streaming with HTTP responses + +3.5.0 / 2012-12-10 +================== + + * added; paths to CastErrors #1239 + * added; support for mongodb connection string spec #1187 + * added; post validate event + * added; Schema#get (to retrieve schema options) + * added; VersionError #1071 + * added; npmignore [hidekiy](https://github.com/hidekiy) + * update; driver to 1.2.3 + * fixed; stackoverflow in setter #1234 + * fixed; utils.isObject() + * fixed; do not clobber user specified driver writeConcern #1227 + * fixed; always pass current document to post hooks + * fixed; throw error when user attempts to overwrite a model + * fixed; connection.model only caches on connection #1209 + * fixed; respect conn.model() creation when matching global model exists #1209 + * fixed; passing model name + collection name now always honors collection name + * fixed; setting virtual field to an empty object #1154 + * fixed; subclassed MongooseErrors exposure, now available in mongoose.Error.xxxx + * fixed; model.remove() ignoring callback when executed twice [daeq](https://github.com/daeq) #1210 + * docs; add collection option to schema api docs #1222 + * docs; NOTE about db safe options + * docs; add post hooks docs + * docs; connection string options + * docs; middleware is not executed with Model.remove #1241 + * docs; {g,s}etter introspection #777 + * docs; update validation docs + * docs; add link to plugins page + * docs; clarify error returned by unique indexes #1225 + * docs; more detail about disabling autoIndex behavior + * docs; add homepage section to package (npm docs mongoose) + * docs; more detail around collection name pluralization #1193 + * website; add .important css + * website; update models page + * website; update getting started + * website; update quick start + +3.4.0 / 2012-11-10 +================== + + * added; support for generic toJSON/toObject transforms #1160 #1020 #1197 + * added; doc.set() merge support #1148 [NuORDER](https://github.com/NuORDER) + * added; query#add support #1188 [aleclofabbro](https://github.com/aleclofabbro) + * changed; adding invalid nested paths to non-objects throws 4216f14 + * changed; fixed; stop invalid function cloning (internal fix) + * fixed; add query $and casting support #1180 [anotheri](https://github.com/anotheri) + * fixed; overwriting of query arguments #1176 + * docs; fix expires examples + * docs; transforms + * docs; schema `collection` option docs [hermanjunge](https://github.com/hermanjunge) + * website; updated + * tests; added + +3.3.1 / 2012-10-11 +================== + + * fixed; allow goose.connect(uris, dbname, opts) #1144 + * docs; persist API private checked state across page loads + +3.3.0 / 2012-10-10 +================== + + * fixed; passing options as 2nd arg to connect() #1144 + * fixed; race condition after no-op save #1139 + * fixed; schema field selection application in findAndModify #1150 + * fixed; directly setting arrays #1126 + * updated; driver to 1.1.11 + * updated; collection pluralization rules [mrickard](https://github.com/mrickard) + * tests; added + * docs; updated + +3.2.2 / 2012-10-08 +================== + + * updated; driver to 1.1.10 #1143 + * updated; use sliced 0.0.3 + * fixed; do not recast embedded docs unnecessarily + * fixed; expires schema option helper #1132 + * fixed; built in string setters #1131 + * fixed; debug output for Dates/ObjectId properties #1129 + * docs; fixed Javascript syntax error in example [olalonde](https://github.com/olalonde) + * docs; fix toJSON example #1137 + * docs; add ensureIndex production notes + * docs; fix spelling + * docs; add blogposts about v3 + * website; updated + * removed; undocumented inGroupsOf util + * tests; added + +3.2.1 / 2012-09-28 +================== + + * fixed; remove query batchSize option default of 1000 https://github.com/learnboost/mongoose/commit/3edaa8651 + * docs; updated + * website; updated + +3.2.0 / 2012-09-27 +================== + + * added; direct array index assignment with casting support `doc.array.set(index, value)` + * fixed; QueryStream#resume within same tick as pause() #1116 + * fixed; default value validatation #1109 + * fixed; array splice() not casting #1123 + * fixed; default array construction edge case #1108 + * fixed; query casting for inequalities in arrays #1101 [dpatti](https://github.com/dpatti) + * tests; added + * website; more documentation + * website; fixed layout issue #1111 [SlashmanX](https://github.com/SlashmanX) + * website; refactored [guille](https://github.com/guille) + +3.1.2 / 2012-09-10 +================== + + * added; ReadPreferrence schema option #1097 + * updated; driver to 1.1.7 + * updated; default query batchSize to 1000 + * fixed; we now cast the mapReduce query option #1095 + * fixed; $elemMatch+$in with field selection #1091 + * fixed; properly cast $elemMatch+$in conditions #1100 + * fixed; default field application of subdocs #1027 + * fixed; querystream prematurely dying #1092 + * fixed; querystream never resumes when paused at getMore boundries #1092 + * fixed; querystream occasionally emits data events after destroy #1092 + * fixed; remove unnecessary ObjectId creation in querystream + * fixed; allow ne(boolean) again #1093 + * docs; add populate/field selection syntax notes + * docs; add toObject/toJSON options detail + * docs; `read` schema option + +3.1.1 / 2012-08-31 +================== + + * updated; driver to 1.1.6 + +3.1.0 / 2012-08-29 +================== + + * changed; fixed; directly setting nested objects now overwrites entire object (previously incorrectly merged them) + * added; read pref support (mongodb 2.2) 205a709c + * added; aggregate support (mongodb 2.2) f3a5bd3d + * added; virtual {g,s}etter introspection (#1070) + * updated; docs [brettz9](https://github.com/brettz9) + * updated; driver to 1.1.5 + * fixed; retain virtual setter return values (#1069) + +3.0.3 / 2012-08-23 +================== + + * fixed; use of nested paths beginning w/ numbers #1062 + * fixed; query population edge case #1053 #1055 [jfremy](https://github.com/jfremy) + * fixed; simultaneous top and sub level array modifications #1073 + * added; id and _id schema option aliases + tests + * improve debug formatting to allow copy/paste logged queries into mongo shell [eknkc](https://github.com/eknkc) + * docs + +3.0.2 / 2012-08-17 +================== + + * added; missing support for v3 sort/select syntax to findAndModify helpers (#1058) + * fixed; replset fullsetup event emission + * fixed; reconnected event for replsets + * fixed; server reconnection setting discovery + * fixed; compat with non-schema path props using positional notation (#1048) + * fixed; setter/casting order (#665) + * docs; updated + +3.0.1 / 2012-08-11 +================== + + * fixed; throw Error on bad validators (1044) + * fixed; typo in EmbeddedDocument#parentArray [lackac] + * fixed; repair mongoose.SchemaTypes alias + * updated; docs + +3.0.0 / 2012-08-07 +================== + + * removed; old subdocument#commit method + * fixed; setting arrays of matching docs [6924cbc2] + * fixed; doc!remove event now emits in save order as save for consistency + * fixed; pre-save hooks no longer fire on subdocuments when validation fails + * added; subdoc#parent() and subdoc#parentArray() to access subdocument parent objects + * added; query#lean() helper + +3.0.0rc0 / 2012-08-01 +===================== + + * fixed; allow subdoc literal declarations containing "type" pathname (#993) + * fixed; unsetting a default array (#758) + * fixed; boolean $in queries (#998) + * fixed; allow use of `options` as a pathname (#529) + * fixed; `model` is again a permitted schema path name + * fixed; field selection option on subdocs (#1022) + * fixed; handle another edge case with subdoc saving (#975) + * added; emit save err on model if listening + * added; MongoDB TTL collection support (#1006) + * added; $center options support + * added; $nearSphere and $polygon support + * updated; driver version to 1.1.2 + +3.0.0alpha2 / 2012-07-18 +========================= + + * changed; index errors are now emitted on their model and passed to an optional callback (#984) + * fixed; specifying index along with sparse/unique option no longer overwrites (#1004) + * fixed; never swallow connection errors (#618) + * fixed; creating object from model with emded object no longer overwrites defaults [achurkin] (#859) + * fixed; stop needless validation of unchanged/unselected fields (#891) + * fixed; document#equals behavior of objectids (#974) + * fixed; honor the minimize schema option (#978) + * fixed; provide helpful error msgs when reserved schema path is used (#928) + * fixed; callback to conn#disconnect is optional (#875) + * fixed; handle missing protocols in connection urls (#987) + * fixed; validate args to query#where (#969) + * fixed; saving modified/removed subdocs (#975) + * fixed; update with $pull from Mixed array (#735) + * fixed; error with null shard key value + * fixed; allow unsetting enums (#967) + * added; support for manual index creation (#984) + * added; support for disabled auto-indexing (#984) + * added; support for preserving MongooseArray#sort changes (#752) + * added; emit state change events on connection + * added; support for specifying BSON subtype in MongooseBuffer#toObject [jcrugzz] + * added; support for disabled versioning (#977) + * added; implicit "new" support for models and Schemas + +3.0.0alpha1 / 2012-06-15 +========================= + + * removed; doc#commit (use doc#markModified) + * removed; doc.modified getter (#950) + * removed; mongoose{connectSet,createSetConnection}. use connect,createConnection instead + * removed; query alias methods 1149804c + * removed; MongooseNumber + * changed; now creating indexes in background by default + * changed; strict mode now enabled by default (#952) + * changed; doc#modifiedPaths is now a method (#950) + * changed; getters no longer cast (#820); casting happens during set + * fixed; no need to pass updateArg to findOneAndUpdate (#931) + * fixed: utils.merge bug when merging nested non-objects. [treygriffith] + * fixed; strict:throw should produce errors in findAndModify (#963) + * fixed; findAndUpdate no longer overwrites document (#962) + * fixed; setting default DocumentArrays (#953) + * fixed; selection of _id with schema deselection (#954) + * fixed; ensure promise#error emits instanceof Error + * fixed; CursorStream: No stack overflow on any size result (#929) + * fixed; doc#remove now passes safe options + * fixed; invalid use of $set during $pop + * fixed; array#{$pop,$shift} mirror MongoDB behavior + * fixed; no longer test non-required vals in string match (#934) + * fixed; edge case with doc#inspect + * fixed; setter order (#665) + * fixed; setting invalid paths in strict mode (#916) + * fixed; handle docs without id in DocumentArray#id method (#897) + * fixed; do not save virtuals during model.update (#894) + * fixed; sub doc toObject virtuals application (#889) + * fixed; MongooseArray#pull of ObjectId (#881) + * fixed; handle passing db name with any repl set string + * fixed; default application of selected fields (#870) + * fixed; subdoc paths reported in validation errors (#725) + * fixed; incorrect reported num of affected docs in update ops (#862) + * fixed; connection assignment in Model#model (#853) + * fixed; stringifying arrays of docs (#852) + * fixed; modifying subdoc and parent array works (#842) + * fixed; passing undefined to next hook (#785) + * fixed; Query#{update,remove}() works without callbacks (#788) + * fixed; set/updating nested objects by parent pathname (#843) + * fixed; allow null in number arrays (#840) + * fixed; isNew on sub doc after insertion error (#837) + * fixed; if an insert fails, set isNew back to false [boutell] + * fixed; isSelected when only _id is selected (#730) + * fixed; setting an unset default value (#742) + * fixed; query#sort error messaging (#671) + * fixed; support for passing $options with $regex + * added; array of object literal notation in schema creates DocumentArrays + * added; gt,gte,lt,lte query support for arrays (#902) + * added; capped collection support (#938) + * added; document versioning support + * added; inclusion of deselected schema path (#786) + * added; non-atomic array#pop + * added; EmbeddedDocument constructor is now exposed in DocArray#create 7cf8beec + * added; mapReduce support (#678) + * added; support for a configurable minimize option #to{Object,JSON}(option) (#848) + * added; support for strict: `throws` [regality] + * added; support for named schema types (#795) + * added; to{Object,JSON} schema options (#805) + * added; findByIdAnd{Update,Remove}() + * added; findOneAnd{Update,Remove}() + * added; query.setOptions() + * added; instance.update() (#794) + * added; support specifying model in populate() [DanielBaulig] + * added; `lean` query option [gitfy] + * added; multi-atomic support to MongooseArray#nonAtomicPush + * added; support for $set + other $atomic ops on single array + * added; tests + * updated; driver to 1.0.2 + * updated; query.sort() syntax to mirror query.select() + * updated; clearer cast error msg for array numbers + * updated; docs + * updated; doc.clone 3x faster (#950) + * updated; only create _id if necessary (#950) + +2.7.3 / 2012-08-01 +================== + + * fixed; boolean $in queries (#998) + * fixed field selection option on subdocs (#1022) + +2.7.2 / 2012-07-18 +================== + + * fixed; callback to conn#disconnect is optional (#875) + * fixed; handle missing protocols in connection urls (#987) + * fixed; saving modified/removed subdocs (#975) + * updated; tests + +2.7.1 / 2012-06-26 +=================== + + * fixed; sharding: when a document holds a null as a value of the shard key + * fixed; update() using $pull on an array of Mixed (gh-735) + * deprecated; MongooseNumber#{inc, increment, decrement} methods + * tests; now using mocha + +2.7.0 / 2012-06-14 +=================== + + * added; deprecation warnings to methods being removed in 3.x + +2.6.8 / 2012-06-14 +=================== + + * fixed; edge case when using 'options' as a path name (#961) + +2.6.7 / 2012-06-08 +=================== + + * fixed; ensure promise#error always emits instanceof Error + * fixed; selection of _id w/ another excluded path (#954) + * fixed; setting default DocumentArrays (#953) + +2.6.6 / 2012-06-06 +=================== + + * fixed; stack overflow in query stream with large result sets (#929) + * added; $gt, $gte, $lt, $lte support to arrays (#902) + * fixed; pass option `safe` along to doc#remove() calls + +2.6.5 / 2012-05-24 +=================== + + * fixed; do not save virtuals in Model.update (#894) + * added; missing $ prefixed query aliases (going away in 3.x) (#884) [timoxley] + * fixed; setting invalid paths in strict mode (#916) + * fixed; resetting isNew after insert failure (#837) [boutell] + +2.6.4 / 2012-05-15 +=================== + + * updated; backport string regex $options to 2.x + * updated; use driver 1.0.2 (performance improvements) (#914) + * fixed; calling MongooseDocumentArray#id when the doc has no _id (#897) + +2.6.3 / 2012-05-03 +=================== + + * fixed; repl-set connectivity issues during failover on MongoDB 2.0.1 + * updated; driver to 1.0.0 + * fixed; virtuals application of subdocs when using toObject({ virtuals: true }) (#889) + * fixed; MongooseArray#pull of ObjectId correctly updates the array itself (#881) + +2.6.2 / 2012-04-30 +=================== + + * fixed; default field application of selected fields (#870) + +2.6.1 / 2012-04-30 +=================== + + * fixed; connection assignment in mongoose#model (#853, #877) + * fixed; incorrect reported num of affected docs in update ops (#862) + +2.6.0 / 2012-04-19 +=================== + + * updated; hooks.js to 0.2.1 + * fixed; issue with passing undefined to a hook callback. thanks to [chrisleishman] for reporting. + * fixed; updating/setting nested objects in strict schemas (#843) as reported by [kof] + * fixed; Query#{update,remove}() work without callbacks again (#788) + * fixed; modifying subdoc along with parent array $atomic op (#842) + +2.5.14 / 2012-04-13 +=================== + + * fixed; setting an unset default value (#742) + * fixed; doc.isSelected(otherpath) when only _id is selected (#730) + * updated; docs + +2.5.13 / 2012-03-22 +=================== + + * fixed; failing validation of unselected required paths (#730,#713) + * fixed; emitting connection error when only one listener (#759) + * fixed; MongooseArray#splice was not returning values (#784) [chrisleishman] + +2.5.12 / 2012-03-21 +=================== + + * fixed; honor the `safe` option in all ensureIndex calls + * updated; node-mongodb-native driver to 0.9.9-7 + +2.5.11 / 2012-03-15 +=================== + + * added; introspection for getters/setters (#745) + * updated; node-mongodb-driver to 0.9.9-5 + * added; tailable method to Query (#769) [holic] + * fixed; Number min/max validation of null (#764) [btamas] + * added; more flexible user/password connection options (#738) [KarneAsada] + +2.5.10 / 2012-03-06 +=================== + + * updated; node-mongodb-native driver to 0.9.9-4 + * added; Query#comment() + * fixed; allow unsetting arrays + * fixed; hooking the set method of subdocuments (#746) + * fixed; edge case in hooks + * fixed; allow $id and $ref in queries (fixes compatibility with mongoose-dbref) (#749) [richtera] + * added; default path selection to SchemaTypes + +2.5.9 / 2012-02-22 +=================== + + * fixed; properly cast nested atomic update operators for sub-documents + +2.5.8 / 2012-02-21 +=================== + + * added; post 'remove' middleware includes model that was removed (#729) [timoxley] + +2.5.7 / 2012-02-09 +=================== + + * fixed; RegExp validators on node >= v0.6.x + +2.5.6 / 2012-02-09 +=================== + + * fixed; emit errors returned from db.collection() on the connection (were being swallowed) + * added; can add multiple validators in your schema at once (#718) [diogogmt] + * fixed; strict embedded documents (#717) + * updated; docs [niemyjski] + * added; pass number of affected docs back in model.update/save + +2.5.5 / 2012-02-03 +=================== + + * fixed; RangeError: maximum call stack exceed error when removing docs with Number _id (#714) + +2.5.4 / 2012-02-03 +=================== + + * fixed; RangeError: maximum call stack exceed error (#714) + +2.5.3 / 2012-02-02 +=================== + + * added; doc#isSelected(path) + * added; query#equals() + * added; beta sharding support + * added; more descript error msgs (#700) [obeleh] + * added; document.modifiedPaths (#709) [ljharb] + * fixed; only functions can be added as getters/setters (#707,704) [ljharb] + +2.5.2 / 2012-01-30 +=================== + + * fixed; rollback -native driver to 0.9.7-3-5 (was causing timeouts and other replica set weirdness) + * deprecated; MongooseNumber (will be moved to a separate repo for 3.x) + * added; init event is emitted on schemas + +2.5.1 / 2012-01-27 +=================== + + * fixed; honor strict schemas in Model.update (#699) + +2.5.0 / 2012-01-26 +=================== + + * added; doc.toJSON calls toJSON on embedded docs when exists [jerem] + * added; populate support for refs of type Buffer (#686) [jerem] + * added; $all support for ObjectIds and Dates (#690) + * fixed; virtual setter calling on instantiation when strict: true (#682) [hunterloftis] + * fixed; doc construction triggering getters (#685) + * fixed; MongooseBuffer check in deepEquals (#688) + * fixed; range error when using Number _ids with `instance.save()` (#691) + * fixed; isNew on embedded docs edge case (#680) + * updated; driver to 0.9.8-3 + * updated; expose `model()` method within static methods + +2.4.10 / 2012-01-10 +=================== + + * added; optional getter application in .toObject()/.toJSON() (#412) + * fixed; nested $operators in $all queries (#670) + * added; $nor support (#674) + * fixed; bug when adding nested schema (#662) [paulwe] + +2.4.9 / 2012-01-04 +=================== + + * updated; driver to 0.9.7-3-5 to fix Linux performance degradation on some boxes + +2.4.8 / 2011-12-22 +=================== + + * updated; bump -native to 0.9.7.2-5 + * fixed; compatibility with date.js (#646) [chrisleishman] + * changed; undocumented schema "lax" option to "strict" + * fixed; default value population for strict schemas + * updated; the nextTick helper for small performance gain. 1bee2a2 + +2.4.7 / 2011-12-16 +=================== + + * fixed; bug in 2.4.6 with path setting + * updated; bump -native to 0.9.7.2-1 + * added; strict schema option [nw] + +2.4.6 / 2011-12-16 +=================== + + * fixed; conflicting mods on update bug [sirlantis] + * improved; doc.id getter performance + +2.4.5 / 2011-12-14 +=================== + + * fixed; bad MongooseArray behavior in 2.4.2 - 2.4.4 + +2.4.4 / 2011-12-14 +=================== + + * fixed; MongooseArray#doAtomics throwing after sliced + +2.4.3 / 2011-12-14 +=================== + + * updated; system.profile schema for MongoDB 2x + +2.4.2 / 2011-12-12 +=================== + + * fixed; partially populating multiple children of subdocs (#639) [kenpratt] + * fixed; allow Update of numbers to null (#640) [jerem] + +2.4.1 / 2011-12-02 +=================== + + * added; options support for populate() queries + * updated; -native driver to 0.9.7-1.4 + +2.4.0 / 2011-11-29 +=================== + + * added; QueryStreams (#614) + * added; debug print mode for development + * added; $within support to Array queries (#586) [ggoodale] + * added; $centerSphere query support + * fixed; $within support + * added; $unset is now used when setting a path to undefined (#519) + * added; query#batchSize support + * updated; docs + * updated; -native driver to 0.9.7-1.3 (provides Windows support) + +2.3.13 / 2011-11-15 +=================== + + * fixed; required validation for Refs (#612) [ded] + * added; $nearSphere support for Arrays (#610) + +2.3.12 / 2011-11-09 +=================== + + * fixed; regression, objects passed to Model.update should not be changed (#605) + * fixed; regression, empty Model.update should not be executed + +2.3.11 / 2011-11-08 +=================== + + * fixed; using $elemMatch on arrays of Mixed types (#591) + * fixed; allow using $regex when querying Arrays (#599) + * fixed; calling Model.update with no atomic keys (#602) + +2.3.10 / 2011-11-05 +=================== + + * fixed; model.update casting for nested paths works (#542) + +2.3.9 / 2011-11-04 +================== + + * fixed; deepEquals check for MongooseArray returned false + * fixed; reset modified flags of embedded docs after save [gitfy] + * fixed; setting embedded doc with identical values no longer marks modified [gitfy] + * updated; -native driver to 0.9.6.23 [mlazarov] + * fixed; Model.update casting (#542, #545, #479) + * fixed; populated refs no longer fail required validators (#577) + * fixed; populating refs of objects with custom ids works + * fixed; $pop & $unset work with Model.update (#574) + * added; more helpful debugging message for Schema#add (#578) + * fixed; accessing .id when no _id exists now returns null (#590) + +2.3.8 / 2011-10-26 +================== + + * added; callback to query#findOne is now optional (#581) + +2.3.7 / 2011-10-24 +================== + + * fixed; wrapped save/remove callbacks in nextTick to mitigate -native swallowing thrown errors + +2.3.6 / 2011-10-21 +================== + + * fixed; exclusion of embedded doc _id from query results (#541) + +2.3.5 / 2011-10-19 +================== + + * fixed; calling queries without passing a callback works (#569) + * fixed; populate() works with String and Number _ids too (#568) + +2.3.4 / 2011-10-18 +================== + + * added; Model.create now accepts an array as a first arg + * fixed; calling toObject on a DocumentArray with nulls no longer throws + * fixed; calling inspect on a DocumentArray with nulls no longer throws + * added; MongooseArray#unshift support + * fixed; save hooks now fire on embedded documents [gitfy] (#456) + * updated; -native driver to 0.9.6-22 + * fixed; correctly pass $addToSet op instead of $push + * fixed; $addToSet properly detects dates + * fixed; $addToSet with multiple items works + * updated; better node 0.6 Buffer support + +2.3.3 / 2011-10-12 +================== + + * fixed; population conditions in multi-query settings [vedmalex] (#563) + * fixed; now compatible with Node v0.5.x + +2.3.2 / 2011-10-11 +================== + + * fixed; population of null subdoc properties no longer hangs (#561) + +2.3.1 / 2011-10-10 +================== + + * added; support for Query filters to populate() [eneko] + * fixed; querying with number no longer crashes mongodb (#555) [jlbyrey] + * updated; version of -native driver to 0.9.6-21 + * fixed; prevent query callbacks that throw errors from corrupting -native connection state + +2.3.0 / 2011-10-04 +================== + + * fixed; nulls as default values for Boolean now works as expected + * updated; version of -native driver to 0.9.6-20 + +2.2.4 / 2011-10-03 +================== + + * fixed; populate() works when returned array contains undefined/nulls + +2.2.3 / 2011-09-29 +================== + + * updated; version of -native driver to 0.9.6-19 + +2.2.2 / 2011-09-28 +================== + + * added; $regex support to String [davidandrewcope] + * added; support for other contexts like repl etc (#535) + * fixed; clear modified state properly after saving + * added; $addToSet support to Array + +2.2.1 / 2011-09-22 +================== + + * more descript error when casting undefined to string + * updated; version of -native driver to 0.9.6-18 + +2.2.0 / 2011-09-22 +================== + + * fixed; maxListeners warning on schemas with many arrays (#530) + * changed; return / apply defaults based on fields selected in query (#423) + * fixed; correctly detect Mixed types within schema arrays (#532) + +2.1.4 / 2011-09-20 +================== + + * fixed; new private methods that stomped on users code + * changed; finished removing old "compat" support which did nothing + +2.1.3 / 2011-09-16 +================== + + * updated; version of -native driver to 0.9.6-15 + * added; emit `error` on connection when open fails [edwardhotchkiss] + * added; index support to Buffers (thanks justmoon for helping track this down) + * fixed; passing collection name via schema in conn.model() now works (thanks vedmalex for reporting) + +2.1.2 / 2011-09-07 +================== + + * fixed; Query#find with no args no longer throws + +2.1.1 / 2011-09-07 +================== + + * added; support Model.count(fn) + * fixed; compatibility with node >=0.4.0 < 0.4.3 + * added; pass model.options.safe through with .save() so w:2, wtimeout:5000 options work [andrewjstone] + * added; support for $type queries + * added; support for Query#or + * added; more tests + * optimized populate queries + +2.1.0 / 2011-09-01 +================== + + * changed; document#validate is a public method + * fixed; setting number to same value no longer marks modified (#476) [gitfy] + * fixed; Buffers shouldn't have default vals + * added; allow specifying collection name in schema (#470) [ixti] + * fixed; reset modified paths and atomics after saved (#459) + * fixed; set isNew on embedded docs to false after save + * fixed; use self to ensure proper scope of options in doOpenSet (#483) [andrewjstone] + +2.0.4 / 2011-08-29 +================== + + * Fixed; Only send the depopulated ObjectId instead of the entire doc on save (DBRefs) + * Fixed; Properly cast nested array values in Model.update (the data was stored in Mongo incorrectly but recast on document fetch was "fixing" it) + +2.0.3 / 2011-08-28 +================== + + * Fixed; manipulating a populated array no longer causes infinite loop in BSON serializer during save (#477) + * Fixed; populating an empty array no longer hangs foreeeeeeeever (#481) + +2.0.2 / 2011-08-25 +================== + + * Fixed; Maintain query option key order (fixes 'bad hint' error from compound query hints) + +2.0.1 / 2011-08-25 +================== + + * Fixed; do not over-write the doc when no valide props exist in Model.update (#473) + +2.0.0 / 2011-08-24 +=================== + + * Added; support for Buffers [justmoon] + * Changed; improved error handling [maelstrom] + * Removed: unused utils.erase + * Fixed; support for passing other context object into Schemas (#234) [Sija] + * Fixed; getters are no longer circular refs to themselves (#366) + * Removed; unused compat.js + * Fixed; getter/setter scopes are set properly + * Changed; made several private properties more obvious by prefixing _ + * Added; DBRef support [guille] + * Changed; removed support for multiple collection names per model + * Fixed; no longer applying setters when document returned from db + * Changed; default auto_reconnect to true + * Changed; Query#bind no longer clones the query + * Fixed; Model.update now accepts $pull, $inc and friends (#404) + * Added; virtual type option support [nw] + +1.8.4 / 2011-08-21 +=================== + + * Fixed; validation bug when instantiated with non-schema properties (#464) [jmreidy] + +1.8.3 / 2011-08-19 +=================== + + * Fixed; regression in connection#open [jshaw86] + +1.8.2 / 2011-08-17 +=================== + + * fixed; reset connection.readyState after failure [tomseago] + * fixed; can now query positionally for non-embedded docs (arrays of numbers/strings etc) + * fixed; embedded document query casting + * added; support for passing options to node-mongo-native db, server, and replsetserver [tomseago] + +1.8.1 / 2011-08-10 +=================== + + * fixed; ObjectIds were always marked modified + * fixed; can now query using document instances + * fixed; can now query/update using documents with subdocs + +1.8.0 / 2011-08-04 +=================== + + * fixed; can now use $all with String and Number + * fixed; can query subdoc array with $ne: null + * fixed; instance.subdocs#id now works with custom _ids + * fixed; do not apply setters when doc returned from db (change in bad behavior) + +1.7.4 / 2011-07-25 +=================== + + * fixed; sparse now a valid seperate schema option + * fixed; now catching cast errors in queries + * fixed; calling new Schema with object created in vm.runInNewContext now works (#384) [Sija] + * fixed; String enum was disallowing null + * fixed; Find by nested document _id now works (#389) + +1.7.3 / 2011-07-16 +=================== + + * fixed; MongooseArray#indexOf now works with ObjectIds + * fixed; validation scope now set properly (#418) + * fixed; added missing colors dependency (#398) + +1.7.2 / 2011-07-13 +=================== + + * changed; node-mongodb-native driver to v0.9.6.7 + +1.7.1 / 2011-07-12 +=================== + + * changed; roll back node-mongodb-native driver to v0.9.6.4 + +1.7.0 / 2011-07-12 +=================== + + * fixed; collection name misspelling [mathrawka] + * fixed; 2nd param is required for ReplSetServers [kevinmarvin] + * fixed; MongooseArray behaves properly with Object.keys + * changed; node-mongodb-native driver to v0.9.6.6 + * fixed/changed; Mongodb segfault when passed invalid ObjectId (#407) + - This means invalid data passed to the ObjectId constructor will now error + +1.6.0 / 2011-07-07 +=================== + + * changed; .save() errors are now emitted on the instances db instead of the instance 9782463fc + * fixed; errors occurring when creating indexes now properly emit on db + * added; $maxDistance support to MongooseArrays + * fixed; RegExps now work with $all + * changed; node-mongodb-native driver to v0.9.6.4 + * fixed; model names are now accessible via .modelName + * added; Query#slaveOk support + +1.5.0 / 2011-06-27 +=================== + + * changed; saving without a callback no longer ignores the error (@bnoguchi) + * changed; hook-js version bump to 0.1.9 + * changed; node-mongodb-native version bumped to 0.9.6.1 - When .remove() doesn't + return an error, null is no longer passed. + * fixed; two memory leaks (@justmoon) + * added; sparse index support + * added; more ObjectId conditionals (gt, lt, gte, lte) (@phillyqueso) + * added; options are now passed in model#remote (@JerryLuke) + +1.4.0 / 2011-06-10 +=================== + + * bumped hooks-js dependency (fixes issue passing null as first arg to next()) + * fixed; document#inspect now works properly with nested docs + * fixed; 'set' now works as a schema attribute (GH-365) + * fixed; _id is now set properly within pre-init hooks (GH-289) + * added; Query#distinct / Model#distinct support (GH-155) + * fixed; embedded docs now can use instance methods (GH-249) + * fixed; can now overwrite strings conflicting with schema type + +1.3.7 / 2011-06-03 +=================== + + * added MongooseArray#splice support + * fixed; 'path' is now a valid Schema pathname + * improved hooks (utilizing https://github.com/bnoguchi/hooks-js) + * fixed; MongooseArray#$shift now works (never did) + * fixed; Document.modified no longer throws + * fixed; modifying subdoc property sets modified paths for subdoc and parent doc + * fixed; marking subdoc path as modified properly persists the value to the db + * fixed; RexExps can again be saved ( #357 ) + +1.3.6 / 2011-05-18 +=================== + + * fixed; corrected casting for queries against array types + * added; Document#set now accepts Document instances + +1.3.5 / 2011-05-17 +=================== + + * fixed; $ne queries work properly with single vals + * added; #inspect() methods to improve console.log output + +1.3.4 / 2011-05-17 +=================== + + * fixed; find by Date works as expected (#336) + * added; geospatial 2d index support + * added; support for $near (#309) + * updated; node-mongodb-native driver + * fixed; updating numbers work (#342) + * added; better error msg when try to remove an embedded doc without an _id (#307) + * added; support for 'on-the-fly' schemas (#227) + * changed; virtual id getters can now be skipped + * fixed; .index() called on subdoc schema now works as expected + * fixed; db.setProfile() now buffers until the db is open (#340) + +1.3.3 / 2011-04-27 +=================== + + * fixed; corrected query casting on nested mixed types + +1.3.2 / 2011-04-27 +=================== + + * fixed; query hints now retain key order + +1.3.1 / 2011-04-27 +=================== + + * fixed; setting a property on an embedded array no longer overwrites entire array (GH-310) + * fixed; setting nested properties works when sibling prop is named "type" + * fixed; isModified is now much finer grained when .set() is used (GH-323) + * fixed; mongoose.model() and connection.model() now return the Model (GH-308, GH-305) + * fixed; can now use $gt, $lt, $gte, $lte with String schema types (GH-317) + * fixed; .lowercase() -> .toLowerCase() in pluralize() + * fixed; updating an embedded document by index works (GH-334) + * changed; .save() now passes the instance to the callback (GH-294, GH-264) + * added; can now query system.profile and system.indexes collections + * added; db.model('system.profile') is now included as a default Schema + * added; db.setProfiling(level, ms, callback) + * added; Query#hint() support + * added; more tests + * updated node-mongodb-native to 0.9.3 + +1.3.0 / 2011-04-19 +=================== + + * changed; save() callbacks now fire only once on failed validation + * changed; Errors returned from save() callbacks now instances of ValidationError + * fixed; MongooseArray#indexOf now works properly + +1.2.0 / 2011-04-11 +=================== + + * changed; MongooseNumber now casts empty string to null + +1.1.25 / 2011-04-08 +=================== + + * fixed; post init now fires at proper time + +1.1.24 / 2011-04-03 +=================== + + * fixed; pushing an array onto an Array works on existing docs + +1.1.23 / 2011-04-01 +=================== + + * Added Model#model + +1.1.22 / 2011-03-31 +=================== + + * Fixed; $in queries on mixed types now work + +1.1.21 / 2011-03-31 +=================== + + * Fixed; setting object root to null/undefined works + +1.1.20 / 2011-03-31 +=================== + + * Fixed; setting multiple props on null field works + +1.1.19 / 2011-03-31 +=================== + + * Fixed; no longer using $set on paths to an unexisting fields + +1.1.18 / 2011-03-30 +=================== + + * Fixed; non-mixed type object setters work after initd from null + +1.1.17 / 2011-03-30 +=================== + + * Fixed; nested object property access works when root initd with null value + +1.1.16 / 2011-03-28 +=================== + + * Fixed; empty arrays are now saved + +1.1.15 / 2011-03-28 +=================== + + * Fixed; `null` and `undefined` are set atomically. + +1.1.14 / 2011-03-28 +=================== + + * Changed; more forgiving date casting, accepting '' as null. + +1.1.13 / 2011-03-26 +=================== + + * Fixed setting values as `undefined`. + +1.1.12 / 2011-03-26 +=================== + + * Fixed; nested objects now convert to JSON properly + * Fixed; setting nested objects directly now works + * Update node-mongodb-native + +1.1.11 / 2011-03-25 +=================== + + * Fixed for use of `type` as a key. + +1.1.10 / 2011-03-23 +=================== + + * Changed; Make sure to only ensure indexes while connected + +1.1.9 / 2011-03-2 +================== + + * Fixed; Mixed can now default to empty arrays + * Fixed; keys by the name 'type' are now valid + * Fixed; null values retrieved from the database are hydrated as null values. + * Fixed repeated atomic operations when saving a same document twice. + +1.1.8 / 2011-03-23 +================== + + * Fixed 'id' overriding. [bnoguchi] + +1.1.7 / 2011-03-22 +================== + + * Fixed RegExp query casting when querying against an Array of Strings [bnoguchi] + * Fixed getters/setters for nested virtualsl. [bnoguchi] + +1.1.6 / 2011-03-22 +================== + + * Only doValidate when path exists in Schema [aheckmann] + * Allow function defaults for Array types [aheckmann] + * Fix validation hang [aheckmann] + * Fix setting of isRequired of SchemaType [aheckmann] + * Fix SchemaType#required(false) filter [aheckmann] + * More backwards compatibility [aheckmann] + * More tests [aheckmann] + +1.1.5 / 2011-03-14 +================== + + * Added support for `uri, db, fn` and `uri, fn` signatures for replica sets. + * Improved/extended replica set tests. + +1.1.4 / 2011-03-09 +================== + + * Fixed; running an empty Query doesn't throw. [aheckmann] + * Changed; Promise#addBack returns promise. [aheckmann] + * Added streaming cursor support. [aheckmann] + * Changed; Query#update defaults to use$SetOnSave now. [brian] + * Added more docs. + +1.1.3 / 2011-03-04 +================== + + * Added Promise#resolve [aheckmann] + * Fixed backward compatibility with nulls [aheckmann] + * Changed; Query#{run,exec} return promises [aheckmann] + +1.1.2 / 2011-03-03 +================== + + * Restored Query#exec and added notion of default operation [brian] + * Fixed ValidatorError messages [brian] + +1.1.1 / 2011-03-01 +================== + + * Added SchemaType String `lowercase`, `uppercase`, `trim`. + * Public exports (`Model`, `Document`) and tests. + * Added ObjectId casting support for `Document`s. + +1.1.0 / 2011-02-25 +================== + + * Added support for replica sets. + +1.0.16 / 2011-02-18 +=================== + + * Added $nin as another whitelisted $conditional for SchemaArray [brian] + * Changed #with to #where [brian] + * Added ability to use $in conditional with Array types [brian] + +1.0.15 / 2011-02-18 +=================== + + * Added `id` virtual getter for documents to easily access the hexString of + the `_id`. + +1.0.14 / 2011-02-17 +=================== + + * Fix for arrays within subdocuments [brian] + +1.0.13 / 2011-02-16 +=================== + + * Fixed embedded documents saving. + +1.0.12 / 2011-02-14 +=================== + + * Minor refactorings [brian] + +1.0.11 / 2011-02-14 +=================== + + * Query refactor and $ne, $slice, $or, $size, $elemMatch, $nin, $exists support [brian] + * Named scopes sugar [brian] + +1.0.10 / 2011-02-11 +=================== + + * Updated node-mongodb-native driver [thanks John Allen] + +1.0.9 / 2011-02-09 +================== + + * Fixed single member arrays as defaults [brian] + +1.0.8 / 2011-02-09 +================== + + * Fixed for collection-level buffering of commands [gitfy] + * Fixed `Document#toJSON` [dalejefferson] + * Fixed `Connection` authentication [robrighter] + * Fixed clash of accessors in getters/setters [eirikurn] + * Improved `Model#save` promise handling + +1.0.7 / 2011-02-05 +================== + + * Fixed memory leak warnings for test suite on 0.3 + * Fixed querying documents that have an array that contain at least one + specified member. [brian] + * Fixed default value for Array types (fixes GH-210). [brian] + * Fixed example code. + +1.0.6 / 2011-02-03 +================== + + * Fixed `post` middleware + * Fixed; it's now possible to instantiate a model even when one of the paths maps + to an undefined value [brian] + +1.0.5 / 2011-02-02 +================== + + * Fixed; combo $push and $pushAll auto-converts into a $pushAll [brian] + * Fixed; combo $pull and $pullAll auto-converts to a single $pullAll [brian] + * Fixed; $pullAll now removes said members from array before save (so it acts just + like pushAll) [brian] + * Fixed; multiple $pulls and $pushes become a single $pullAll and $pushAll. + Moreover, $pull now modifies the array before save to reflect the immediate + change [brian] + * Added tests for nested shortcut getters [brian] + * Added tests that show that Schemas with nested Arrays don't apply defaults + [brian] + +1.0.4 / 2011-02-02 +================== + + * Added MongooseNumber#toString + * Added MongooseNumber unit tests + +1.0.3 / 2011-02-02 +================== + + * Make sure safe mode works with Model#save + * Changed Schema options: safe mode is now the default + * Updated node-mongodb-native to HEAD + +1.0.2 / 2011-02-02 +================== + + * Added a Model.create shortcut for creating documents. [brian] + * Fixed; we can now instantiate models with hashes that map to at least one + null value. [brian] + * Fixed Schema with more than 2 nested levels. [brian] + +1.0.1 / 2011-02-02 +================== + + * Improved `MongooseNumber`, works almost like the native except for `typeof` + not being `'number'`. diff --git a/5-2/service/node_modules/mongoose/README.md b/5-2/service/node_modules/mongoose/README.md new file mode 100644 index 0000000..0f9e958 --- /dev/null +++ b/5-2/service/node_modules/mongoose/README.md @@ -0,0 +1,317 @@ +# Mongoose + +Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. + +[![Build Status](https://api.travis-ci.org/Automattic/mongoose.png?branch=master)](https://travis-ci.org/Automattic/mongoose) +[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Automattic/mongoose?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose) + +## Documentation + +[mongoosejs.com](http://mongoosejs.com/) + +## Support + + - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose) + - [bug reports](https://github.com/Automattic/mongoose/issues/) + - [help forum](http://groups.google.com/group/mongoose-orm) + - [MongoDB support](https://docs.mongodb.org/manual/support/) + - (irc) #mongoosejs on freenode + +## Plugins + +Check out the [plugins search site](http://plugins.mongoosejs.com/) to see hundreds of related modules from the community. + +Build your own Mongoose plugin through [generator-mongoose-plugin](https://github.com/huei90/generator-mongoose-plugin). + +## Contributors + +View all 100+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors). Stand up and be counted as a [contributor](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md) too! + +## Live Examples + + +## Installation + +First install [node.js](http://nodejs.org/) and [mongodb](https://www.mongodb.org/downloads). Then: + +```sh +$ npm install mongoose +``` + +## Stability + +The current stable branch is [master](https://github.com/Automattic/mongoose/tree/master). The [3.8.x](https://github.com/Automattic/mongoose/tree/3.8.x) branch contains legacy support for the 3.x release series, which is no longer under active development as of September 2015. The [3.8.x docs](http://mongoosejs.com/docs/3.8.x/) are still available. + +## Overview + +### Connecting to MongoDB + +First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`. + +Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`. + +```js +var mongoose = require('mongoose'); + +mongoose.connect('mongodb://localhost/my_database'); +``` + +Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`. + +**Note:** _If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed._ + +**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc. + +### Defining a Model + +Models are defined through the `Schema` interface. + +```js +var Schema = mongoose.Schema, + ObjectId = Schema.ObjectId; + +var BlogPost = new Schema({ + author : ObjectId, + title : String, + body : String, + date : Date +}); +``` + +Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of: + +* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync) +* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default) +* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get) +* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set) +* [Indexes](http://mongoosejs.com/docs/guide.html#indexes) +* [Middleware](http://mongoosejs.com/docs/middleware.html) +* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition +* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition +* [Plugins](http://mongoosejs.com/docs/plugins.html) +* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html) + +The following example shows some of these features: + +```js +var Comment = new Schema({ + name: { type: String, default: 'hahaha' }, + age: { type: Number, min: 18, index: true }, + bio: { type: String, match: /[a-z]/ }, + date: { type: Date, default: Date.now }, + buff: Buffer +}); + +// a setter +Comment.path('name').set(function (v) { + return capitalize(v); +}); + +// middleware +Comment.pre('save', function (next) { + notify(this.get('email')); + next(); +}); +``` + +Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup. + +### Accessing a Model + +Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function + +```js +var myModel = mongoose.model('ModelName'); +``` + +Or just do it all at once + +```js +var MyModel = mongoose.model('ModelName', mySchema); +``` + +The first argument is the _singular_ name of the collection your model is for. **Mongoose automatically looks for the _plural_ version of your model name.** For example, if you use + +```js +var MyModel = mongoose.model('Ticket', mySchema); +``` + +Then Mongoose will create the model for your __tickets__ collection, not your __ticket__ collection. + +Once we have our model, we can then instantiate it, and save it: + +```js +var instance = new MyModel(); +instance.my.key = 'hello'; +instance.save(function (err) { + // +}); +``` + +Or we can find documents from the same collection + +```js +MyModel.find({}, function (err, docs) { + // docs.forEach +}); +``` + +You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html). + +**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created: + +```js +var conn = mongoose.createConnection('your connection string'), + MyModel = conn.model('ModelName', schema), + m = new MyModel; +m.save(); // works +``` + +vs + +```js +var conn = mongoose.createConnection('your connection string'), + MyModel = mongoose.model('ModelName', schema), + m = new MyModel; +m.save(); // does not work b/c the default connection object was never connected +``` + +### Embedded Documents + +In the first example snippet, we defined a key in the Schema that looks like: + +``` +comments: [Comment] +``` + +Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as: + +```js +// retrieve my model +var BlogPost = mongoose.model('BlogPost'); + +// create a blog post +var post = new BlogPost(); + +// create a comment +post.comments.push({ title: 'My comment' }); + +post.save(function (err) { + if (!err) console.log('Success!'); +}); +``` + +The same goes for removing them: + +```js +BlogPost.findById(myId, function (err, post) { + if (!err) { + post.comments[0].remove(); + post.save(function (err) { + // do something + }); + } +}); +``` + +Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap! + + +### Middleware + +See the [docs](http://mongoosejs.com/docs/middleware.html) page. + +#### Intercepting and mutating method arguments + +You can intercept method arguments via middleware. + +For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value: + +```js +schema.pre('set', function (next, path, val, typel) { + // `this` is the current Document + this.emit('set', path, val); + + // Pass control to the next pre + next(); +}); +``` + +Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`: + +```js +.pre(method, function firstPre (next, methodArg1, methodArg2) { + // Mutate methodArg1 + next("altered-" + methodArg1.toString(), methodArg2); +}); + +// pre declaration is chainable +.pre(method, function secondPre (next, methodArg1, methodArg2) { + console.log(methodArg1); + // => 'altered-originalValOfMethodArg1' + + console.log(methodArg2); + // => 'originalValOfMethodArg2' + + // Passing no arguments to `next` automatically passes along the current argument values + // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)` + // and also equivalent to, with the example method arg + // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')` + next(); +}); +``` + +#### Schema gotcha + +`type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation: + +```js +new Schema({ + broken: { type: Boolean }, + asset : { + name: String, + type: String // uh oh, it broke. asset will be interpreted as String + } +}); + +new Schema({ + works: { type: Boolean }, + asset: { + name: String, + type: { type: String } // works. asset is an object with a type property + } +}); +``` + +### Driver access + +The driver being used defaults to [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) and is directly accessible through `YourModel.collection`. **Note**: using the driver directly bypasses all Mongoose power-tools like validation, getters, setters, hooks, etc. + +## API Docs + +Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](https://github.com/tj/dox) +and [acquit](https://github.com/vkarpov15/acquit). + +## License + +Copyright (c) 2010 LearnBoost <dev@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/5-2/service/node_modules/mongoose/examples/README.md b/5-2/service/node_modules/mongoose/examples/README.md new file mode 100644 index 0000000..cb32898 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/README.md @@ -0,0 +1,41 @@ +This directory contains runnable sample mongoose programs. + +To run: + + - first install [Node.js](http://nodejs.org/) + - from the root of the project, execute `npm install -d` + - in the example directory, run `npm install -d` + - from the command line, execute: `node example.js`, replacing "example.js" with the name of a program. + + +Goal is to show: + +- ~~global schemas~~ +- ~~GeoJSON schemas / use (with crs)~~ +- text search (once MongoDB removes the "Experimental/beta" label) +- ~~lean queries~~ +- ~~statics~~ +- methods and statics on subdocs +- custom types +- ~~querybuilder~~ +- ~~promises~~ +- accessing driver collection, db +- ~~connecting to replica sets~~ +- connecting to sharded clusters +- enabling a fail fast mode +- on the fly schemas +- storing files +- ~~map reduce~~ +- ~~aggregation~~ +- advanced hooks +- using $elemMatch to return a subset of an array +- query casting +- upserts +- pagination +- express + mongoose session handling +- ~~group by (use aggregation)~~ +- authentication +- schema migration techniques +- converting documents to plain objects (show transforms) +- how to $unset + diff --git a/5-2/service/node_modules/mongoose/examples/aggregate/aggregate.js b/5-2/service/node_modules/mongoose/examples/aggregate/aggregate.js new file mode 100644 index 0000000..ccafd49 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/aggregate/aggregate.js @@ -0,0 +1,103 @@ + +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)), + gender: 'Male', + likes: ['movies', 'games', 'dogs'] + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)), + gender: 'Female', + likes: ['movies', 'birds', 'cats'] + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)), + gender: 'Male', + likes: ['tv', 'games', 'rabbits'] + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)), + gender: 'Female', + likes: ['books', 'cats', 'dogs'] + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), + gender: 'Male', + likes: ['glasses', 'wine', 'the night'] + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) throw err; + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handle error + } + + // run an aggregate query that will get all of the people who like a given + // item. To see the full documentation on ways to use the aggregate + // framework, see http://docs.mongodb.org/manual/core/aggregation/ + Person.aggregate( + // select the fields we want to deal with + {$project: {name: 1, likes: 1}}, + // unwind 'likes', which will create a document for each like + {$unwind: '$likes'}, + // group everything by the like and then add each name with that like to + // the set for the like + {$group: { + _id: {likes: '$likes'}, + likers: {$addToSet: '$name'} + }}, + function(err, result) { + if (err) throw err; + console.log(result); + /* [ + { _id: { likes: 'the night' }, likers: [ 'alucard' ] }, + { _id: { likes: 'wine' }, likers: [ 'alucard' ] }, + { _id: { likes: 'books' }, likers: [ 'lilly' ] }, + { _id: { likes: 'glasses' }, likers: [ 'alucard' ] }, + { _id: { likes: 'birds' }, likers: [ 'mary' ] }, + { _id: { likes: 'rabbits' }, likers: [ 'bob' ] }, + { _id: { likes: 'cats' }, likers: [ 'lilly', 'mary' ] }, + { _id: { likes: 'dogs' }, likers: [ 'lilly', 'bill' ] }, + { _id: { likes: 'tv' }, likers: [ 'bob' ] }, + { _id: { likes: 'games' }, likers: [ 'bob', 'bill' ] }, + { _id: { likes: 'movies' }, likers: [ 'mary', 'bill' ] } + ] */ + + cleanup(); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/aggregate/package.json b/5-2/service/node_modules/mongoose/examples/aggregate/package.json new file mode 100644 index 0000000..53ed2e1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/aggregate/package.json @@ -0,0 +1,14 @@ +{ + "name": "aggregate-example", + "private": "true", + "version": "0.0.0", + "description": "deps for aggregate example", + "main": "aggregate.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-2/service/node_modules/mongoose/examples/aggregate/person.js b/5-2/service/node_modules/mongoose/examples/aggregate/person.js new file mode 100644 index 0000000..607bb07 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/aggregate/person.js @@ -0,0 +1,17 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date, + gender: String, + likes: [String] + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-2/service/node_modules/mongoose/examples/doc-methods.js b/5-2/service/node_modules/mongoose/examples/doc-methods.js new file mode 100644 index 0000000..1f648b9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/doc-methods.js @@ -0,0 +1,77 @@ + +var mongoose = require('mongoose'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Schema + */ + +var CharacterSchema = Schema({ + name: { + type: String, + required: true + }, + health: { + type: Number, + min: 0, + max: 100 + } +}); + +/** + * Methods + */ + +CharacterSchema.methods.attack = function() { + console.log('%s is attacking', this.name); +}; + +/** + * Character model + */ + +var Character = mongoose.model('Character', CharacterSchema); + +/** + * Connect to the database on localhost with + * the default port (27017) + */ + +var dbname = 'mongoose-example-doc-methods-' + ((Math.random() * 10000) | 0); +var uri = 'mongodb://localhost/' + dbname; + +console.log('connecting to %s', uri); + +mongoose.connect(uri, function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + example(); +}); + +/** + * Use case + */ + +function example() { + Character.create({name: 'Link', health: 100}, function(err, link) { + if (err) return done(err); + console.log('found', link); + link.attack(); // 'Link is attacking' + done(); + }); +} + +/** + * Clean up + */ + +function done(err) { + if (err) console.error(err); + mongoose.connection.db.dropDatabase(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/express/README.md b/5-2/service/node_modules/mongoose/examples/express/README.md new file mode 100644 index 0000000..7ba07b8 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/express/README.md @@ -0,0 +1 @@ +Mongoose + Express examples diff --git a/5-2/service/node_modules/mongoose/examples/express/connection-sharing/README.md b/5-2/service/node_modules/mongoose/examples/express/connection-sharing/README.md new file mode 100644 index 0000000..fc709a3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/express/connection-sharing/README.md @@ -0,0 +1,6 @@ + +To run: + +- Execute `npm install` from this directory +- Execute `node app.js` +- Navigate to `localhost:8000` diff --git a/5-2/service/node_modules/mongoose/examples/express/connection-sharing/app.js b/5-2/service/node_modules/mongoose/examples/express/connection-sharing/app.js new file mode 100644 index 0000000..8fb2fee --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/express/connection-sharing/app.js @@ -0,0 +1,17 @@ + +var express = require('express'); +var mongoose = require('../../../lib'); + +var uri = 'mongodb://localhost/mongoose-shared-connection'; +global.db = mongoose.createConnection(uri); + +var routes = require('./routes'); + +var app = express(); +app.get('/', routes.home); +app.get('/insert', routes.insert); +app.get('/name', routes.modelName); + +app.listen(8000, function() { + console.log('listening on http://localhost:8000'); +}); diff --git a/5-2/service/node_modules/mongoose/examples/express/connection-sharing/modelA.js b/5-2/service/node_modules/mongoose/examples/express/connection-sharing/modelA.js new file mode 100644 index 0000000..78f9ff6 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/express/connection-sharing/modelA.js @@ -0,0 +1,5 @@ +var Schema = require('../../../lib').Schema; +var mySchema = Schema({name: String}); + +/* global db */ +module.exports = db.model('MyModel', mySchema); diff --git a/5-2/service/node_modules/mongoose/examples/express/connection-sharing/package.json b/5-2/service/node_modules/mongoose/examples/express/connection-sharing/package.json new file mode 100644 index 0000000..e326165 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/express/connection-sharing/package.json @@ -0,0 +1,14 @@ +{ + "name": "connection-sharing", + "private": "true", + "version": "0.0.0", + "description": "ERROR: No README.md file found!", + "main": "app.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "express": "3.1.1" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-2/service/node_modules/mongoose/examples/express/connection-sharing/routes.js b/5-2/service/node_modules/mongoose/examples/express/connection-sharing/routes.js new file mode 100644 index 0000000..35e4f8f --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/express/connection-sharing/routes.js @@ -0,0 +1,20 @@ + +var model = require('./modelA'); + +exports.home = function(req, res, next) { + model.find(function(err, docs) { + if (err) return next(err); + res.send(docs); + }); +}; + +exports.modelName = function(req, res) { + res.send('my model name is ' + model.modelName); +}; + +exports.insert = function(req, res, next) { + model.create({name: 'inserting ' + Date.now()}, function(err, doc) { + if (err) return next(err); + res.send(doc); + }); +}; diff --git a/5-2/service/node_modules/mongoose/examples/geospatial/geoJSONSchema.js b/5-2/service/node_modules/mongoose/examples/geospatial/geoJSONSchema.js new file mode 100644 index 0000000..f950dea --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/geospatial/geoJSONSchema.js @@ -0,0 +1,22 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + // NOTE : This object must conform *precisely* to the geoJSON specification + // you cannot embed a geoJSON doc inside a model or anything like that- IT + // MUST BE VANILLA + var LocationObject = new Schema({ + loc: { + type: {type: String}, + coordinates: [] + } + }); + // define the index + LocationObject.index({loc: '2dsphere'}); + + mongoose.model('Location', LocationObject); +}; diff --git a/5-2/service/node_modules/mongoose/examples/geospatial/geoJSONexample.js b/5-2/service/node_modules/mongoose/examples/geospatial/geoJSONexample.js new file mode 100644 index 0000000..8e5dd2b --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/geospatial/geoJSONexample.js @@ -0,0 +1,56 @@ +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./geoJSONSchema.js')(); + +var Location = mongoose.model('Location'); + +// define some dummy data +// note: the type can be Point, LineString, or Polygon +var data = [ + {loc: {type: 'Point', coordinates: [-20.0, 5.0]}}, + {loc: {type: 'Point', coordinates: [6.0, 10.0]}}, + {loc: {type: 'Point', coordinates: [34.0, -50.0]}}, + {loc: {type: 'Point', coordinates: [-100.0, 70.0]}}, + {loc: {type: 'Point', coordinates: [38.0, 38.0]}} +]; + + +mongoose.connect('mongodb://localhost/locations', function(err) { + if (err) { + throw err; + } + + Location.on('index', function(err) { + if (err) { + throw err; + } + // create all of the dummy locations + async.each(data, function(item, cb) { + Location.create(item, cb); + }, function(err) { + if (err) { + throw err; + } + // create the location we want to search for + var coords = {type: 'Point', coordinates: [-5, 5]}; + // search for it + Location.find({loc: {$near: coords}}).limit(1).exec(function(err, res) { + if (err) { + throw err; + } + console.log('Closest to %s is %s', JSON.stringify(coords), res); + cleanup(); + }); + }); + }); +}); + +function cleanup() { + Location.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/geospatial/geospatial.js b/5-2/service/node_modules/mongoose/examples/geospatial/geospatial.js new file mode 100644 index 0000000..6e4b439 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/geospatial/geospatial.js @@ -0,0 +1,100 @@ +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)), + gender: 'Male', + likes: ['movies', 'games', 'dogs'], + loc: [0, 0] + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)), + gender: 'Female', + likes: ['movies', 'birds', 'cats'], + loc: [1, 1] + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)), + gender: 'Male', + likes: ['tv', 'games', 'rabbits'], + loc: [3, 3] + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)), + gender: 'Female', + likes: ['books', 'cats', 'dogs'], + loc: [6, 6] + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), + gender: 'Male', + likes: ['glasses', 'wine', 'the night'], + loc: [10, 10] + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) { + throw err; + } + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handler error + } + + // let's find the closest person to bob + Person.find({name: 'bob'}, function(err, res) { + if (err) { + throw err; + } + + res[0].findClosest(function(err, closest) { + if (err) { + throw err; + } + + console.log('%s is closest to %s', res[0].name, closest); + + + // we can also just query straight off of the model. For more + // information about geospatial queries and indexes, see + // http://docs.mongodb.org/manual/applications/geospatial-indexes/ + var coords = [7, 7]; + Person.find({loc: {$nearSphere: coords}}).limit(1).exec(function(err, res) { + console.log('Closest to %s is %s', coords, res); + cleanup(); + }); + }); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/geospatial/package.json b/5-2/service/node_modules/mongoose/examples/geospatial/package.json new file mode 100644 index 0000000..75c2a0e --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/geospatial/package.json @@ -0,0 +1,14 @@ +{ + "name": "geospatial-example", + "private": "true", + "version": "0.0.0", + "description": "deps for geospatial example", + "main": "geospatial.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-2/service/node_modules/mongoose/examples/geospatial/person.js b/5-2/service/node_modules/mongoose/examples/geospatial/person.js new file mode 100644 index 0000000..e816637 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/geospatial/person.js @@ -0,0 +1,27 @@ +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date, + gender: String, + likes: [String], + // define the geospatial field + loc: {type: [Number], index: '2d'} + }); + + // define a method to find the closest person + PersonSchema.methods.findClosest = function(cb) { + return this.model('Person').find({ + loc: {$nearSphere: this.loc}, + name: {$ne: this.name} + }).limit(1).exec(cb); + }; + + mongoose.model('Person', PersonSchema); +}; diff --git a/5-2/service/node_modules/mongoose/examples/globalschemas/gs_example.js b/5-2/service/node_modules/mongoose/examples/globalschemas/gs_example.js new file mode 100644 index 0000000..af9ff11 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/globalschemas/gs_example.js @@ -0,0 +1,47 @@ +var mongoose = require('../../lib'); + + +// import the global schema, this can be done in any file that needs the model +require('./person.js')(); + +// grab the person model object +var Person = mongoose.model('Person'); + +// connect to a server to do a quick write / read example + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) { + throw err; + } + + Person.create({ + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)) + }, function(err, bill) { + if (err) { + throw err; + } + console.log('People added to db: %s', bill.toString()); + Person.find({}, function(err, people) { + if (err) { + throw err; + } + + people.forEach(function(person) { + console.log('People in the db: %s', person.toString()); + }); + + // make sure to clean things up after we're done + setTimeout(function() { + cleanup(); + }, 2000); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/globalschemas/person.js b/5-2/service/node_modules/mongoose/examples/globalschemas/person.js new file mode 100644 index 0000000..39ae725 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/globalschemas/person.js @@ -0,0 +1,14 @@ +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-2/service/node_modules/mongoose/examples/lean/lean.js b/5-2/service/node_modules/mongoose/examples/lean/lean.js new file mode 100644 index 0000000..c3e682e --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/lean/lean.js @@ -0,0 +1,84 @@ + +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)), + gender: 'Male', + likes: ['movies', 'games', 'dogs'] + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)), + gender: 'Female', + likes: ['movies', 'birds', 'cats'] + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)), + gender: 'Male', + likes: ['tv', 'games', 'rabbits'] + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)), + gender: 'Female', + likes: ['books', 'cats', 'dogs'] + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), + gender: 'Male', + likes: ['glasses', 'wine', 'the night'] + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) throw err; + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handle error + } + + // lean queries return just plain javascript objects, not + // MongooseDocuments. This makes them good for high performance read + // situations + + // when using .lean() the default is true, but you can explicitly set the + // value by passing in a boolean value. IE. .lean(false) + var q = Person.find({age: {$lt: 1000}}).sort('age').limit(2).lean(); + q.exec(function(err, results) { + if (err) throw err; + console.log('Are the results MongooseDocuments?: %s', results[0] instanceof mongoose.Document); + + console.log(results); + cleanup(); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/lean/package.json b/5-2/service/node_modules/mongoose/examples/lean/package.json new file mode 100644 index 0000000..6ee511d --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/lean/package.json @@ -0,0 +1,14 @@ +{ + "name": "lean-example", + "private": "true", + "version": "0.0.0", + "description": "deps for lean example", + "main": "lean.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-2/service/node_modules/mongoose/examples/lean/person.js b/5-2/service/node_modules/mongoose/examples/lean/person.js new file mode 100644 index 0000000..b0bd2ed --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/lean/person.js @@ -0,0 +1,16 @@ +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date, + gender: String, + likes: [String] + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-2/service/node_modules/mongoose/examples/mapreduce/mapreduce.js b/5-2/service/node_modules/mongoose/examples/mapreduce/mapreduce.js new file mode 100644 index 0000000..593d73a --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/mapreduce/mapreduce.js @@ -0,0 +1,100 @@ +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)), + gender: 'Male' + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)), + gender: 'Female' + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)), + gender: 'Male' + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)), + gender: 'Female' + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), + gender: 'Male' + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) throw err; + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handle error + } + + // alright, simple map reduce example. We will find the total ages of each + // gender + + // create the options object + var o = {}; + + o.map = function() { + // in this function, 'this' refers to the current document being + // processed. Return the (gender, age) tuple using + /* global emit */ + emit(this.gender, this.age); + }; + + // the reduce function receives the array of ages that are grouped by the + // id, which in this case is the gender + o.reduce = function(id, ages) { + return Array.sum(ages); + }; + + // other options that can be specified + + // o.query = { age : { $lt : 1000 }}; // the query object + // o.limit = 3; // max number of documents + // o.keeptemp = true; // default is false, specifies whether to keep temp data + // o.finalize = someFunc; // function called after reduce + // o.scope = {}; // the scope variable exposed to map/reduce/finalize + // o.jsMode = true; // default is false, force execution to stay in JS + o.verbose = true; // default is false, provide stats on the job + // o.out = {}; // objects to specify where output goes, by default is + // returned, but can also be stored in a new collection + // see: http://mongoosejs.com/docs/api.html#model_Model.mapReduce + Person.mapReduce(o, function(err, results, stats) { + console.log('map reduce took %d ms', stats.processtime); + console.log(results); + cleanup(); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/mapreduce/package.json b/5-2/service/node_modules/mongoose/examples/mapreduce/package.json new file mode 100644 index 0000000..4240068 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/mapreduce/package.json @@ -0,0 +1,14 @@ +{ + "name": "map-reduce-example", + "private": "true", + "version": "0.0.0", + "description": "deps for map reduce example", + "main": "mapreduce.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-2/service/node_modules/mongoose/examples/mapreduce/person.js b/5-2/service/node_modules/mongoose/examples/mapreduce/person.js new file mode 100644 index 0000000..9e2f084 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/mapreduce/person.js @@ -0,0 +1,16 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date, + gender: String + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-2/service/node_modules/mongoose/examples/population/population-across-three-collections.js b/5-2/service/node_modules/mongoose/examples/population/population-across-three-collections.js new file mode 100644 index 0000000..fe6de72 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/population/population-across-three-collections.js @@ -0,0 +1,134 @@ + +var assert = require('assert'); +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; +var ObjectId = mongoose.Types.ObjectId; + +/** + * Connect to the db + */ + +var dbname = 'testing_populateAdInfinitum_' + require('../../lib/utils').random(); +mongoose.connect('localhost', dbname); +mongoose.connection.on('error', function() { + console.error('connection error', arguments); +}); + +/** + * Schemas + */ + +var user = new Schema({ + name: String, + friends: [{ + type: Schema.ObjectId, + ref: 'User' + }] +}); +var User = mongoose.model('User', user); + +var blogpost = Schema({ + title: String, + tags: [String], + author: { + type: Schema.ObjectId, + ref: 'User' + } +}); +var BlogPost = mongoose.model('BlogPost', blogpost); + +/** + * example + */ + +mongoose.connection.on('open', function() { + /** + * Generate data + */ + + var userIds = [new ObjectId, new ObjectId, new ObjectId, new ObjectId]; + var users = []; + + users.push({ + _id: userIds[0], + name: 'mary', + friends: [userIds[1], userIds[2], userIds[3]] + }); + users.push({ + _id: userIds[1], + name: 'bob', + friends: [userIds[0], userIds[2], userIds[3]] + }); + users.push({ + _id: userIds[2], + name: 'joe', + friends: [userIds[0], userIds[1], userIds[3]] + }); + users.push({ + _id: userIds[3], + name: 'sally', + friends: [userIds[0], userIds[1], userIds[2]] + }); + + User.create(users, function(err) { + assert.ifError(err); + + var blogposts = []; + blogposts.push({ + title: 'blog 1', + tags: ['fun', 'cool'], + author: userIds[3] + }); + blogposts.push({ + title: 'blog 2', + tags: ['cool'], + author: userIds[1] + }); + blogposts.push({ + title: 'blog 3', + tags: ['fun', 'odd'], + author: userIds[2] + }); + + BlogPost.create(blogposts, function(err) { + assert.ifError(err); + + /** + * Population + */ + + BlogPost + .find({tags: 'fun'}) + .lean() + .populate('author') + .exec(function(err, docs) { + assert.ifError(err); + + /** + * Populate the populated documents + */ + + var opts = { + path: 'author.friends', + select: 'name', + options: {limit: 2} + }; + + BlogPost.populate(docs, opts, function(err, docs) { + assert.ifError(err); + console.log('populated'); + var s = require('util').inspect(docs, {depth: null, colors: true}); + console.log(s); + done(); + }); + }); + }); + }); +}); + +function done(err) { + if (err) console.error(err.stack); + mongoose.connection.db.dropDatabase(function() { + mongoose.connection.close(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/population/population-basic.js b/5-2/service/node_modules/mongoose/examples/population/population-basic.js new file mode 100644 index 0000000..252cc53 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/population/population-basic.js @@ -0,0 +1,103 @@ + +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Console schema + */ + +var consoleSchema = Schema({ + name: String, + manufacturer: String, + released: Date +}); +var Console = mongoose.model('Console', consoleSchema); + +/** + * Game schema + */ + +var gameSchema = Schema({ + name: String, + developer: String, + released: Date, + consoles: [{ + type: Schema.Types.ObjectId, + ref: 'Console' + }] +}); +var Game = mongoose.model('Game', gameSchema); + +/** + * Connect to the console database on localhost with + * the default port (27017) + */ + +mongoose.connect('mongodb://localhost/console', function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + createData(); +}); + +/** + * Data generation + */ + +function createData() { + Console.create( + { + name: 'Nintendo 64', + manufacturer: 'Nintendo', + released: 'September 29, 1996' + }, + function(err, nintendo64) { + if (err) return done(err); + + Game.create({ + name: 'Legend of Zelda: Ocarina of Time', + developer: 'Nintendo', + released: new Date('November 21, 1998'), + consoles: [nintendo64] + }, + function(err) { + if (err) return done(err); + example(); + }); + } + ); +} + +/** + * Population + */ + +function example() { + Game + .findOne({name: /^Legend of Zelda/}) + .populate('consoles') + .exec(function(err, ocinara) { + if (err) return done(err); + + console.log( + '"%s" was released for the %s on %s', + ocinara.name, + ocinara.consoles[0].name, + ocinara.released.toLocaleDateString() + ); + + done(); + }); +} + +function done(err) { + if (err) console.error(err); + Console.remove(function() { + Game.remove(function() { + mongoose.disconnect(); + }); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/population/population-of-existing-doc.js b/5-2/service/node_modules/mongoose/examples/population/population-of-existing-doc.js new file mode 100644 index 0000000..c7eadfe --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/population/population-of-existing-doc.js @@ -0,0 +1,109 @@ + +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Console schema + */ + +var consoleSchema = Schema({ + name: String, + manufacturer: String, + released: Date +}); +var Console = mongoose.model('Console', consoleSchema); + +/** + * Game schema + */ + +var gameSchema = Schema({ + name: String, + developer: String, + released: Date, + consoles: [{ + type: Schema.Types.ObjectId, + ref: 'Console' + }] +}); +var Game = mongoose.model('Game', gameSchema); + +/** + * Connect to the console database on localhost with + * the default port (27017) + */ + +mongoose.connect('mongodb://localhost/console', function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + createData(); +}); + +/** + * Data generation + */ + +function createData() { + Console.create( + { + name: 'Nintendo 64', + manufacturer: 'Nintendo', + released: 'September 29, 1996' + }, + function(err, nintendo64) { + if (err) return done(err); + + Game.create({ + name: 'Legend of Zelda: Ocarina of Time', + developer: 'Nintendo', + released: new Date('November 21, 1998'), + consoles: [nintendo64] + }, + function(err) { + if (err) return done(err); + example(); + }); + } + ); +} + +/** + * Population + */ + +function example() { + Game + .findOne({name: /^Legend of Zelda/}) + .exec(function(err, ocinara) { + if (err) return done(err); + + console.log('"%s" console _id: %s', ocinara.name, ocinara.consoles[0]); + + // population of existing document + ocinara.populate('consoles', function(err) { + if (err) return done(err); + + console.log( + '"%s" was released for the %s on %s', + ocinara.name, + ocinara.consoles[0].name, + ocinara.released.toLocaleDateString() + ); + + done(); + }); + }); +} + +function done(err) { + if (err) console.error(err); + Console.remove(function() { + Game.remove(function() { + mongoose.disconnect(); + }); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js b/5-2/service/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js new file mode 100644 index 0000000..61b4e85 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js @@ -0,0 +1,124 @@ + +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Console schema + */ + +var consoleSchema = Schema({ + name: String, + manufacturer: String, + released: Date +}); +var Console = mongoose.model('Console', consoleSchema); + +/** + * Game schema + */ + +var gameSchema = Schema({ + name: String, + developer: String, + released: Date, + consoles: [{ + type: Schema.Types.ObjectId, + ref: 'Console' + }] +}); +var Game = mongoose.model('Game', gameSchema); + +/** + * Connect to the console database on localhost with + * the default port (27017) + */ + +mongoose.connect('mongodb://localhost/console', function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + createData(); +}); + +/** + * Data generation + */ + +function createData() { + Console.create( + { + name: 'Nintendo 64', + manufacturer: 'Nintendo', + released: 'September 29, 1996' + }, + { + name: 'Super Nintendo', + manufacturer: 'Nintendo', + released: 'August 23, 1991' + }, + function(err, nintendo64, superNintendo) { + if (err) return done(err); + + Game.create( + { + name: 'Legend of Zelda: Ocarina of Time', + developer: 'Nintendo', + released: new Date('November 21, 1998'), + consoles: [nintendo64] + }, + { + name: 'Mario Kart', + developer: 'Nintendo', + released: 'September 1, 1992', + consoles: [superNintendo] + }, + function(err) { + if (err) return done(err); + example(); + } + ); + } + ); +} + +/** + * Population + */ + +function example() { + Game + .find({}) + .exec(function(err, games) { + if (err) return done(err); + + console.log('found %d games', games.length); + + var options = {path: 'consoles', select: 'name released -_id'}; + Game.populate(games, options, function(err, games) { + if (err) return done(err); + + games.forEach(function(game) { + console.log( + '"%s" was released for the %s on %s', + game.name, + game.consoles[0].name, + game.released.toLocaleDateString() + ); + }); + + done(); + }); + }); +} + +function done(err) { + if (err) console.error(err); + Console.remove(function() { + Game.remove(function() { + mongoose.disconnect(); + }); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/population/population-options.js b/5-2/service/node_modules/mongoose/examples/population/population-options.js new file mode 100644 index 0000000..59cfd1e --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/population/population-options.js @@ -0,0 +1,138 @@ + +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Console schema + */ + +var consoleSchema = Schema({ + name: String, + manufacturer: String, + released: Date +}); +var Console = mongoose.model('Console', consoleSchema); + +/** + * Game schema + */ + +var gameSchema = Schema({ + name: String, + developer: String, + released: Date, + consoles: [{ + type: Schema.Types.ObjectId, + ref: 'Console' + }] +}); +var Game = mongoose.model('Game', gameSchema); + +/** + * Connect to the console database on localhost with + * the default port (27017) + */ + +mongoose.connect('mongodb://localhost/console', function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + createData(); +}); + +/** + * Data generation + */ + +function createData() { + Console.create( + { + name: 'Nintendo 64', + manufacturer: 'Nintendo', + released: 'September 29, 1996' + }, + { + name: 'Super Nintendo', + manufacturer: 'Nintendo', + released: 'August 23, 1991' + }, + { + name: 'XBOX 360', + manufacturer: 'Microsoft', + released: 'November 22, 2005' + }, + function(err, nintendo64, superNintendo, xbox360) { + if (err) return done(err); + + Game.create( + { + name: 'Legend of Zelda: Ocarina of Time', + developer: 'Nintendo', + released: new Date('November 21, 1998'), + consoles: [nintendo64] + }, + { + name: 'Mario Kart', + developer: 'Nintendo', + released: 'September 1, 1992', + consoles: [superNintendo] + }, + { + name: 'Perfect Dark Zero', + developer: 'Rare', + released: 'November 17, 2005', + consoles: [xbox360] + }, + function(err) { + if (err) return done(err); + example(); + } + ); + } + ); +} + +/** + * Population + */ + +function example() { + Game + .find({}) + .populate({ + path: 'consoles', + match: {manufacturer: 'Nintendo'}, + select: 'name', + options: {comment: 'population'} + }) + .exec(function(err, games) { + if (err) return done(err); + + games.forEach(function(game) { + console.log( + '"%s" was released for the %s on %s', + game.name, + game.consoles.length ? game.consoles[0].name : '??', + game.released.toLocaleDateString() + ); + }); + + return done(); + }); +} + +/** + * Clean up + */ + +function done(err) { + if (err) console.error(err); + Console.remove(function() { + Game.remove(function() { + mongoose.disconnect(); + }); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/population/population-plain-objects.js b/5-2/service/node_modules/mongoose/examples/population/population-plain-objects.js new file mode 100644 index 0000000..ba849dc --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/population/population-plain-objects.js @@ -0,0 +1,106 @@ + +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Console schema + */ + +var consoleSchema = Schema({ + name: String, + manufacturer: String, + released: Date +}); +var Console = mongoose.model('Console', consoleSchema); + +/** + * Game schema + */ + +var gameSchema = Schema({ + name: String, + developer: String, + released: Date, + consoles: [{ + type: Schema.Types.ObjectId, + ref: 'Console' + }] +}); +var Game = mongoose.model('Game', gameSchema); + +/** + * Connect to the console database on localhost with + * the default port (27017) + */ + +mongoose.connect('mongodb://localhost/console', function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + createData(); +}); + +/** + * Data generation + */ + +function createData() { + Console.create( + { + name: 'Nintendo 64', + manufacturer: 'Nintendo', + released: 'September 29, 1996' + }, + function(err, nintendo64) { + if (err) return done(err); + + Game.create( + { + name: 'Legend of Zelda: Ocarina of Time', + developer: 'Nintendo', + released: new Date('November 21, 1998'), + consoles: [nintendo64] + }, + function(err) { + if (err) return done(err); + example(); + } + ); + } + ); +} + +/** + * Population + */ + +function example() { + Game + .findOne({name: /^Legend of Zelda/}) + .populate('consoles') + .lean() // just return plain objects, not documents wrapped by mongoose + .exec(function(err, ocinara) { + if (err) return done(err); + + console.log( + '"%s" was released for the %s on %s', + ocinara.name, + ocinara.consoles[0].name, + ocinara.released.toLocaleDateString() + ); + + done(); + }); +} + +function done(err) { + if (err) console.error(err); + Console.remove(function() { + Game.remove(function() { + mongoose.disconnect(); + }); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/promises/package.json b/5-2/service/node_modules/mongoose/examples/promises/package.json new file mode 100644 index 0000000..1983250 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/promises/package.json @@ -0,0 +1,14 @@ +{ + "name": "promise-example", + "private": "true", + "version": "0.0.0", + "description": "deps for promise example", + "main": "promise.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-2/service/node_modules/mongoose/examples/promises/person.js b/5-2/service/node_modules/mongoose/examples/promises/person.js new file mode 100644 index 0000000..40e2bf1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/promises/person.js @@ -0,0 +1,15 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-2/service/node_modules/mongoose/examples/promises/promise.js b/5-2/service/node_modules/mongoose/examples/promises/promise.js new file mode 100644 index 0000000..fd1ff7a --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/promises/promise.js @@ -0,0 +1,94 @@ +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)) + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)) + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)) + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)) + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)) + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) { + throw err; + } + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handle error + } + + // create a promise (get one from the query builder) + var prom = Person.find({age: {$lt: 1000}}).exec(); + + // add a callback on the promise. This will be called on both error and + // complete + prom.addBack(function() { + console.log('completed'); + }); + + // add a callback that is only called on complete (success) events + prom.addCallback(function() { + console.log('Successful Completion!'); + }); + + // add a callback that is only called on err (rejected) events + prom.addErrback(function() { + console.log('Fail Boat'); + }); + + // you can chain things just like in the promise/A+ spec + // note: each then() is returning a new promise, so the above methods + // that we defined will all fire after the initial promise is fulfilled + prom.then(function(people) { + // just getting the stuff for the next query + var ids = people.map(function(p) { + return p._id; + }); + + // return the next promise + return Person.find({_id: {$nin: ids}}).exec(); + }).then(function(oldest) { + console.log('Oldest person is: %s', oldest); + }).then(cleanup); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/querybuilder/package.json b/5-2/service/node_modules/mongoose/examples/querybuilder/package.json new file mode 100644 index 0000000..1a3450a --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/querybuilder/package.json @@ -0,0 +1,14 @@ +{ + "name": "query-builder-example", + "private": "true", + "version": "0.0.0", + "description": "deps for query builder example", + "main": "querybuilder.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-2/service/node_modules/mongoose/examples/querybuilder/person.js b/5-2/service/node_modules/mongoose/examples/querybuilder/person.js new file mode 100644 index 0000000..40e2bf1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/querybuilder/person.js @@ -0,0 +1,15 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-2/service/node_modules/mongoose/examples/querybuilder/querybuilder.js b/5-2/service/node_modules/mongoose/examples/querybuilder/querybuilder.js new file mode 100644 index 0000000..723a357 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/querybuilder/querybuilder.js @@ -0,0 +1,79 @@ + +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)) + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)) + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)) + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)) + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)) + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) throw err; + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) throw err; + + // when querying data, instead of providing a callback, you can instead + // leave that off and get a query object returned + var query = Person.find({age: {$lt: 1000}}); + + // this allows you to continue applying modifiers to it + query.sort('birthday'); + query.select('name'); + + // you can chain them together as well + // a full list of methods can be found: + // http://mongoosejs.com/docs/api.html#query-js + query.where('age').gt(21); + + // finally, when ready to execute the query, call the exec() function + query.exec(function(err, results) { + if (err) throw err; + + console.log(results); + + cleanup(); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/replicasets/package.json b/5-2/service/node_modules/mongoose/examples/replicasets/package.json new file mode 100644 index 0000000..927dfd2 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/replicasets/package.json @@ -0,0 +1,14 @@ +{ + "name": "replica-set-example", + "private": "true", + "version": "0.0.0", + "description": "deps for replica set example", + "main": "querybuilder.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-2/service/node_modules/mongoose/examples/replicasets/person.js b/5-2/service/node_modules/mongoose/examples/replicasets/person.js new file mode 100644 index 0000000..40e2bf1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/replicasets/person.js @@ -0,0 +1,15 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-2/service/node_modules/mongoose/examples/replicasets/replica-sets.js b/5-2/service/node_modules/mongoose/examples/replicasets/replica-sets.js new file mode 100644 index 0000000..6aa27b5 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/replicasets/replica-sets.js @@ -0,0 +1,71 @@ + +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)) + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)) + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)) + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)) + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)) + } +]; + + +// to connect to a replica set, pass in the comma delimited uri and optionally +// any connection options such as the rs_name. +var opts = { + replSet: {rs_name: 'rs0'} +}; +mongoose.connect('mongodb://localhost:27018/persons,localhost:27019,localhost:27020', opts, function(err) { + if (err) throw err; + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handle error + } + + // create and delete some data + var prom = Person.find({age: {$lt: 1000}}).exec(); + + prom.then(function(people) { + console.log('young people: %s', people); + }).then(cleanup); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/examples/schema/schema.js b/5-2/service/node_modules/mongoose/examples/schema/schema.js new file mode 100644 index 0000000..5bc99ae --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/schema/schema.js @@ -0,0 +1,119 @@ +/** + * Module dependencies. + */ + +var mongoose = require('../../lib'), + Schema = mongoose.Schema; + +/** + * Schema definition + */ + +// recursive embedded-document schema + +var Comment = new Schema(); + +Comment.add({ + title: { + type: String, + index: true + }, + date: Date, + body: String, + comments: [Comment] +}); + +var BlogPost = new Schema({ + title: { + type: String, + index: true + }, + slug: { + type: String, + lowercase: true, + trim: true + }, + date: Date, + buf: Buffer, + comments: [Comment], + creator: Schema.ObjectId +}); + +var Person = new Schema({ + name: { + first: String, + last: String + }, + email: { + type: String, + required: true, + index: { + unique: true, + sparse: true + } + }, + alive: Boolean +}); + +/** + * Accessing a specific schema type by key + */ + +BlogPost.path('date') +.default(function() { + return new Date(); +}) +.set(function(v) { + return v === 'now' ? new Date() : v; +}); + +/** + * Pre hook. + */ + +BlogPost.pre('save', function(next, done) { + /* global emailAuthor */ + emailAuthor(done); // some async function + next(); +}); + +/** + * Methods + */ + +BlogPost.methods.findCreator = function(callback) { + return this.db.model('Person').findById(this.creator, callback); +}; + +BlogPost.statics.findByTitle = function(title, callback) { + return this.find({title: title}, callback); +}; + +BlogPost.methods.expressiveQuery = function(creator, date, callback) { + return this.find('creator', creator).where('date').gte(date).run(callback); +}; + +/** + * Plugins + */ + +function slugGenerator(options) { + options = options || {}; + var key = options.key || 'title'; + + return function slugGenerator(schema) { + schema.path(key).set(function(v) { + this.slug = v.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/-+/g, ''); + return v; + }); + }; +} + +BlogPost.plugin(slugGenerator()); + +/** + * Define model. + */ + +mongoose.model('BlogPost', BlogPost); +mongoose.model('Person', Person); diff --git a/5-2/service/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js b/5-2/service/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js new file mode 100644 index 0000000..284b478 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js @@ -0,0 +1,27 @@ + +// modules +var mongoose = require('../../../lib'); +var Schema = mongoose.Schema; + +// parse json +var raw = require('./schema.json'); + +// create a schema +var timeSignatureSchema = Schema(raw); + +// compile the model +var TimeSignature = mongoose.model('TimeSignatures', timeSignatureSchema); + +// create a TimeSignature document +var threeFour = new TimeSignature({ + count: 3, + unit: 4, + description: '3/4', + additive: false, + created: new Date, + links: ['http://en.wikipedia.org/wiki/Time_signature'], + user_id: '518d31a0ef32bbfa853a9814' +}); + +// print its description +console.log(threeFour); diff --git a/5-2/service/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json b/5-2/service/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json new file mode 100644 index 0000000..5afc626 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json @@ -0,0 +1,9 @@ +{ + "count": "number", + "unit": "number", + "description": "string", + "links": ["string"], + "created": "date", + "additive": "boolean", + "user_id": "ObjectId" +} diff --git a/5-2/service/node_modules/mongoose/examples/statics/person.js b/5-2/service/node_modules/mongoose/examples/statics/person.js new file mode 100644 index 0000000..a93b8c6 --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/statics/person.js @@ -0,0 +1,20 @@ +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date + }); + + // define a static + PersonSchema.statics.findPersonByName = function(name, cb) { + this.find({name: new RegExp(name, 'i')}, cb); + }; + + mongoose.model('Person', PersonSchema); +}; diff --git a/5-2/service/node_modules/mongoose/examples/statics/statics.js b/5-2/service/node_modules/mongoose/examples/statics/statics.js new file mode 100644 index 0000000..610b2aa --- /dev/null +++ b/5-2/service/node_modules/mongoose/examples/statics/statics.js @@ -0,0 +1,41 @@ +var mongoose = require('../../lib'); + + +// import the schema +require('./person.js')(); + +// grab the person model object +var Person = mongoose.model('Person'); + +// connect to a server to do a quick write / read example + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) { + throw err; + } + + Person.create({name: 'bill', age: 25, birthday: new Date().setFullYear((new Date().getFullYear() - 25))}, + function(err, bill) { + if (err) { + throw err; + } + console.log('People added to db: %s', bill.toString()); + + // using the static + Person.findPersonByName('bill', function(err, result) { + if (err) { + throw err; + } + + console.log(result); + cleanup(); + }); + } + ); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-2/service/node_modules/mongoose/index.js b/5-2/service/node_modules/mongoose/index.js new file mode 100644 index 0000000..e7e6278 --- /dev/null +++ b/5-2/service/node_modules/mongoose/index.js @@ -0,0 +1,7 @@ + +/** + * Export lib/mongoose + * + */ + +module.exports = require('./lib/'); diff --git a/5-2/service/node_modules/mongoose/lib/ES6Promise.js b/5-2/service/node_modules/mongoose/lib/ES6Promise.js new file mode 100644 index 0000000..13371ac --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/ES6Promise.js @@ -0,0 +1,26 @@ +/** + * ES6 Promise wrapper constructor. + * + * Promises are returned from executed queries. Example: + * + * var query = Candy.find({ bar: true }); + * var promise = query.exec(); + * + * DEPRECATED. Mongoose 5.0 will use native promises by default (or bluebird, + * if native promises are not present) but still + * support plugging in your own ES6-compatible promises library. Mongoose 5.0 + * will **not** support mpromise. + * + * @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature + * @api public + */ + +function ES6Promise() { + throw new Error('Can\'t use ES6 promise with mpromise style constructor'); +} + +ES6Promise.use = function(Promise) { + ES6Promise.ES6 = Promise; +}; + +module.exports = ES6Promise; diff --git a/5-2/service/node_modules/mongoose/lib/aggregate.js b/5-2/service/node_modules/mongoose/lib/aggregate.js new file mode 100644 index 0000000..fd2c2fc --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/aggregate.js @@ -0,0 +1,623 @@ +/*! + * Module dependencies + */ + +var util = require('util'); +var utils = require('./utils'); +var PromiseProvider = require('./promise_provider'); +var Query = require('./query'); +var read = Query.prototype.read; + +/** + * Aggregate constructor used for building aggregation pipelines. + * + * ####Example: + * + * new Aggregate(); + * new Aggregate({ $project: { a: 1, b: 1 } }); + * new Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); + * new Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); + * + * Returned when calling Model.aggregate(). + * + * ####Example: + * + * Model + * .aggregate({ $match: { age: { $gte: 21 }}}) + * .unwind('tags') + * .exec(callback) + * + * ####Note: + * + * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). + * - Requires MongoDB >= 2.1 + * - Mongoose does **not** cast pipeline stages. `new Aggregate({ $match: { _id: '00000000000000000000000a' } });` will not work unless `_id` is a string in the database. Use `new Aggregate({ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } });` instead. + * + * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ + * @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate + * @param {Object|Array} [ops] aggregation operator(s) or operator array + * @api public + */ + +function Aggregate() { + this._pipeline = []; + this._model = undefined; + this.options = undefined; + + if (arguments.length === 1 && util.isArray(arguments[0])) { + this.append.apply(this, arguments[0]); + } else { + this.append.apply(this, arguments); + } +} + +/** + * Binds this aggregate to a model. + * + * @param {Model} model the model to which the aggregate is to be bound + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.model = function(model) { + this._model = model; + return this; +}; + +/** + * Appends new operators to this aggregate pipeline + * + * ####Examples: + * + * aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); + * + * // or pass an array + * var pipeline = [{ $match: { daw: 'Logic Audio X' }} ]; + * aggregate.append(pipeline); + * + * @param {Object} ops operator(s) to append + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.append = function() { + var args = (arguments.length === 1 && util.isArray(arguments[0])) + ? arguments[0] + : utils.args(arguments); + + if (!args.every(isOperator)) { + throw new Error('Arguments must be aggregate pipeline operators'); + } + + this._pipeline = this._pipeline.concat(args); + + return this; +}; + +/** + * Appends a new $project operator to this aggregate pipeline. + * + * Mongoose query [selection syntax](#query_Query-select) is also supported. + * + * ####Examples: + * + * // include a, include b, exclude _id + * aggregate.project("a b -_id"); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * aggregate.project({a: 1, b: 1, _id: 0}); + * + * // reshaping documents + * aggregate.project({ + * newField: '$b.nested' + * , plusTen: { $add: ['$val', 10]} + * , sub: { + * name: '$a' + * } + * }) + * + * // etc + * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); + * + * @param {Object|String} arg field specification + * @see projection http://docs.mongodb.org/manual/reference/aggregation/project/ + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.project = function(arg) { + var fields = {}; + + if (typeof arg === 'object' && !util.isArray(arg)) { + Object.keys(arg).forEach(function(field) { + fields[field] = arg[field]; + }); + } else if (arguments.length === 1 && typeof arg === 'string') { + arg.split(/\s+/).forEach(function(field) { + if (!field) { + return; + } + var include = field[0] === '-' ? 0 : 1; + if (include === 0) { + field = field.substring(1); + } + fields[field] = include; + }); + } else { + throw new Error('Invalid project() argument. Must be string or object'); + } + + return this.append({$project: fields}); +}; + +/** + * Appends a new custom $group operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.group({ _id: "$department" }); + * + * @see $group http://docs.mongodb.org/manual/reference/aggregation/group/ + * @method group + * @memberOf Aggregate + * @param {Object} arg $group operator contents + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new custom $match operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.match({ department: { $in: [ "sales", "engineering" } } }); + * + * @see $match http://docs.mongodb.org/manual/reference/aggregation/match/ + * @method match + * @memberOf Aggregate + * @param {Object} arg $match operator contents + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new $skip operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.skip(10); + * + * @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/ + * @method skip + * @memberOf Aggregate + * @param {Number} num number of records to skip before next stage + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new $limit operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.limit(10); + * + * @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/ + * @method limit + * @memberOf Aggregate + * @param {Number} num maximum number of records to pass to the next stage + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new $geoNear operator to this aggregate pipeline. + * + * ####NOTE: + * + * **MUST** be used as the first operator in the pipeline. + * + * ####Examples: + * + * aggregate.near({ + * near: [40.724, -73.997], + * distanceField: "dist.calculated", // required + * maxDistance: 0.008, + * query: { type: "public" }, + * includeLocs: "dist.location", + * uniqueDocs: true, + * num: 5 + * }); + * + * @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/ + * @method near + * @memberOf Aggregate + * @param {Object} parameters + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.near = function(arg) { + var op = {}; + op.$geoNear = arg; + return this.append(op); +}; + +/*! + * define methods + */ + +'group match skip limit out'.split(' ').forEach(function($operator) { + Aggregate.prototype[$operator] = function(arg) { + var op = {}; + op['$' + $operator] = arg; + return this.append(op); + }; +}); + +/** + * Appends new custom $unwind operator(s) to this aggregate pipeline. + * + * Note that the `$unwind` operator requires the path name to start with '$'. + * Mongoose will prepend '$' if the specified field doesn't start '$'. + * + * ####Examples: + * + * aggregate.unwind("tags"); + * aggregate.unwind("a", "b", "c"); + * + * @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/ + * @param {String} fields the field(s) to unwind + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.unwind = function() { + var args = utils.args(arguments); + + return this.append.apply(this, args.map(function(arg) { + return {$unwind: (arg && arg.charAt(0) === '$') ? arg : '$' + arg}; + })); +}; + +/** + * Appends new custom $lookup operator(s) to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' }); + * + * @see $lookup https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/#pipe._S_lookup + * @param {Object} options to $lookup as described in the above link + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.lookup = function(options) { + return this.append({$lookup: options}); +}; + +/** + * Appends new custom $sample operator(s) to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.sample(3); // Add a pipeline that picks 3 random documents + * + * @see $sample https://docs.mongodb.org/manual/reference/operator/aggregation/sample/#pipe._S_sample + * @param {Number} size number of random documents to pick + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.sample = function(size) { + return this.append({$sample: {size: size}}); +}; + +/** + * Appends a new $sort operator to this aggregate pipeline. + * + * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + * + * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + * + * ####Examples: + * + * // these are equivalent + * aggregate.sort({ field: 'asc', test: -1 }); + * aggregate.sort('field -test'); + * + * @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/ + * @param {Object|String} arg + * @return {Aggregate} this + * @api public + */ + +Aggregate.prototype.sort = function(arg) { + // TODO refactor to reuse the query builder logic + + var sort = {}; + + if (arg.constructor.name === 'Object') { + var desc = ['desc', 'descending', -1]; + Object.keys(arg).forEach(function(field) { + sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1; + }); + } else if (arguments.length === 1 && typeof arg === 'string') { + arg.split(/\s+/).forEach(function(field) { + if (!field) { + return; + } + var ascend = field[0] === '-' ? -1 : 1; + if (ascend === -1) { + field = field.substring(1); + } + sort[field] = ascend; + }); + } else { + throw new TypeError('Invalid sort() argument. Must be a string or object.'); + } + + return this.append({$sort: sort}); +}; + +/** + * Sets the readPreference option for the aggregation query. + * + * ####Example: + * + * Model.aggregate(..).read('primaryPreferred').exec(callback) + * + * @param {String} pref one of the listed preference options or their aliases + * @param {Array} [tags] optional tags for this query + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + */ + +Aggregate.prototype.read = function(pref, tags) { + if (!this.options) { + this.options = {}; + } + read.call(this, pref, tags); + return this; +}; + +/** + * Execute the aggregation with explain + * + * ####Example: + * + * Model.aggregate(..).explain(callback) + * + * @param {Function} callback + * @return {Promise} + */ + +Aggregate.prototype.explain = function(callback) { + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + if (!_this._pipeline.length) { + var err = new Error('Aggregate has empty pipeline'); + if (callback) { + callback(err); + } + reject(err); + return; + } + + prepareDiscriminatorPipeline(_this); + + _this._model + .collection + .aggregate(_this._pipeline, _this.options || {}) + .explain(function(error, result) { + if (error) { + if (callback) { + callback(error); + } + reject(error); + return; + } + + if (callback) { + callback(null, result); + } + resolve(result); + }); + }); +}; + +/** + * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) + * + * ####Example: + * + * Model.aggregate(..).allowDiskUse(true).exec(callback) + * + * @param {Boolean} value Should tell server it can use hard drive to store data during aggregation. + * @param {Array} [tags] optional tags for this query + * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ + */ + +Aggregate.prototype.allowDiskUse = function(value) { + if (!this.options) { + this.options = {}; + } + this.options.allowDiskUse = value; + return this; +}; + +/** + * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). + * Note the different syntax below: .exec() returns a cursor object, and no callback + * is necessary. + * + * ####Example: + * + * var cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec(); + * cursor.each(function(error, doc) { + * // use doc + * }); + * + * @param {Object} options set the cursor batch size + * @see mongodb http://mongodb.github.io/node-mongodb-native/2.0/api/AggregationCursor.html + */ + +Aggregate.prototype.cursor = function(options) { + if (!this.options) { + this.options = {}; + } + this.options.cursor = options || {}; + return this; +}; + +/** + * Executes the aggregate pipeline on the currently bound Model. + * + * ####Example: + * + * aggregate.exec(callback); + * + * // Because a promise is returned, the `callback` is optional. + * var promise = aggregate.exec(); + * promise.then(..); + * + * @see Promise #promise_Promise + * @param {Function} [callback] + * @return {Promise} + * @api public + */ + +Aggregate.prototype.exec = function(callback) { + if (!this._model) { + throw new Error('Aggregate not bound to any Model'); + } + var _this = this; + var Promise = PromiseProvider.get(); + + if (this.options && this.options.cursor) { + if (this.options.cursor.async) { + return new Promise.ES6(function(resolve) { + if (!_this._model.collection.buffer) { + process.nextTick(function() { + var cursor = _this._model.collection. + aggregate(_this._pipeline, _this.options || {}); + resolve(cursor); + callback && callback(cursor); + }); + return; + } + _this._model.collection.emitter.once('queue', function() { + var cursor = _this._model.collection. + aggregate(_this._pipeline, _this.options || {}); + resolve(cursor); + callback && callback(null, cursor); + }); + }); + } + return this._model.collection. + aggregate(this._pipeline, this.options || {}); + } + + return new Promise.ES6(function(resolve, reject) { + if (!_this._pipeline.length) { + var err = new Error('Aggregate has empty pipeline'); + if (callback) { + callback(err); + } + reject(err); + return; + } + + prepareDiscriminatorPipeline(_this); + + _this._model + .collection + .aggregate(_this._pipeline, _this.options || {}, function(error, result) { + if (error) { + if (callback) { + callback(error); + } + reject(error); + return; + } + + if (callback) { + callback(null, result); + } + resolve(result); + }); + }); +}; + +/*! + * Helpers + */ + +/** + * Checks whether an object is likely a pipeline operator + * + * @param {Object} obj object to check + * @return {Boolean} + * @api private + */ + +function isOperator(obj) { + var k; + + if (typeof obj !== 'object') { + return false; + } + + k = Object.keys(obj); + + return k.length === 1 && k + .some(function(key) { + return key[0] === '$'; + }); +} + +/*! + * Adds the appropriate `$match` pipeline step to the top of an aggregate's + * pipeline, should it's model is a non-root discriminator type. This is + * analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`. + * + * @param {Aggregate} aggregate Aggregate to prepare + */ + +function prepareDiscriminatorPipeline(aggregate) { + var schema = aggregate._model.schema, + discriminatorMapping = schema && schema.discriminatorMapping; + + if (discriminatorMapping && !discriminatorMapping.isRoot) { + var originalPipeline = aggregate._pipeline, + discriminatorKey = discriminatorMapping.key, + discriminatorValue = discriminatorMapping.value; + + // If the first pipeline stage is a match and it doesn't specify a `__t` + // key, add the discriminator key to it. This allows for potential + // aggregation query optimizations not to be disturbed by this feature. + if (originalPipeline[0] && originalPipeline[0].$match && !originalPipeline[0].$match[discriminatorKey]) { + originalPipeline[0].$match[discriminatorKey] = discriminatorValue; + // `originalPipeline` is a ref, so there's no need for + // aggregate._pipeline = originalPipeline + } else if (originalPipeline[0] && originalPipeline[0].$geoNear) { + originalPipeline[0].$geoNear.query = + originalPipeline[0].$geoNear.query || {}; + originalPipeline[0].$geoNear.query[discriminatorKey] = discriminatorValue; + } else { + var match = {}; + match[discriminatorKey] = discriminatorValue; + aggregate._pipeline = [{$match: match}].concat(originalPipeline); + } + } +} + + +/*! + * Exports + */ + +module.exports = Aggregate; diff --git a/5-2/service/node_modules/mongoose/lib/browser.js b/5-2/service/node_modules/mongoose/lib/browser.js new file mode 100644 index 0000000..74a7b6e --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/browser.js @@ -0,0 +1,99 @@ +/* eslint-env browser */ + +/** + * The [MongooseError](#error_MongooseError) constructor. + * + * @method Error + * @api public + */ + +exports.Error = require('./error'); + +/** + * The Mongoose [Schema](#schema_Schema) constructor + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var Schema = mongoose.Schema; + * var CatSchema = new Schema(..); + * + * @method Schema + * @api public + */ + +exports.Schema = require('./schema'); + +/** + * The various Mongoose Types. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var array = mongoose.Types.Array; + * + * ####Types: + * + * - [ObjectId](#types-objectid-js) + * - [Buffer](#types-buffer-js) + * - [SubDocument](#types-embedded-js) + * - [Array](#types-array-js) + * - [DocumentArray](#types-documentarray-js) + * + * Using this exposed access to the `ObjectId` type, we can construct ids on demand. + * + * var ObjectId = mongoose.Types.ObjectId; + * var id1 = new ObjectId; + * + * @property Types + * @api public + */ +exports.Types = require('./types'); + +/** + * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor + * + * @method VirtualType + * @api public + */ +exports.VirtualType = require('./virtualtype'); + +/** + * The various Mongoose SchemaTypes. + * + * ####Note: + * + * _Alias of mongoose.Schema.Types for backwards compatibility._ + * + * @property SchemaTypes + * @see Schema.SchemaTypes #schema_Schema.Types + * @api public + */ + +exports.SchemaType = require('./schematype.js'); + +/** + * Internal utils + * + * @property utils + * @api private + */ + +exports.utils = require('./utils.js'); + +/** + * The Mongoose browser [Document](#document-js) constructor. + * + * @method Document + * @api public + */ +exports.Document = require('./document_provider.js')(); + +/*! + * Module exports. + */ + +if (typeof window !== 'undefined') { + window.mongoose = module.exports; + window.Buffer = Buffer; +} diff --git a/5-2/service/node_modules/mongoose/lib/browserDocument.js b/5-2/service/node_modules/mongoose/lib/browserDocument.js new file mode 100644 index 0000000..6c87d19 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/browserDocument.js @@ -0,0 +1,103 @@ +/*! + * Module dependencies. + */ + +var NodeJSDocument = require('./document'), + EventEmitter = require('events').EventEmitter, + MongooseError = require('./error'), + Schema = require('./schema'), + ObjectId = require('./types/objectid'), + utils = require('./utils'), + ValidationError = MongooseError.ValidationError, + InternalCache = require('./internal'); + +/** + * Document constructor. + * + * @param {Object} obj the values to set + * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data + * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose. + * @event `save`: Emitted when the document is successfully saved + * @api private + */ + +function Document(obj, schema, fields, skipId, skipInit) { + if (!(this instanceof Document)) { + return new Document(obj, schema, fields, skipId, skipInit); + } + + + if (utils.isObject(schema) && !schema.instanceOfSchema) { + schema = new Schema(schema); + } + + // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id + schema = this.schema || schema; + + // Generate ObjectId if it is missing, but it requires a scheme + if (!this.schema && schema.options._id) { + obj = obj || {}; + + if (obj._id === undefined) { + obj._id = new ObjectId(); + } + } + + if (!schema) { + throw new MongooseError.MissingSchemaError(); + } + + this.$__setSchema(schema); + + this.$__ = new InternalCache; + this.$__.emitter = new EventEmitter(); + this.isNew = true; + this.errors = undefined; + + // var schema = this.schema; + + if (typeof fields === 'boolean') { + this.$__.strictMode = fields; + fields = undefined; + } else { + this.$__.strictMode = this.schema.options && this.schema.options.strict; + this.$__.selected = fields; + } + + var required = this.schema.requiredPaths(); + for (var i = 0; i < required.length; ++i) { + this.$__.activePaths.require(required[i]); + } + + this.$__.emitter.setMaxListeners(0); + this._doc = this.$__buildDoc(obj, fields, skipId); + + if (!skipInit && obj) { + this.init(obj); + } + + this.$__registerHooksFromSchema(); + + // apply methods + for (var m in schema.methods) { + this[m] = schema.methods[m]; + } + // apply statics + for (var s in schema.statics) { + this[s] = schema.statics[s]; + } +} + +/*! + * Inherit from the NodeJS document + */ +Document.prototype = Object.create(NodeJSDocument.prototype); +Document.prototype.constructor = Document; + +/*! + * Module exports. + */ +Document.ValidationError = ValidationError; +module.exports = exports = Document; diff --git a/5-2/service/node_modules/mongoose/lib/cast.js b/5-2/service/node_modules/mongoose/lib/cast.js new file mode 100644 index 0000000..9c63ee3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/cast.js @@ -0,0 +1,204 @@ +/*! + * Module dependencies. + */ + +var utils = require('./utils'); +var Types = require('./schema/index'); + +/** + * Handles internal casting for queries + * + * @param {Schema} schema + * @param {Object} obj Object to cast + * @api private + */ +module.exports = function cast(schema, obj) { + var paths = Object.keys(obj), + i = paths.length, + any$conditionals, + schematype, + nested, + path, + type, + val; + + while (i--) { + path = paths[i]; + val = obj[path]; + + if (path === '$or' || path === '$nor' || path === '$and') { + var k = val.length; + + while (k--) { + val[k] = cast(schema, val[k]); + } + } else if (path === '$where') { + type = typeof val; + + if (type !== 'string' && type !== 'function') { + throw new Error('Must have a string or function for $where'); + } + + if (type === 'function') { + obj[path] = val.toString(); + } + + continue; + } else if (path === '$elemMatch') { + val = cast(schema, val); + } else { + if (!schema) { + // no casting for Mixed types + continue; + } + + schematype = schema.path(path); + + if (!schematype) { + // Handle potential embedded array queries + var split = path.split('.'), + j = split.length, + pathFirstHalf, + pathLastHalf, + remainingConds; + + // Find the part of the var path that is a path of the Schema + while (j--) { + pathFirstHalf = split.slice(0, j).join('.'); + schematype = schema.path(pathFirstHalf); + if (schematype) { + break; + } + } + + // If a substring of the input path resolves to an actual real path... + if (schematype) { + // Apply the casting; similar code for $elemMatch in schema/array.js + if (schematype.caster && schematype.caster.schema) { + remainingConds = {}; + pathLastHalf = split.slice(j).join('.'); + remainingConds[pathLastHalf] = val; + obj[path] = cast(schematype.caster.schema, remainingConds)[pathLastHalf]; + } else { + obj[path] = val; + } + continue; + } + + if (utils.isObject(val)) { + // handle geo schemas that use object notation + // { loc: { long: Number, lat: Number } + + var geo = val.$near ? '$near' : + val.$nearSphere ? '$nearSphere' : + val.$within ? '$within' : + val.$geoIntersects ? '$geoIntersects' : ''; + + if (!geo) { + continue; + } + + var numbertype = new Types.Number('__QueryCasting__'); + var value = val[geo]; + + if (val.$maxDistance) { + val.$maxDistance = numbertype.castForQuery(val.$maxDistance); + } + + if (geo === '$within') { + var withinType = value.$center + || value.$centerSphere + || value.$box + || value.$polygon; + + if (!withinType) { + throw new Error('Bad $within paramater: ' + JSON.stringify(val)); + } + + value = withinType; + } else if (geo === '$near' && + typeof value.type === 'string' && Array.isArray(value.coordinates)) { + // geojson; cast the coordinates + value = value.coordinates; + } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') && + value.$geometry && typeof value.$geometry.type === 'string' && + Array.isArray(value.$geometry.coordinates)) { + // geojson; cast the coordinates + value = value.$geometry.coordinates; + } + + _cast(value, numbertype); + } + } else if (val === null || val === undefined) { + obj[path] = null; + continue; + } else if (val.constructor.name === 'Object') { + any$conditionals = Object.keys(val).some(function(k) { + return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; + }); + + if (!any$conditionals) { + obj[path] = schematype.castForQuery(val); + } else { + var ks = Object.keys(val), + $cond; + + k = ks.length; + + while (k--) { + $cond = ks[k]; + nested = val[$cond]; + + if ($cond === '$exists') { + if (typeof nested !== 'boolean') { + throw new Error('$exists parameter must be Boolean'); + } + continue; + } + + if ($cond === '$type') { + if (typeof nested !== 'number') { + throw new Error('$type parameter must be Number'); + } + continue; + } + + if ($cond === '$not') { + cast(schema, nested); + } else { + val[$cond] = schematype.castForQuery($cond, nested); + } + } + } + } else { + obj[path] = schematype.castForQuery(val); + } + } + } + + return obj; +}; + +function _cast(val, numbertype) { + if (Array.isArray(val)) { + val.forEach(function(item, i) { + if (Array.isArray(item) || utils.isObject(item)) { + return _cast(item, numbertype); + } + val[i] = numbertype.castForQuery(item); + }); + } else { + var nearKeys = Object.keys(val); + var nearLen = nearKeys.length; + while (nearLen--) { + var nkey = nearKeys[nearLen]; + var item = val[nkey]; + if (Array.isArray(item) || utils.isObject(item)) { + _cast(item, numbertype); + val[nkey] = item; + } else { + val[nkey] = numbertype.castForQuery(item); + } + } + } +} diff --git a/5-2/service/node_modules/mongoose/lib/collection.js b/5-2/service/node_modules/mongoose/lib/collection.js new file mode 100644 index 0000000..3aee0aa --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/collection.js @@ -0,0 +1,206 @@ +/*! + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var STATES = require('./connectionstate'); + +/** + * Abstract Collection constructor + * + * This is the base class that drivers inherit from and implement. + * + * @param {String} name name of the collection + * @param {Connection} conn A MongooseConnection instance + * @param {Object} opts optional collection options + * @api public + */ + +function Collection(name, conn, opts) { + if (opts === void 0) { + opts = {}; + } + if (opts.capped === void 0) { + opts.capped = {}; + } + + opts.bufferCommands = undefined === opts.bufferCommands + ? true + : opts.bufferCommands; + + if (typeof opts.capped === 'number') { + opts.capped = {size: opts.capped}; + } + + this.opts = opts; + this.name = name; + this.collectionName = name; + this.conn = conn; + this.queue = []; + this.buffer = this.opts.bufferCommands; + this.emitter = new EventEmitter(); + + if (STATES.connected === this.conn.readyState) { + this.onOpen(); + } +} + +/** + * The collection name + * + * @api public + * @property name + */ + +Collection.prototype.name; + +/** + * The collection name + * + * @api public + * @property collectionName + */ + +Collection.prototype.collectionName; + +/** + * The Connection instance + * + * @api public + * @property conn + */ + +Collection.prototype.conn; + +/** + * Called when the database connects + * + * @api private + */ + +Collection.prototype.onOpen = function() { + this.buffer = false; + this.doQueue(); +}; + +/** + * Called when the database disconnects + * + * @api private + */ + +Collection.prototype.onClose = function() { + if (this.opts.bufferCommands) { + this.buffer = true; + } +}; + +/** + * Queues a method for later execution when its + * database connection opens. + * + * @param {String} name name of the method to queue + * @param {Array} args arguments to pass to the method when executed + * @api private + */ + +Collection.prototype.addQueue = function(name, args) { + this.queue.push([name, args]); + return this; +}; + +/** + * Executes all queued methods and clears the queue. + * + * @api private + */ + +Collection.prototype.doQueue = function() { + for (var i = 0, l = this.queue.length; i < l; i++) { + this[this.queue[i][0]].apply(this, this.queue[i][1]); + } + this.queue = []; + var _this = this; + process.nextTick(function() { + _this.emitter.emit('queue'); + }); + return this; +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.ensureIndex = function() { + throw new Error('Collection#ensureIndex unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.findAndModify = function() { + throw new Error('Collection#findAndModify unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.findOne = function() { + throw new Error('Collection#findOne unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.find = function() { + throw new Error('Collection#find unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.insert = function() { + throw new Error('Collection#insert unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.save = function() { + throw new Error('Collection#save unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.update = function() { + throw new Error('Collection#update unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.getIndexes = function() { + throw new Error('Collection#getIndexes unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.mapReduce = function() { + throw new Error('Collection#mapReduce unimplemented by driver'); +}; + +/*! + * Module exports. + */ + +module.exports = Collection; diff --git a/5-2/service/node_modules/mongoose/lib/connection.js b/5-2/service/node_modules/mongoose/lib/connection.js new file mode 100644 index 0000000..e2fa003 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/connection.js @@ -0,0 +1,787 @@ +/*! + * Module dependencies. + */ + +var utils = require('./utils'), + EventEmitter = require('events').EventEmitter, + driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native', + Schema = require('./schema'), + Collection = require(driver + '/collection'), + STATES = require('./connectionstate'), + MongooseError = require('./error'), + muri = require('muri'), + PromiseProvider = require('./promise_provider'); + +/*! + * Protocol prefix regexp. + * + * @api private + */ + +var rgxProtocol = /^(?:.)+:\/\//; + +/*! + * A list of authentication mechanisms that don't require a password for authentication. + * This is used by the authMechanismDoesNotRequirePassword method. + * + * @api private + */ +var authMechanismsWhichDontRequirePassword = [ + 'MONGODB-X509' +]; + +/** + * Connection constructor + * + * For practical reasons, a Connection equals a Db. + * + * @param {Mongoose} base a mongoose instance + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `connecting`: Emitted when `connection.{open,openSet}()` is executed on this connection. + * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios. + * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models. + * @event `disconnecting`: Emitted when `connection.close()` was executed. + * @event `disconnected`: Emitted after getting disconnected from the db. + * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models. + * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection. + * @event `error`: Emitted when an error occurs on this connection. + * @event `fullsetup`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. + * @api public + */ + +function Connection(base) { + this.base = base; + this.collections = {}; + this.models = {}; + this.config = {autoIndex: true}; + this.replica = false; + this.hosts = null; + this.host = null; + this.port = null; + this.user = null; + this.pass = null; + this.name = null; + this.options = null; + this.otherDbs = []; + this._readyState = STATES.disconnected; + this._closeCalled = false; + this._hasOpened = false; +} + +/*! + * Inherit from EventEmitter + */ + +Connection.prototype.__proto__ = EventEmitter.prototype; + +/** + * Connection ready state + * + * - 0 = disconnected + * - 1 = connected + * - 2 = connecting + * - 3 = disconnecting + * + * Each state change emits its associated event name. + * + * ####Example + * + * conn.on('connected', callback); + * conn.on('disconnected', callback); + * + * @property readyState + * @api public + */ + +Object.defineProperty(Connection.prototype, 'readyState', { + get: function() { + return this._readyState; + }, + set: function(val) { + if (!(val in STATES)) { + throw new Error('Invalid connection state: ' + val); + } + + if (this._readyState !== val) { + this._readyState = val; + // loop over the otherDbs on this connection and change their state + for (var i = 0; i < this.otherDbs.length; i++) { + this.otherDbs[i].readyState = val; + } + + if (STATES.connected === val) { + this._hasOpened = true; + } + + this.emit(STATES[val]); + } + } +}); + +/** + * A hash of the collections associated with this connection + * + * @property collections + */ + +Connection.prototype.collections; + +/** + * The mongodb.Db instance, set when the connection is opened + * + * @property db + */ + +Connection.prototype.db; + +/** + * A hash of the global options that are associated with this connection + * + * @property global + */ + +Connection.prototype.config; + +/** + * Opens the connection to MongoDB. + * + * `options` is a hash with the following possible properties: + * + * config - passed to the connection config instance + * db - passed to the connection db instance + * server - passed to the connection server instance(s) + * replset - passed to the connection ReplSet instance + * user - username for authentication + * pass - password for authentication + * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) + * + * ####Notes: + * + * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden. + * Mongoose defaults the server `auto_reconnect` options to true which can be overridden. + * See the node-mongodb-native driver instance for options that it understands. + * + * _Options passed take precedence over options included in connection strings._ + * + * @param {String} connection_string mongodb://uri or the host to which you are connecting + * @param {String} [database] database name + * @param {Number} [port] database port + * @param {Object} [options] options + * @param {Function} [callback] + * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native + * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate + * @api public + */ + +Connection.prototype.open = function(host, database, port, options, callback) { + var parsed; + + if (typeof database === 'string') { + switch (arguments.length) { + case 2: + port = 27017; + break; + case 3: + switch (typeof port) { + case 'function': + callback = port; + port = 27017; + break; + case 'object': + options = port; + port = 27017; + break; + } + break; + case 4: + if (typeof options === 'function') { + callback = options; + options = {}; + } + } + } else { + switch (typeof database) { + case 'function': + callback = database; + database = undefined; + break; + case 'object': + options = database; + database = undefined; + callback = port; + break; + } + + if (!rgxProtocol.test(host)) { + host = 'mongodb://' + host; + } + + try { + parsed = muri(host); + } catch (err) { + this.error(err, callback); + return this; + } + + database = parsed.db; + host = parsed.hosts[0].host || parsed.hosts[0].ipc; + port = parsed.hosts[0].port || 27017; + } + + this.options = this.parseOptions(options, parsed && parsed.options); + + // make sure we can open + if (STATES.disconnected !== this.readyState) { + var err = new Error('Trying to open unclosed connection.'); + err.state = this.readyState; + this.error(err, callback); + return this; + } + + if (!host) { + this.error(new Error('Missing hostname.'), callback); + return this; + } + + if (!database) { + this.error(new Error('Missing database name.'), callback); + return this; + } + + // authentication + if (this.optionsProvideAuthenticationData(options)) { + this.user = options.user; + this.pass = options.pass; + } else if (parsed && parsed.auth) { + this.user = parsed.auth.user; + this.pass = parsed.auth.pass; + + // Check hostname for user/pass + } else if (/@/.test(host) && /:/.test(host.split('@')[0])) { + host = host.split('@'); + var auth = host.shift().split(':'); + host = host.pop(); + this.user = auth[0]; + this.pass = auth[1]; + } else { + this.user = this.pass = undefined; + } + + // global configuration options + if (options && options.config) { + this.config.autoIndex = options.config.autoIndex !== false; + } + + this.name = database; + this.host = host; + this.port = port; + + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _this._open(!!callback, function(error) { + callback && callback(error); + if (error) { + reject(error); + return; + } + resolve(); + }); + }); +}; + +/** + * Opens the connection to a replica set. + * + * ####Example: + * + * var db = mongoose.createConnection(); + * db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019"); + * + * The database name and/or auth need only be included in one URI. + * The `options` is a hash which is passed to the internal driver connection object. + * + * Valid `options` + * + * db - passed to the connection db instance + * server - passed to the connection server instance(s) + * replset - passed to the connection ReplSetServer instance + * user - username for authentication + * pass - password for authentication + * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) + * mongos - Boolean - if true, enables High Availability support for mongos + * + * _Options passed take precedence over options included in connection strings._ + * + * ####Notes: + * + * _If connecting to multiple mongos servers, set the `mongos` option to true._ + * + * conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb); + * + * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden. + * Mongoose defaults the server `auto_reconnect` options to true which can be overridden. + * See the node-mongodb-native driver instance for options that it understands. + * + * _Options passed take precedence over options included in connection strings._ + * + * @param {String} uris comma-separated mongodb:// `URI`s + * @param {String} [database] database name if not included in `uris` + * @param {Object} [options] passed to the internal driver + * @param {Function} [callback] + * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native + * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate + * @api public + */ + +Connection.prototype.openSet = function(uris, database, options, callback) { + if (!rgxProtocol.test(uris)) { + uris = 'mongodb://' + uris; + } + + switch (arguments.length) { + case 3: + switch (typeof database) { + case 'string': + this.name = database; + break; + case 'object': + callback = options; + options = database; + database = null; + break; + } + + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 2: + switch (typeof database) { + case 'string': + this.name = database; + break; + case 'function': + callback = database; + database = null; + break; + case 'object': + options = database; + database = null; + break; + } + } + + var parsed; + try { + parsed = muri(uris); + } catch (err) { + this.error(err, callback); + return this; + } + + if (!this.name) { + this.name = parsed.db; + } + + this.hosts = parsed.hosts; + this.options = this.parseOptions(options, parsed && parsed.options); + this.replica = true; + + if (!this.name) { + this.error(new Error('No database name provided for replica set'), callback); + return this; + } + + // authentication + if (this.optionsProvideAuthenticationData(options)) { + this.user = options.user; + this.pass = options.pass; + } else if (parsed && parsed.auth) { + this.user = parsed.auth.user; + this.pass = parsed.auth.pass; + } else { + this.user = this.pass = undefined; + } + + // global configuration options + if (options && options.config) { + this.config.autoIndex = options.config.autoIndex !== false; + } + + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _this._open(!!callback, function(error) { + callback && callback(error); + if (error) { + reject(error); + return; + } + resolve(); + }); + }); +}; + +/** + * error + * + * Graceful error handling, passes error to callback + * if available, else emits error on the connection. + * + * @param {Error} err + * @param {Function} callback optional + * @api private + */ + +Connection.prototype.error = function(err, callback) { + if (callback) { + return callback(err); + } + this.emit('error', err); +}; + +/** + * Handles opening the connection with the appropriate method based on connection type. + * + * @param {Function} callback + * @api private + */ + +Connection.prototype._open = function(emit, callback) { + this.readyState = STATES.connecting; + this._closeCalled = false; + + var _this = this; + + var method = this.replica + ? 'doOpenSet' + : 'doOpen'; + + // open connection + this[method](function(err) { + if (err) { + _this.readyState = STATES.disconnected; + if (_this._hasOpened) { + if (callback) { + callback(err); + } + } else { + _this.error(err, emit && callback); + } + return; + } + + _this.onOpen(callback); + }); +}; + +/** + * Called when the connection is opened + * + * @api private + */ + +Connection.prototype.onOpen = function(callback) { + var _this = this; + + function open(err, isAuth) { + if (err) { + _this.readyState = isAuth ? STATES.unauthorized : STATES.disconnected; + if (_this._hasOpened) { + if (callback) { + callback(err); + } + } else { + _this.error(err, callback); + } + return; + } + + _this.readyState = STATES.connected; + + // avoid having the collection subscribe to our event emitter + // to prevent 0.3 warning + for (var i in _this.collections) { + _this.collections[i].onOpen(); + } + + callback && callback(); + _this.emit('open'); + } + + // re-authenticate + if (this.shouldAuthenticate()) { + _this.db.authenticate(_this.user, _this.pass, _this.options.auth, function(err) { + open(err, true); + }); + } else { + open(); + } +}; + +/** + * Closes the connection + * + * @param {Function} [callback] optional + * @return {Connection} self + * @api public + */ + +Connection.prototype.close = function(callback) { + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _this._close(function(error) { + callback && callback(error); + if (error) { + reject(error); + return; + } + resolve(); + }); + }); +}; + +/** + * Handles closing the connection + * + * @param {Function} callback + * @api private + */ +Connection.prototype._close = function(callback) { + var _this = this; + this._closeCalled = true; + + switch (this.readyState) { + case 0: // disconnected + callback && callback(); + break; + + case 1: // connected + case 4: // unauthorized + this.readyState = STATES.disconnecting; + this.doClose(function(err) { + if (err) { + _this.error(err, callback); + } else { + _this.onClose(); + callback && callback(); + } + }); + break; + + case 2: // connecting + this.once('open', function() { + _this.close(callback); + }); + break; + + case 3: // disconnecting + if (!callback) { + break; + } + this.once('close', function() { + callback(); + }); + break; + } + + return this; +}; + +/** + * Called when the connection closes + * + * @api private + */ + +Connection.prototype.onClose = function() { + this.readyState = STATES.disconnected; + + // avoid having the collection subscribe to our event emitter + // to prevent 0.3 warning + for (var i in this.collections) { + this.collections[i].onClose(); + } + + this.emit('close'); +}; + +/** + * Retrieves a collection, creating it if not cached. + * + * Not typically needed by applications. Just talk to your collection through your model. + * + * @param {String} name of the collection + * @param {Object} [options] optional collection options + * @return {Collection} collection instance + * @api public + */ + +Connection.prototype.collection = function(name, options) { + if (!(name in this.collections)) { + this.collections[name] = new Collection(name, this, options); + } + return this.collections[name]; +}; + +/** + * Defines or retrieves a model. + * + * var mongoose = require('mongoose'); + * var db = mongoose.createConnection(..); + * db.model('Venue', new Schema(..)); + * var Ticket = db.model('Ticket', new Schema(..)); + * var Venue = db.model('Venue'); + * + * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ + * + * ####Example: + * + * var schema = new Schema({ name: String }, { collection: 'actor' }); + * + * // or + * + * schema.set('collection', 'actor'); + * + * // or + * + * var collectionName = 'actor' + * var M = conn.model('Actor', schema, collectionName) + * + * @param {String} name the model name + * @param {Schema} [schema] a schema. necessary when defining a model + * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name + * @see Mongoose#model #index_Mongoose-model + * @return {Model} The compiled model + * @api public + */ + +Connection.prototype.model = function(name, schema, collection) { + // collection name discovery + if (typeof schema === 'string') { + collection = schema; + schema = false; + } + + if (utils.isObject(schema) && !schema.instanceOfSchema) { + schema = new Schema(schema); + } + + if (this.models[name] && !collection) { + // model exists but we are not subclassing with custom collection + if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { + throw new MongooseError.OverwriteModelError(name); + } + return this.models[name]; + } + + var opts = {cache: false, connection: this}; + var model; + + if (schema && schema.instanceOfSchema) { + // compile a model + model = this.base.model(name, schema, collection, opts); + + // only the first model with this name is cached to allow + // for one-offs with custom collection names etc. + if (!this.models[name]) { + this.models[name] = model; + } + + model.init(); + return model; + } + + if (this.models[name] && collection) { + // subclassing current model with alternate collection + model = this.models[name]; + schema = model.prototype.schema; + var sub = model.__subclass(this, schema, collection); + // do not cache the sub model + return sub; + } + + // lookup model in mongoose module + model = this.base.models[name]; + + if (!model) { + throw new MongooseError.MissingSchemaError(name); + } + + if (this === model.prototype.db + && (!collection || collection === model.collection.name)) { + // model already uses this connection. + + // only the first model with this name is cached to allow + // for one-offs with custom collection names etc. + if (!this.models[name]) { + this.models[name] = model; + } + + return model; + } + this.models[name] = model.__subclass(this, schema, collection); + return this.models[name]; +}; + +/** + * Returns an array of model names created on this connection. + * @api public + * @return {Array} + */ + +Connection.prototype.modelNames = function() { + return Object.keys(this.models); +}; + +/** + * @brief Returns if the connection requires authentication after it is opened. Generally if a + * username and password are both provided than authentication is needed, but in some cases a + * password is not required. + * @api private + * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false. + */ +Connection.prototype.shouldAuthenticate = function() { + return (this.user !== null && this.user !== void 0) && + ((this.pass !== null || this.pass !== void 0) || this.authMechanismDoesNotRequirePassword()); +}; + +/** + * @brief Returns a boolean value that specifies if the current authentication mechanism needs a + * password to authenticate according to the auth objects passed into the open/openSet methods. + * @api private + * @return {Boolean} true if the authentication mechanism specified in the options object requires + * a password, otherwise false. + */ +Connection.prototype.authMechanismDoesNotRequirePassword = function() { + if (this.options && this.options.auth) { + return authMechanismsWhichDontRequirePassword.indexOf(this.options.auth.authMechanism) >= 0; + } + return true; +}; + +/** + * @brief Returns a boolean value that specifies if the provided objects object provides enough + * data to authenticate with. Generally this is true if the username and password are both specified + * but in some authentication methods, a password is not required for authentication so only a username + * is required. + * @param {Object} [options] the options object passed into the open/openSet methods. + * @api private + * @return {Boolean} true if the provided options object provides enough data to authenticate with, + * otherwise false. + */ +Connection.prototype.optionsProvideAuthenticationData = function(options) { + return (options) && + (options.user) && + ((options.pass) || this.authMechanismDoesNotRequirePassword()); +}; + +/*! + * Module exports. + */ + +Connection.STATES = STATES; +module.exports = Connection; diff --git a/5-2/service/node_modules/mongoose/lib/connectionstate.js b/5-2/service/node_modules/mongoose/lib/connectionstate.js new file mode 100644 index 0000000..b9d1baf --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/connectionstate.js @@ -0,0 +1,27 @@ + +/*! + * Connection states + */ + +var STATES = module.exports = exports = Object.create(null); + +var disconnected = 'disconnected'; +var connected = 'connected'; +var connecting = 'connecting'; +var disconnecting = 'disconnecting'; +var unauthorized = 'unauthorized'; +var uninitialized = 'uninitialized'; + +STATES[0] = disconnected; +STATES[1] = connected; +STATES[2] = connecting; +STATES[3] = disconnecting; +STATES[4] = unauthorized; +STATES[99] = uninitialized; + +STATES[disconnected] = 0; +STATES[connected] = 1; +STATES[connecting] = 2; +STATES[disconnecting] = 3; +STATES[unauthorized] = 4; +STATES[uninitialized] = 99; diff --git a/5-2/service/node_modules/mongoose/lib/document.js b/5-2/service/node_modules/mongoose/lib/document.js new file mode 100644 index 0000000..f9da698 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/document.js @@ -0,0 +1,2412 @@ +/*! + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter, + MongooseError = require('./error'), + MixedSchema = require('./schema/mixed'), + Schema = require('./schema'), + ObjectExpectedError = require('./error/objectExpected'), + StrictModeError = require('./error/strict'), + ValidatorError = require('./schematype').ValidatorError, + utils = require('./utils'), + clone = utils.clone, + isMongooseObject = utils.isMongooseObject, + inspect = require('util').inspect, + ValidationError = MongooseError.ValidationError, + InternalCache = require('./internal'), + deepEqual = utils.deepEqual, + hooks = require('hooks-fixed'), + PromiseProvider = require('./promise_provider'), + DocumentArray, + MongooseArray, + Embedded; + +/** + * Document constructor. + * + * @param {Object} obj the values to set + * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data + * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose. + * @event `save`: Emitted when the document is successfully saved + * @api private + */ + +function Document(obj, fields, skipId) { + this.$__ = new InternalCache; + this.$__.emitter = new EventEmitter(); + this.isNew = true; + this.errors = undefined; + + var schema = this.schema; + + if (typeof fields === 'boolean') { + this.$__.strictMode = fields; + fields = undefined; + } else { + this.$__.strictMode = schema.options && schema.options.strict; + this.$__.selected = fields; + } + + var required = schema.requiredPaths(true); + for (var i = 0; i < required.length; ++i) { + this.$__.activePaths.require(required[i]); + } + + this.$__.emitter.setMaxListeners(0); + this._doc = this.$__buildDoc(obj, fields, skipId); + + if (obj) { + this.set(obj, undefined, true); + } + + if (!schema.options.strict && obj) { + var _this = this, + keys = Object.keys(this._doc); + + keys.forEach(function(key) { + if (!(key in schema.tree)) { + defineKey(key, null, _this); + } + }); + } + + this.$__registerHooksFromSchema(); +} + +/*! + * Document exposes the NodeJS event emitter API, so you can use + * `on`, `once`, etc. + */ +utils.each( + ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', + 'removeAllListeners', 'addListener'], + function(emitterFn) { + Document.prototype[emitterFn] = function() { + return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); + }; + }); + +Document.prototype.constructor = Document; + +/** + * The documents schema. + * + * @api public + * @property schema + */ + +Document.prototype.schema; + +/** + * Boolean flag specifying if the document is new. + * + * @api public + * @property isNew + */ + +Document.prototype.isNew; + +/** + * The string version of this documents _id. + * + * ####Note: + * + * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. + * + * new Schema({ name: String }, { id: false }); + * + * @api public + * @see Schema options /docs/guide.html#options + * @property id + */ + +Document.prototype.id; + +/** + * Hash containing current validation errors. + * + * @api public + * @property errors + */ + +Document.prototype.errors; + +/** + * Builds the default doc structure + * + * @param {Object} obj + * @param {Object} [fields] + * @param {Boolean} [skipId] + * @return {Object} + * @api private + * @method $__buildDoc + * @memberOf Document + */ + +Document.prototype.$__buildDoc = function(obj, fields, skipId) { + var doc = {}; + var exclude = null; + var keys; + var ki; + var _this = this; + + // determine if this doc is a result of a query with + // excluded fields + if (fields && utils.getFunctionName(fields.constructor) === 'Object') { + keys = Object.keys(fields); + ki = keys.length; + + if (ki === 1 && keys[0] === '_id') { + exclude = !!fields[keys[ki]]; + } else { + while (ki--) { + if (keys[ki] !== '_id' && + (!fields[keys[ki]] || typeof fields[keys[ki]] !== 'object')) { + exclude = !fields[keys[ki]]; + break; + } + } + } + } + + var paths = Object.keys(this.schema.paths), + plen = paths.length, + ii = 0; + + for (; ii < plen; ++ii) { + var p = paths[ii]; + + if (p === '_id') { + if (skipId) { + continue; + } + if (obj && '_id' in obj) { + continue; + } + } + + var type = this.schema.paths[p]; + var path = p.split('.'); + var len = path.length; + var last = len - 1; + var curPath = ''; + var doc_ = doc; + var i = 0; + var included = false; + + for (; i < len; ++i) { + var piece = path[i], + def; + + curPath += piece; + + // support excluding intermediary levels + if (exclude === true) { + if (curPath in fields) { + break; + } + } else if (fields && curPath in fields) { + included = true; + } + + if (i === last) { + if (fields && exclude !== null) { + if (exclude === true) { + // apply defaults to all non-excluded fields + if (p in fields) { + continue; + } + + def = type.getDefault(_this, true); + if (typeof def !== 'undefined') { + doc_[piece] = def; + _this.$__.activePaths.default(p); + } + } else if (included) { + // selected field + def = type.getDefault(_this, true); + if (typeof def !== 'undefined') { + doc_[piece] = def; + _this.$__.activePaths.default(p); + } + } + } else { + def = type.getDefault(_this, true); + if (typeof def !== 'undefined') { + doc_[piece] = def; + _this.$__.activePaths.default(p); + } + } + } else { + doc_ = doc_[piece] || (doc_[piece] = {}); + curPath += '.'; + } + } + } + + return doc; +}; + +/** + * Initializes the document without setters or marking anything modified. + * + * Called internally after a document is returned from mongodb. + * + * @param {Object} doc document returned by mongo + * @param {Function} fn callback + * @api public + */ + +Document.prototype.init = function(doc, opts, fn) { + // do not prefix this method with $__ since its + // used by public hooks + + if (typeof opts === 'function') { + fn = opts; + opts = null; + } + + this.isNew = false; + + // handle docs with populated paths + // If doc._id is not null or undefined + if (doc._id !== null && doc._id !== undefined && + opts && opts.populated && opts.populated.length) { + var id = String(doc._id); + for (var i = 0; i < opts.populated.length; ++i) { + var item = opts.populated[i]; + this.populated(item.path, item._docs[id], item); + } + } + + init(this, doc, this._doc); + this.$__storeShard(); + + this.emit('init', this); + if (fn) { + fn(null); + } + return this; +}; + +/*! + * Init helper. + * + * @param {Object} self document instance + * @param {Object} obj raw mongodb doc + * @param {Object} doc object we are initializing + * @api private + */ + +function init(self, obj, doc, prefix) { + prefix = prefix || ''; + + var keys = Object.keys(obj), + len = keys.length, + schema, + path, + i; + + while (len--) { + i = keys[len]; + path = prefix + i; + schema = self.schema.path(path); + + if (!schema && utils.isObject(obj[i]) && + (!obj[i].constructor || utils.getFunctionName(obj[i].constructor) === 'Object')) { + // assume nested object + if (!doc[i]) { + doc[i] = {}; + } + init(self, obj[i], doc[i], path + '.'); + } else { + if (obj[i] === null) { + doc[i] = null; + } else if (obj[i] !== undefined) { + if (schema) { + try { + doc[i] = schema.cast(obj[i], self, true); + } catch (e) { + self.invalidate(e.path, new ValidatorError({ + path: e.path, + message: e.message, + type: 'cast', + value: e.value + })); + } + } else { + doc[i] = obj[i]; + } + } + // mark as hydrated + if (!self.isModified(path)) { + self.$__.activePaths.init(path); + } + } + } +} + +/** + * Stores the current values of the shard keys. + * + * ####Note: + * + * _Shard key values do not / are not allowed to change._ + * + * @api private + * @method $__storeShard + * @memberOf Document + */ + +Document.prototype.$__storeShard = function() { + // backwards compat + var key = this.schema.options.shardKey || this.schema.options.shardkey; + if (!(key && utils.getFunctionName(key.constructor) === 'Object')) { + return; + } + + var orig = this.$__.shardval = {}, + paths = Object.keys(key), + len = paths.length, + val; + + for (var i = 0; i < len; ++i) { + val = this.getValue(paths[i]); + if (isMongooseObject(val)) { + orig[paths[i]] = val.toObject({depopulate: true}); + } else if (val !== null && val !== undefined && val.valueOf && + // Explicitly don't take value of dates + (!val.constructor || utils.getFunctionName(val.constructor) !== 'Date')) { + orig[paths[i]] = val.valueOf(); + } else { + orig[paths[i]] = val; + } + } +}; + +/*! + * Set up middleware support + */ + +for (var k in hooks) { + Document.prototype[k] = Document[k] = hooks[k]; +} + +/** + * Sends an update command with this document `_id` as the query selector. + * + * ####Example: + * + * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); + * + * ####Valid options: + * + * - same as in [Model.update](#model_Model.update) + * + * @see Model.update #model_Model.update + * @param {Object} doc + * @param {Object} options + * @param {Function} callback + * @return {Query} + * @api public + */ + +Document.prototype.update = function update() { + var args = utils.args(arguments); + args.unshift({_id: this._id}); + return this.constructor.update.apply(this.constructor, args); +}; + +/** + * Sets the value of a path, or many paths. + * + * ####Example: + * + * // path, value + * doc.set(path, value) + * + * // object + * doc.set({ + * path : value + * , path2 : { + * path : value + * } + * }) + * + * // on-the-fly cast to number + * doc.set(path, value, Number) + * + * // on-the-fly cast to string + * doc.set(path, value, String) + * + * // changing strict mode behavior + * doc.set(path, value, { strict: false }); + * + * @param {String|Object} path path or object of key/vals to set + * @param {Any} val the value to set + * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes + * @param {Object} [options] optionally specify options that modify the behavior of the set + * @api public + */ + +Document.prototype.set = function(path, val, type, options) { + if (type && utils.getFunctionName(type.constructor) === 'Object') { + options = type; + type = undefined; + } + + var merge = options && options.merge, + adhoc = type && type !== true, + constructing = type === true, + adhocs; + + var strict = options && 'strict' in options + ? options.strict + : this.$__.strictMode; + + if (adhoc) { + adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); + adhocs[path] = Schema.interpretAsType(path, type, this.schema.options); + } + + if (typeof path !== 'string') { + // new Document({ key: val }) + + if (path === null || path === void 0) { + var _ = path; + path = val; + val = _; + } else { + var prefix = val + ? val + '.' + : ''; + + if (path instanceof Document) { + if (path.$__isNested) { + path = path.toObject(); + } else { + path = path._doc; + } + } + + var keys = Object.keys(path), + i = keys.length, + pathtype, + key; + + while (i--) { + key = keys[i]; + var pathName = prefix + key; + pathtype = this.schema.pathType(pathName); + + if (path[key] !== null + && path[key] !== undefined + // need to know if plain object - no Buffer, ObjectId, ref, etc + && utils.isObject(path[key]) + && (!path[key].constructor || utils.getFunctionName(path[key].constructor) === 'Object') + && pathtype !== 'virtual' + && pathtype !== 'real' + && !(this.$__path(pathName) instanceof MixedSchema) + && !(this.schema.paths[pathName] && + this.schema.paths[pathName].options && + this.schema.paths[pathName].options.ref)) { + this.set(path[key], prefix + key, constructing); + } else if (strict) { + if (pathtype === 'real' || pathtype === 'virtual') { + // Check for setting single embedded schema to document (gh-3535) + if (this.schema.paths[pathName] && + this.schema.paths[pathName].$isSingleNested && + path[key] instanceof Document) { + path[key] = path[key].toObject({virtuals: false}); + } + this.set(prefix + key, path[key], constructing); + } else if (pathtype === 'nested' && path[key] instanceof Document) { + this.set(prefix + key, + path[key].toObject({virtuals: false}), constructing); + } else if (strict === 'throw') { + if (pathtype === 'nested') { + throw new ObjectExpectedError(key, path[key]); + } else { + throw new StrictModeError(key); + } + } + } else if (undefined !== path[key]) { + this.set(prefix + key, path[key], constructing); + } + } + + return this; + } + } + + // ensure _strict is honored for obj props + // docschema = new Schema({ path: { nest: 'string' }}) + // doc.set('path', obj); + var pathType = this.schema.pathType(path); + if (pathType === 'nested' && val) { + if (utils.isObject(val) && + (!val.constructor || utils.getFunctionName(val.constructor) === 'Object')) { + if (!merge) { + this.setValue(path, null); + } + this.set(val, path, constructing); + return this; + } + this.invalidate(path, new MongooseError.CastError('Object', val, path)); + return this; + } + + var schema; + var parts = path.split('.'); + + if (pathType === 'adhocOrUndefined' && strict) { + // check for roots that are Mixed types + var mixed; + + for (i = 0; i < parts.length; ++i) { + var subpath = parts.slice(0, i + 1).join('.'); + schema = this.schema.path(subpath); + if (schema instanceof MixedSchema) { + // allow changes to sub paths of mixed types + mixed = true; + break; + } + } + + if (!mixed) { + if (strict === 'throw') { + throw new StrictModeError(path); + } + return this; + } + } else if (pathType === 'virtual') { + schema = this.schema.virtualpath(path); + schema.applySetters(val, this); + return this; + } else { + schema = this.$__path(path); + } + + var pathToMark; + + // When using the $set operator the path to the field must already exist. + // Else mongodb throws: "LEFT_SUBFIELD only supports Object" + + if (parts.length <= 1) { + pathToMark = path; + } else { + for (i = 0; i < parts.length; ++i) { + subpath = parts.slice(0, i + 1).join('.'); + if (this.isDirectModified(subpath) // earlier prefixes that are already + // marked as dirty have precedence + || this.get(subpath) === null) { + pathToMark = subpath; + break; + } + } + + if (!pathToMark) { + pathToMark = path; + } + } + + // if this doc is being constructed we should not trigger getters + var priorVal = constructing + ? undefined + : this.getValue(path); + + if (!schema) { + this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); + return this; + } + + var shouldSet = true; + try { + // If the user is trying to set a ref path to a document with + // the correct model name, treat it as populated + var didPopulate = false; + if (schema.options && + schema.options.ref && + val instanceof Document && + schema.options.ref === val.constructor.modelName) { + if (this.ownerDocument) { + this.ownerDocument().populated(this.$__fullPath(path), + val._id, {model: val.constructor}); + } else { + this.populated(path, val._id, {model: val.constructor}); + } + didPopulate = true; + } + + if (schema.options && + Array.isArray(schema.options.type) && + schema.options.type.length && + schema.options.type[0].ref && + Array.isArray(val) && + val.length > 0 && + val[0] instanceof Document && + val[0].constructor.modelName && + schema.options.type[0].ref === val[0].constructor.modelName) { + if (this.ownerDocument) { + this.ownerDocument().populated(this.$__fullPath(path), + val.map(function(v) { + return v._id; + }), + {model: val[0].constructor}); + } else { + this.populated(path, val + .map(function(v) { + return v._id; + }), + {model: val[0].constructor}); + } + didPopulate = true; + } + val = schema.applySetters(val, this, false, priorVal); + + if (!didPopulate && this.$__.populated) { + delete this.$__.populated[path]; + } + + this.$markValid(path); + } catch (e) { + var reason; + if (!(e instanceof MongooseError.CastError)) { + reason = e; + } + this.invalidate(path, + new MongooseError.CastError(schema.instance, val, path, reason)); + shouldSet = false; + } + + if (shouldSet) { + this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); + } + + return this; +}; + +/** + * Determine if we should mark this change as modified. + * + * @return {Boolean} + * @api private + * @method $__shouldModify + * @memberOf Document + */ + +Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) { + if (this.isNew) { + return true; + } + + if (undefined === val && !this.isSelected(path)) { + // when a path is not selected in a query, its initial + // value will be undefined. + return true; + } + + if (undefined === val && path in this.$__.activePaths.states.default) { + // we're just unsetting the default value which was never saved + return false; + } + + if (!deepEqual(val, priorVal || this.get(path))) { + return true; + } + + if (!constructing && + val !== null && + val !== undefined && + path in this.$__.activePaths.states.default && + deepEqual(val, schema.getDefault(this, constructing))) { + // a path with a default was $unset on the server + // and the user is setting it to the same value again + return true; + } + return false; +}; + +/** + * Handles the actual setting of the value and marking the path modified if appropriate. + * + * @api private + * @method $__set + * @memberOf Document + */ + +Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) { + Embedded = Embedded || require('./types/embedded'); + + var shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts, + schema, val, priorVal); + var _this = this; + + if (shouldModify) { + this.markModified(pathToMark, val); + + // handle directly setting arrays (gh-1126) + MongooseArray || (MongooseArray = require('./types/array')); + if (val && val.isMongooseArray) { + val._registerAtomic('$set', val); + + // Small hack for gh-1638: if we're overwriting the entire array, ignore + // paths that were modified before the array overwrite + this.$__.activePaths.forEach(function(modifiedPath) { + if (modifiedPath.indexOf(path + '.') === 0) { + _this.$__.activePaths.ignore(modifiedPath); + } + }); + } + } + + var obj = this._doc, + i = 0, + l = parts.length; + + for (; i < l; i++) { + var next = i + 1, + last = next === l; + + if (last) { + obj[parts[i]] = val; + } else { + if (obj[parts[i]] && utils.getFunctionName(obj[parts[i]].constructor) === 'Object') { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { + obj = obj[parts[i]]; + } else { + obj = obj[parts[i]] = {}; + } + } + } +}; + +/** + * Gets a raw value from a path (no getters) + * + * @param {String} path + * @api private + */ + +Document.prototype.getValue = function(path) { + return utils.getValue(path, this._doc); +}; + +/** + * Sets a raw value for a path (no casting, setters, transformations) + * + * @param {String} path + * @param {Object} value + * @api private + */ + +Document.prototype.setValue = function(path, val) { + utils.setValue(path, val, this._doc); + return this; +}; + +/** + * Returns the value of a path. + * + * ####Example + * + * // path + * doc.get('age') // 47 + * + * // dynamic casting to a string + * doc.get('age', String) // "47" + * + * @param {String} path + * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes + * @api public + */ + +Document.prototype.get = function(path, type) { + var adhoc; + if (type) { + adhoc = Schema.interpretAsType(path, type, this.schema.options); + } + + var schema = this.$__path(path) || this.schema.virtualpath(path), + pieces = path.split('.'), + obj = this._doc; + + for (var i = 0, l = pieces.length; i < l; i++) { + obj = obj === null || obj === void 0 + ? undefined + : obj[pieces[i]]; + } + + if (adhoc) { + obj = adhoc.cast(obj); + } + + // Check if this path is populated - don't apply getters if it is, + // because otherwise its a nested object. See gh-3357 + if (schema && !this.populated(path)) { + obj = schema.applyGetters(obj, this); + } + + return obj; +}; + +/** + * Returns the schematype for the given `path`. + * + * @param {String} path + * @api private + * @method $__path + * @memberOf Document + */ + +Document.prototype.$__path = function(path) { + var adhocs = this.$__.adhocPaths, + adhocType = adhocs && adhocs[path]; + + if (adhocType) { + return adhocType; + } + return this.schema.path(path); +}; + +/** + * Marks the path as having pending changes to write to the db. + * + * _Very helpful when using [Mixed](./schematypes.html#mixed) types._ + * + * ####Example: + * + * doc.mixed.type = 'changed'; + * doc.markModified('mixed.type'); + * doc.save() // changes to mixed.type are now persisted + * + * @param {String} path the path to mark modified + * @api public + */ + +Document.prototype.markModified = function(path) { + this.$__.activePaths.modify(path); +}; + +/** + * Returns the list of paths that have been modified. + * + * @return {Array} + * @api public + */ + +Document.prototype.modifiedPaths = function() { + var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); + + return directModifiedPaths.reduce(function(list, path) { + var parts = path.split('.'); + return list.concat(parts.reduce(function(chains, part, i) { + return chains.concat(parts.slice(0, i).concat(part).join('.')); + }, [])); + }, []); +}; + +/** + * Returns true if this document was modified, else false. + * + * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. + * + * ####Example + * + * doc.set('documents.0.title', 'changed'); + * doc.isModified() // true + * doc.isModified('documents') // true + * doc.isModified('documents.0.title') // true + * doc.isDirectModified('documents') // false + * + * @param {String} [path] optional + * @return {Boolean} + * @api public + */ + +Document.prototype.isModified = function(path) { + return path + ? !!~this.modifiedPaths().indexOf(path) + : this.$__.activePaths.some('modify'); +}; + +/** + * Checks if a path is set to its default. + * + * ####Example + * + * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} }); + * var m = new MyModel(); + * m.$isDefault('name'); // true + * + * @param {String} [path] + * @return {Boolean} + * @method $isDefault + * @api public + */ + +Document.prototype.$isDefault = function(path) { + return (path in this.$__.activePaths.states.default); +}; + +/** + * Returns true if `path` was directly set and modified, else false. + * + * ####Example + * + * doc.set('documents.0.title', 'changed'); + * doc.isDirectModified('documents.0.title') // true + * doc.isDirectModified('documents') // false + * + * @param {String} path + * @return {Boolean} + * @api public + */ + +Document.prototype.isDirectModified = function(path) { + return (path in this.$__.activePaths.states.modify); +}; + +/** + * Checks if `path` was initialized. + * + * @param {String} path + * @return {Boolean} + * @api public + */ + +Document.prototype.isInit = function(path) { + return (path in this.$__.activePaths.states.init); +}; + +/** + * Checks if `path` was selected in the source query which initialized this document. + * + * ####Example + * + * Thing.findOne().select('name').exec(function (err, doc) { + * doc.isSelected('name') // true + * doc.isSelected('age') // false + * }) + * + * @param {String} path + * @return {Boolean} + * @api public + */ + +Document.prototype.isSelected = function isSelected(path) { + if (this.$__.selected) { + if (path === '_id') { + return this.$__.selected._id !== 0; + } + + var paths = Object.keys(this.$__.selected), + i = paths.length, + inclusive = false, + cur; + + if (i === 1 && paths[0] === '_id') { + // only _id was selected. + return this.$__.selected._id === 0; + } + + while (i--) { + cur = paths[i]; + if (cur === '_id') { + continue; + } + inclusive = !!this.$__.selected[cur]; + break; + } + + if (path in this.$__.selected) { + return inclusive; + } + + i = paths.length; + var pathDot = path + '.'; + + while (i--) { + cur = paths[i]; + if (cur === '_id') { + continue; + } + + if (cur.indexOf(pathDot) === 0) { + return inclusive; + } + + if (pathDot.indexOf(cur + '.') === 0) { + return inclusive; + } + } + + return !inclusive; + } + + return true; +}; + +/** + * Executes registered validation rules for this document. + * + * ####Note: + * + * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. + * + * ####Example: + * + * doc.validate(function (err) { + * if (err) handleError(err); + * else // validation passed + * }); + * + * @param {Object} optional options internal options + * @param {Function} optional callback called after validation completes, passing an error if one occurred + * @return {Promise} Promise + * @api public + */ + +Document.prototype.validate = function(options, callback) { + var _this = this; + var Promise = PromiseProvider.get(); + if (typeof options === 'function') { + callback = options; + options = null; + } + + if (options && options.__noPromise) { + this.$__validate(callback); + return; + } + + return new Promise.ES6(function(resolve, reject) { + _this.$__validate(function(error) { + callback && callback(error); + if (error) { + reject(error); + return; + } + resolve(); + }); + }); +}; + +/*! + * ignore + */ + +Document.prototype.$__validate = function(callback) { + var _this = this; + var _complete = function() { + var err = _this.$__.validationError; + _this.$__.validationError = undefined; + _this.emit('validate', _this); + if (err) { + for (var key in err.errors) { + // Make sure cast errors persist + if (!_this.__parent && err.errors[key] instanceof MongooseError.CastError) { + _this.invalidate(key, err.errors[key]); + } + } + + return err; + } + }; + + // only validate required fields when necessary + var paths = Object.keys(this.$__.activePaths.states.require).filter(function(path) { + if (!_this.isSelected(path) && !_this.isModified(path)) { + return false; + } + return true; + }); + + paths = paths.concat(Object.keys(this.$__.activePaths.states.init)); + paths = paths.concat(Object.keys(this.$__.activePaths.states.modify)); + paths = paths.concat(Object.keys(this.$__.activePaths.states.default)); + + if (paths.length === 0) { + process.nextTick(function() { + var err = _complete(); + if (err) { + callback(err); + return; + } + callback(); + }); + } + + var validating = {}, + total = 0; + + // gh-661: if a whole array is modified, make sure to run validation on all + // the children as well + for (var i = 0; i < paths.length; ++i) { + var path = paths[i]; + var val = _this.getValue(path); + if (val && val.isMongooseArray && !Buffer.isBuffer(val) && !val.isMongooseDocumentArray) { + var numElements = val.length; + for (var j = 0; j < numElements; ++j) { + paths.push(path + '.' + j); + } + } + } + + var complete = function() { + var err = _complete(); + if (err) { + callback(err); + return; + } + callback(); + }; + + var validatePath = function(path) { + if (validating[path]) { + return; + } + + validating[path] = true; + total++; + + process.nextTick(function() { + var p = _this.schema.path(path); + if (!p) { + return --total || complete(); + } + + // If user marked as invalid or there was a cast error, don't validate + if (!_this.$isValid(path)) { + --total || complete(); + return; + } + + var val = _this.getValue(path); + p.doValidate(val, function(err) { + if (err) { + _this.invalidate(path, err, undefined, true); + } + --total || complete(); + }, _this); + }); + }; + + paths.forEach(validatePath); +}; + +/** + * Executes registered validation rules (skipping asynchronous validators) for this document. + * + * ####Note: + * + * This method is useful if you need synchronous validation. + * + * ####Example: + * + * var err = doc.validateSync(); + * if ( err ){ + * handleError( err ); + * } else { + * // validation passed + * } + * + * @param {Array|string} pathsToValidate only validate the given paths + * @return {MongooseError|undefined} MongooseError if there are errors during validation, or undefined if there is no error. + * @api public + */ + +Document.prototype.validateSync = function(pathsToValidate) { + var _this = this; + + if (typeof pathsToValidate === 'string') { + pathsToValidate = pathsToValidate.split(' '); + } + + // only validate required fields when necessary + var paths = Object.keys(this.$__.activePaths.states.require).filter(function(path) { + if (!_this.isSelected(path) && !_this.isModified(path)) { + return false; + } + return true; + }); + + paths = paths.concat(Object.keys(this.$__.activePaths.states.init)); + paths = paths.concat(Object.keys(this.$__.activePaths.states.modify)); + paths = paths.concat(Object.keys(this.$__.activePaths.states.default)); + + if (pathsToValidate && pathsToValidate.length) { + var tmp = []; + for (var i = 0; i < paths.length; ++i) { + if (pathsToValidate.indexOf(paths[i]) !== -1) { + tmp.push(paths[i]); + } + } + paths = tmp; + } + + var validating = {}; + + paths.forEach(function(path) { + if (validating[path]) { + return; + } + + validating[path] = true; + + var p = _this.schema.path(path); + if (!p) { + return; + } + if (!_this.$isValid(path)) { + return; + } + + var val = _this.getValue(path); + var err = p.doValidateSync(val, _this); + if (err) { + _this.invalidate(path, err, undefined, true); + } + }); + + var err = _this.$__.validationError; + _this.$__.validationError = undefined; + _this.emit('validate', _this); + + if (err) { + for (var key in err.errors) { + // Make sure cast errors persist + if (err.errors[key] instanceof MongooseError.CastError) { + _this.invalidate(key, err.errors[key]); + } + } + } + + return err; +}; + +/** + * Marks a path as invalid, causing validation to fail. + * + * The `errorMsg` argument will become the message of the `ValidationError`. + * + * The `value` argument (if passed) will be available through the `ValidationError.value` property. + * + * doc.invalidate('size', 'must be less than 20', 14); + + * doc.validate(function (err) { + * console.log(err) + * // prints + * { message: 'Validation failed', + * name: 'ValidationError', + * errors: + * { size: + * { message: 'must be less than 20', + * name: 'ValidatorError', + * path: 'size', + * type: 'user defined', + * value: 14 } } } + * }) + * + * @param {String} path the field to invalidate + * @param {String|Error} errorMsg the error which states the reason `path` was invalid + * @param {Object|String|Number|any} value optional invalid value + * @api public + */ + +Document.prototype.invalidate = function(path, err, val) { + if (!this.$__.validationError) { + this.$__.validationError = new ValidationError(this); + } + + if (this.$__.validationError.errors[path]) { + return; + } + + if (!err || typeof err === 'string') { + err = new ValidatorError({ + path: path, + message: err, + type: 'user defined', + value: val + }); + } + + if (this.$__.validationError === err) { + return; + } + + this.$__.validationError.errors[path] = err; +}; + +/** + * Marks a path as valid, removing existing validation errors. + * + * @param {String} path the field to mark as valid + * @api private + * @method $markValid + * @receiver Document + */ + +Document.prototype.$markValid = function(path) { + if (!this.$__.validationError || !this.$__.validationError.errors[path]) { + return; + } + + delete this.$__.validationError.errors[path]; + if (Object.keys(this.$__.validationError.errors).length === 0) { + this.$__.validationError = null; + } +}; + +/** + * Checks if a path is invalid + * + * @param {String} path the field to check + * @method $isValid + * @api private + * @receiver Document + */ + +Document.prototype.$isValid = function(path) { + return !this.$__.validationError || !this.$__.validationError.errors[path]; +}; + +/** + * Resets the internal modified state of this document. + * + * @api private + * @return {Document} + * @method $__reset + * @memberOf Document + */ + +Document.prototype.$__reset = function reset() { + var _this = this; + DocumentArray || (DocumentArray = require('./types/documentarray')); + + this.$__.activePaths + .map('init', 'modify', function(i) { + return _this.getValue(i); + }) + .filter(function(val) { + return val && val instanceof Array && val.isMongooseDocumentArray && val.length; + }) + .forEach(function(array) { + var i = array.length; + while (i--) { + var doc = array[i]; + if (!doc) { + continue; + } + doc.$__reset(); + } + }); + + // clear atomics + this.$__dirty().forEach(function(dirt) { + var type = dirt.value; + if (type && type._atomics) { + type._atomics = {}; + } + }); + + // Clear 'dirty' cache + this.$__.activePaths.clear('modify'); + this.$__.activePaths.clear('default'); + this.$__.validationError = undefined; + this.errors = undefined; + _this = this; + this.schema.requiredPaths().forEach(function(path) { + _this.$__.activePaths.require(path); + }); + + return this; +}; + +/** + * Returns this documents dirty paths / vals. + * + * @api private + * @method $__dirty + * @memberOf Document + */ + +Document.prototype.$__dirty = function() { + var _this = this; + + var all = this.$__.activePaths.map('modify', function(path) { + return { + path: path, + value: _this.getValue(path), + schema: _this.$__path(path) + }; + }); + + // gh-2558: if we had to set a default and the value is not undefined, + // we have to save as well + all = all.concat(this.$__.activePaths.map('default', function(path) { + if (path === '_id' || !_this.getValue(path)) { + return; + } + return { + path: path, + value: _this.getValue(path), + schema: _this.$__path(path) + }; + })); + + // Sort dirty paths in a flat hierarchy. + all.sort(function(a, b) { + return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0)); + }); + + // Ignore "foo.a" if "foo" is dirty already. + var minimal = [], + lastPath, + top; + + all.forEach(function(item) { + if (!item) { + return; + } + if (item.path.indexOf(lastPath) !== 0) { + lastPath = item.path + '.'; + minimal.push(item); + top = item; + } else { + // special case for top level MongooseArrays + if (top.value && top.value._atomics && top.value.hasAtomics()) { + // the `top` array itself and a sub path of `top` are being modified. + // the only way to honor all of both modifications is through a $set + // of entire array. + top.value._atomics = {}; + top.value._atomics.$set = top.value; + } + } + }); + + top = lastPath = null; + return minimal; +}; + +/*! + * Compiles schemas. + */ + +function compile(tree, proto, prefix, options) { + var keys = Object.keys(tree), + i = keys.length, + limb, + key; + + while (i--) { + key = keys[i]; + limb = tree[key]; + + defineKey(key, + ((utils.getFunctionName(limb.constructor) === 'Object' + && Object.keys(limb).length) + && (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type)) + ? limb + : null) + , proto + , prefix + , keys + , options); + } +} + +// gets descriptors for all properties of `object` +// makes all properties non-enumerable to match previous behavior to #2211 +function getOwnPropertyDescriptors(object) { + var result = {}; + + Object.getOwnPropertyNames(object).forEach(function(key) { + result[key] = Object.getOwnPropertyDescriptor(object, key); + result[key].enumerable = true; + }); + + return result; +} + +/*! + * Defines the accessor named prop on the incoming prototype. + */ + +function defineKey(prop, subprops, prototype, prefix, keys, options) { + var path = (prefix ? prefix + '.' : '') + prop; + prefix = prefix || ''; + + if (subprops) { + Object.defineProperty(prototype, prop, { + enumerable: true, + configurable: true, + get: function() { + var _this = this; + if (!this.$__.getters) { + this.$__.getters = {}; + } + + if (!this.$__.getters[path]) { + var nested = Object.create(Object.getPrototypeOf(this), getOwnPropertyDescriptors(this)); + + // save scope for nested getters/setters + if (!prefix) { + nested.$__.scope = this; + } + + // shadow inherited getters from sub-objects so + // thing.nested.nested.nested... doesn't occur (gh-366) + var i = 0, + len = keys.length; + + for (; i < len; ++i) { + // over-write the parents getter without triggering it + Object.defineProperty(nested, keys[i], { + enumerable: false, // It doesn't show up. + writable: true, // We can set it later. + configurable: true, // We can Object.defineProperty again. + value: undefined // It shadows its parent. + }); + } + + Object.defineProperty(nested, 'toObject', { + enumerable: true, + configurable: true, + writable: false, + value: function() { + return _this.get(path); + } + }); + + Object.defineProperty(nested, 'toJSON', { + enumerable: true, + configurable: true, + writable: false, + value: function() { + return _this.get(path); + } + }); + + Object.defineProperty(nested, '$__isNested', { + enumerable: true, + configurable: true, + writable: false, + value: true + }); + + compile(subprops, nested, path, options); + this.$__.getters[path] = nested; + } + + return this.$__.getters[path]; + }, + set: function(v) { + if (v instanceof Document) { + v = v.toObject(); + } + return (this.$__.scope || this).set(path, v); + } + }); + } else { + Object.defineProperty(prototype, prop, { + enumerable: true, + configurable: true, + get: function() { + return this.get.call(this.$__.scope || this, path); + }, + set: function(v) { + return this.set.call(this.$__.scope || this, path, v); + } + }); + } +} + +/** + * Assigns/compiles `schema` into this documents prototype. + * + * @param {Schema} schema + * @api private + * @method $__setSchema + * @memberOf Document + */ + +Document.prototype.$__setSchema = function(schema) { + compile(schema.tree, this, undefined, schema.options); + this.schema = schema; +}; + + +/** + * Get active path that were changed and are arrays + * + * @api private + * @method $__getArrayPathsToValidate + * @memberOf Document + */ + +Document.prototype.$__getArrayPathsToValidate = function() { + DocumentArray || (DocumentArray = require('./types/documentarray')); + + // validate all document arrays. + return this.$__.activePaths + .map('init', 'modify', function(i) { + return this.getValue(i); + }.bind(this)) + .filter(function(val) { + return val && val instanceof Array && val.isMongooseDocumentArray && val.length; + }).reduce(function(seed, array) { + return seed.concat(array); + }, []) + .filter(function(doc) { + return doc; + }); +}; + + +/** + * Get all subdocs (by bfs) + * + * @api private + * @method $__getAllSubdocs + * @memberOf Document + */ + +Document.prototype.$__getAllSubdocs = function() { + DocumentArray || (DocumentArray = require('./types/documentarray')); + Embedded = Embedded || require('./types/embedded'); + + function docReducer(seed, path) { + var val = this[path]; + + if (val instanceof Embedded) { + seed.push(val); + } + if (val && val.$isSingleNested) { + seed = Object.keys(val._doc).reduce(docReducer.bind(val._doc), seed); + seed.push(val); + } + if (val && val.isMongooseDocumentArray) { + val.forEach(function _docReduce(doc) { + if (!doc || !doc._doc) { + return; + } + if (doc instanceof Embedded) { + seed.push(doc); + } + seed = Object.keys(doc._doc).reduce(docReducer.bind(doc._doc), seed); + }); + } else if (val instanceof Document && val.$__isNested) { + val = val.toObject(); + if (val) { + seed = Object.keys(val).reduce(docReducer.bind(val), seed); + } + } + return seed; + } + + var subDocs = Object.keys(this._doc).reduce(docReducer.bind(this), []); + + return subDocs; +}; + +/** + * Executes methods queued from the Schema definition + * + * @api private + * @method $__registerHooksFromSchema + * @memberOf Document + */ + +Document.prototype.$__registerHooksFromSchema = function() { + Embedded = Embedded || require('./types/embedded'); + var Promise = PromiseProvider.get(); + + var _this = this; + var q = _this.schema && _this.schema.callQueue; + if (!q.length) { + return _this; + } + + // we are only interested in 'pre' hooks, and group by point-cut + var toWrap = q.reduce(function(seed, pair) { + if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { + _this[pair[0]].apply(_this, pair[1]); + return seed; + } + var args = [].slice.call(pair[1]); + var pointCut = pair[0] === 'on' ? 'post' : args[0]; + if (!(pointCut in seed)) { + seed[pointCut] = {post: [], pre: []}; + } + if (pair[0] === 'post') { + seed[pointCut].post.push(args); + } else if (pair[0] === 'on') { + seed[pointCut].push(args); + } else { + seed[pointCut].pre.push(args); + } + return seed; + }, {post: []}); + + // 'post' hooks are simpler + toWrap.post.forEach(function(args) { + _this.on.apply(_this, args); + }); + delete toWrap.post; + + // 'init' should be synchronous on subdocuments + if (toWrap.init && _this instanceof Embedded) { + if (toWrap.init.pre) { + toWrap.init.pre.forEach(function(args) { + _this.pre.apply(_this, args); + }); + } + if (toWrap.init.post) { + toWrap.init.post.forEach(function(args) { + _this.post.apply(_this, args); + }); + } + delete toWrap.init; + } else if (toWrap.set) { + // Set hooks also need to be sync re: gh-3479 + if (toWrap.set.pre) { + toWrap.set.pre.forEach(function(args) { + _this.pre.apply(_this, args); + }); + } + if (toWrap.set.post) { + toWrap.set.post.forEach(function(args) { + _this.post.apply(_this, args); + }); + } + delete toWrap.set; + } + + Object.keys(toWrap).forEach(function(pointCut) { + // this is so we can wrap everything into a promise; + var newName = ('$__original_' + pointCut); + if (!_this[pointCut]) { + return; + } + _this[newName] = _this[pointCut]; + _this[pointCut] = function wrappedPointCut() { + var args = [].slice.call(arguments); + var lastArg = args.pop(); + var fn; + + return new Promise.ES6(function(resolve, reject) { + if (lastArg && typeof lastArg !== 'function') { + args.push(lastArg); + } else { + fn = lastArg; + } + args.push(function(error, result) { + if (error) { + _this.$__handleReject(error); + fn && fn(error); + reject(error); + return; + } + + fn && fn.apply(null, [null].concat(Array.prototype.slice.call(arguments, 1))); + resolve(result); + }); + + _this[newName].apply(_this, args); + }); + }; + + toWrap[pointCut].pre.forEach(function(args) { + args[0] = newName; + _this.pre.apply(_this, args); + }); + toWrap[pointCut].post.forEach(function(args) { + args[0] = newName; + _this.post.apply(_this, args); + }); + }); + return _this; +}; + +Document.prototype.$__handleReject = function handleReject(err) { + // emit on the Model if listening + if (this.listeners('error').length) { + this.emit('error', err); + } else if (this.constructor.listeners && this.constructor.listeners('error').length) { + this.constructor.emit('error', err); + } else if (this.listeners && this.listeners('error').length) { + this.emit('error', err); + } +}; + +/** + * Internal helper for toObject() and toJSON() that doesn't manipulate options + * + * @api private + * @method $toObject + * @memberOf Document + */ + +Document.prototype.$toObject = function(options, json) { + var defaultOptions = {transform: true, json: json}; + + if (options && options.depopulate && !options._skipDepopulateTopLevel && this.$__.wasPopulated) { + // populated paths that we set to a document + return clone(this._id, options); + } + + // If we're calling toObject on a populated doc, we may want to skip + // depopulated on the top level + if (options && options._skipDepopulateTopLevel) { + options._skipDepopulateTopLevel = false; + } + + // When internally saving this document we always pass options, + // bypassing the custom schema options. + if (!(options && utils.getFunctionName(options.constructor) === 'Object') || + (options && options._useSchemaOptions)) { + if (json) { + options = this.schema.options.toJSON ? + clone(this.schema.options.toJSON) : + {}; + options.json = true; + options._useSchemaOptions = true; + } else { + options = this.schema.options.toObject ? + clone(this.schema.options.toObject) : + {}; + options.json = false; + options._useSchemaOptions = true; + } + } + + for (var key in defaultOptions) { + if (options[key] === undefined) { + options[key] = defaultOptions[key]; + } + } + + ('minimize' in options) || (options.minimize = this.schema.options.minimize); + + // remember the root transform function + // to save it from being overwritten by sub-transform functions + var originalTransform = options.transform; + + var ret = clone(this._doc, options) || {}; + + if (options.getters) { + applyGetters(this, ret, 'paths', options); + // applyGetters for paths will add nested empty objects; + // if minimize is set, we need to remove them. + if (options.minimize) { + ret = minimize(ret) || {}; + } + } + + if (options.virtuals || options.getters && options.virtuals !== false) { + applyGetters(this, ret, 'virtuals', options); + } + + if (options.versionKey === false && this.schema.options.versionKey) { + delete ret[this.schema.options.versionKey]; + } + + var transform = options.transform; + + // In the case where a subdocument has its own transform function, we need to + // check and see if the parent has a transform (options.transform) and if the + // child schema has a transform (this.schema.options.toObject) In this case, + // we need to adjust options.transform to be the child schema's transform and + // not the parent schema's + if (transform === true || + (this.schema.options.toObject && transform)) { + var opts = options.json ? this.schema.options.toJSON : this.schema.options.toObject; + + if (opts) { + transform = (typeof options.transform === 'function' ? options.transform : opts.transform); + } + } else { + options.transform = originalTransform; + } + + if (typeof transform === 'function') { + var xformed = transform(this, ret, options); + if (typeof xformed !== 'undefined') { + ret = xformed; + } + } + + return ret; +}; + +/** + * Converts this document into a plain javascript object, ready for storage in MongoDB. + * + * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. + * + * ####Options: + * + * - `getters` apply all getters (path and virtual getters) + * - `virtuals` apply virtual getters (can override `getters` option) + * - `minimize` remove empty objects (defaults to true) + * - `transform` a transform function to apply to the resulting document before returning + * - `depopulate` depopulate any populated paths, replacing them with their original refs (defaults to false) + * - `versionKey` whether to include the version key (defaults to true) + * - `retainKeyOrder` keep the order of object keys. If this is set to true, `Object.keys(new Doc({ a: 1, b: 2}).toObject())` will always produce `['a', 'b']` (defaults to false) + * + * ####Getters/Virtuals + * + * Example of only applying path getters + * + * doc.toObject({ getters: true, virtuals: false }) + * + * Example of only applying virtual getters + * + * doc.toObject({ virtuals: true }) + * + * Example of applying both path and virtual getters + * + * doc.toObject({ getters: true }) + * + * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. + * + * schema.set('toObject', { virtuals: true }) + * + * ####Transform + * + * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. + * + * Transform functions receive three arguments + * + * function (doc, ret, options) {} + * + * - `doc` The mongoose document which is being converted + * - `ret` The plain object representation which has been converted + * - `options` The options in use (either schema options or the options passed inline) + * + * ####Example + * + * // specify the transform schema option + * if (!schema.options.toObject) schema.options.toObject = {}; + * schema.options.toObject.transform = function (doc, ret, options) { + * // remove the _id of every document before returning the result + * delete ret._id; + * } + * + * // without the transformation in the schema + * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } + * + * // with the transformation + * doc.toObject(); // { name: 'Wreck-it Ralph' } + * + * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: + * + * if (!schema.options.toObject) schema.options.toObject = {}; + * schema.options.toObject.transform = function (doc, ret, options) { + * return { movie: ret.name } + * } + * + * // without the transformation in the schema + * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } + * + * // with the transformation + * doc.toObject(); // { movie: 'Wreck-it Ralph' } + * + * _Note: if a transform function returns `undefined`, the return value will be ignored._ + * + * Transformations may also be applied inline, overridding any transform set in the options: + * + * function xform (doc, ret, options) { + * return { inline: ret.name, custom: true } + * } + * + * // pass the transform as an inline option + * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } + * + * _Note: if you call `toObject` and pass any options, the transform declared in your schema options will __not__ be applied. To force its application pass `transform: true`_ + * + * if (!schema.options.toObject) schema.options.toObject = {}; + * schema.options.toObject.hide = '_id'; + * schema.options.toObject.transform = function (doc, ret, options) { + * if (options.hide) { + * options.hide.split(' ').forEach(function (prop) { + * delete ret[prop]; + * }); + * } + * } + * + * var doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); + * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } + * doc.toObject({ hide: 'secret _id' }); // { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } + * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } + * + * Transforms are applied _only to the document and are not applied to sub-documents_. + * + * Transforms, like all of these options, are also available for `toJSON`. + * + * See [schema options](/docs/guide.html#toObject) for some more details. + * + * _During save, no custom options are applied to the document before being sent to the database._ + * + * @param {Object} [options] + * @return {Object} js object + * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html + * @api public + */ + +Document.prototype.toObject = function(options) { + return this.$toObject(options); +}; + +/*! + * Minimizes an object, removing undefined values and empty objects + * + * @param {Object} object to minimize + * @return {Object} + */ + +function minimize(obj) { + var keys = Object.keys(obj), + i = keys.length, + hasKeys, + key, + val; + + while (i--) { + key = keys[i]; + val = obj[key]; + + if (utils.isObject(val)) { + obj[key] = minimize(val); + } + + if (undefined === obj[key]) { + delete obj[key]; + continue; + } + + hasKeys = true; + } + + return hasKeys + ? obj + : undefined; +} + +/*! + * Applies virtuals properties to `json`. + * + * @param {Document} self + * @param {Object} json + * @param {String} type either `virtuals` or `paths` + * @return {Object} `json` + */ + +function applyGetters(self, json, type, options) { + var schema = self.schema, + paths = Object.keys(schema[type]), + i = paths.length, + path; + + while (i--) { + path = paths[i]; + + var parts = path.split('.'), + plen = parts.length, + last = plen - 1, + branch = json, + part; + + for (var ii = 0; ii < plen; ++ii) { + part = parts[ii]; + if (ii === last) { + branch[part] = clone(self.get(path), options); + } else { + branch = branch[part] || (branch[part] = {}); + } + } + } + + return json; +} + +/** + * The return value of this method is used in calls to JSON.stringify(doc). + * + * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. + * + * schema.set('toJSON', { virtuals: true }) + * + * See [schema options](/docs/guide.html#toJSON) for details. + * + * @param {Object} options + * @return {Object} + * @see Document#toObject #document_Document-toObject + * @api public + */ + +Document.prototype.toJSON = function(options) { + return this.$toObject(options, true); +}; + +/** + * Helper for console.log + * + * @api public + */ + +Document.prototype.inspect = function(options) { + var opts = options && utils.getFunctionName(options.constructor) === 'Object' ? options : {}; + opts.minimize = false; + opts.retainKeyOrder = true; + return this.toObject(opts); +}; + +/** + * Helper for console.log + * + * @api public + * @method toString + */ + +Document.prototype.toString = function() { + return inspect(this.inspect()); +}; + +/** + * Returns true if the Document stores the same data as doc. + * + * Documents are considered equal when they have matching `_id`s, unless neither + * document has an `_id`, in which case this function falls back to using + * `deepEqual()`. + * + * @param {Document} doc a document to compare + * @return {Boolean} + * @api public + */ + +Document.prototype.equals = function(doc) { + var tid = this.get('_id'); + var docid = doc.get ? doc.get('_id') : doc; + if (!tid && !docid) { + return deepEqual(this, doc); + } + return tid && tid.equals + ? tid.equals(docid) + : tid === docid; +}; + +/** + * Populates document references, executing the `callback` when complete. + * + * ####Example: + * + * doc + * .populate('company') + * .populate({ + * path: 'notes', + * match: /airline/, + * select: 'text', + * model: 'modelName' + * options: opts + * }, function (err, user) { + * assert(doc._id === user._id) // the document itself is passed + * }) + * + * // summary + * doc.populate(path) // not executed + * doc.populate(options); // not executed + * doc.populate(path, callback) // executed + * doc.populate(options, callback); // executed + * doc.populate(callback); // executed + * + * + * ####NOTE: + * + * Population does not occur unless a `callback` is passed *or* you explicitly + * call `execPopulate()`. + * Passing the same path a second time will overwrite the previous path options. + * See [Model.populate()](#model_Model.populate) for explaination of options. + * + * @see Model.populate #model_Model.populate + * @param {String|Object} [path] The path to populate or an options object + * @param {Function} [callback] When passed, population is invoked + * @api public + * @return {Document} this + */ + +Document.prototype.populate = function populate() { + if (arguments.length === 0) { + return this; + } + + var pop = this.$__.populate || (this.$__.populate = {}); + var args = utils.args(arguments); + var fn; + + if (typeof args[args.length - 1] === 'function') { + fn = args.pop(); + } + + // allow `doc.populate(callback)` + if (args.length) { + // use hash to remove duplicate paths + var res = utils.populate.apply(null, args); + for (var i = 0; i < res.length; ++i) { + pop[res[i].path] = res[i]; + } + } + + if (fn) { + var paths = utils.object.vals(pop); + this.$__.populate = undefined; + paths.__noPromise = true; + this.constructor.populate(this, paths, fn); + } + + return this; +}; + +/** + * Explicitly executes population and returns a promise. Useful for ES6 + * integration. + * + * ####Example: + * + * var promise = doc. + * populate('company'). + * populate({ + * path: 'notes', + * match: /airline/, + * select: 'text', + * model: 'modelName' + * options: opts + * }). + * execPopulate(); + * + * // summary + * doc.execPopulate() + * + * + * @see Document.populate #Document_model.populate + * @api public + * @return {Promise} promise that resolves to the document when population is done + */ + +Document.prototype.execPopulate = function() { + var Promise = PromiseProvider.get(); + var _this = this; + return new Promise.ES6(function(resolve, reject) { + _this.populate(function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * Gets _id(s) used during population of the given `path`. + * + * ####Example: + * + * Model.findOne().populate('author').exec(function (err, doc) { + * console.log(doc.author.name) // Dr.Seuss + * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' + * }) + * + * If the path was not populated, undefined is returned. + * + * @param {String} path + * @return {Array|ObjectId|Number|Buffer|String|undefined} + * @api public + */ + +Document.prototype.populated = function(path, val, options) { + // val and options are internal + + if (val === null || val === void 0) { + if (!this.$__.populated) { + return undefined; + } + var v = this.$__.populated[path]; + if (v) { + return v.value; + } + return undefined; + } + + // internal + + if (val === true) { + if (!this.$__.populated) { + return undefined; + } + return this.$__.populated[path]; + } + + this.$__.populated || (this.$__.populated = {}); + this.$__.populated[path] = {value: val, options: options}; + return val; +}; + +/** + * Takes a populated field and returns it to its unpopulated state. + * + * ####Example: + * + * Model.findOne().populate('author').exec(function (err, doc) { + * console.log(doc.author.name); // Dr.Seuss + * console.log(doc.depopulate('author')); + * console.log(doc.author); // '5144cf8050f071d979c118a7' + * }) + * + * If the path was not populated, this is a no-op. + * + * @param {String} path + * @api public + */ + +Document.prototype.depopulate = function(path) { + var populatedIds = this.populated(path); + if (!populatedIds) { + return; + } + delete this.$__.populated[path]; + this.set(path, populatedIds); +}; + + +/** + * Returns the full path to this document. + * + * @param {String} [path] + * @return {String} + * @api private + * @method $__fullPath + * @memberOf Document + */ + +Document.prototype.$__fullPath = function(path) { + // overridden in SubDocuments + return path || ''; +}; + +/*! + * Module exports. + */ + +Document.ValidationError = ValidationError; +module.exports = exports = Document; diff --git a/5-2/service/node_modules/mongoose/lib/document_provider.js b/5-2/service/node_modules/mongoose/lib/document_provider.js new file mode 100644 index 0000000..10087cc --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/document_provider.js @@ -0,0 +1,21 @@ +'use strict'; + +/* eslint-env browser */ + +/*! + * Module dependencies. + */ +var Document = require('./document.js'); +var BrowserDocument = require('./browserDocument.js'); + +/** + * Returns the Document constructor for the current context + * + * @api private + */ +module.exports = function() { + if (typeof window !== 'undefined' && typeof document !== 'undefined' && document === window.document) { + return BrowserDocument; + } + return Document; +}; diff --git a/5-2/service/node_modules/mongoose/lib/drivers/SPEC.md b/5-2/service/node_modules/mongoose/lib/drivers/SPEC.md new file mode 100644 index 0000000..6464693 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/SPEC.md @@ -0,0 +1,4 @@ + +# Driver Spec + +TODO diff --git a/5-2/service/node_modules/mongoose/lib/drivers/browser/ReadPreference.js b/5-2/service/node_modules/mongoose/lib/drivers/browser/ReadPreference.js new file mode 100644 index 0000000..f20cd6c --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/browser/ReadPreference.js @@ -0,0 +1,5 @@ +/*! + * ignore + */ + +module.exports = function() {}; diff --git a/5-2/service/node_modules/mongoose/lib/drivers/browser/binary.js b/5-2/service/node_modules/mongoose/lib/drivers/browser/binary.js new file mode 100644 index 0000000..4d7a395 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/browser/binary.js @@ -0,0 +1,12 @@ + +/*! + * Module dependencies. + */ + +var Binary = require('bson').Binary; + +/*! + * Module exports. + */ + +module.exports = exports = Binary; diff --git a/5-2/service/node_modules/mongoose/lib/drivers/browser/index.js b/5-2/service/node_modules/mongoose/lib/drivers/browser/index.js new file mode 100644 index 0000000..fa5dbb4 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/browser/index.js @@ -0,0 +1,7 @@ +/*! + * Module exports. + */ + +exports.Binary = require('./binary'); +exports.ObjectId = require('./objectid'); +exports.ReadPreference = require('./ReadPreference'); diff --git a/5-2/service/node_modules/mongoose/lib/drivers/browser/objectid.js b/5-2/service/node_modules/mongoose/lib/drivers/browser/objectid.js new file mode 100644 index 0000000..e63c04a --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/browser/objectid.js @@ -0,0 +1,14 @@ + +/*! + * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId + * @constructor NodeMongoDbObjectId + * @see ObjectId + */ + +var ObjectId = require('bson').ObjectID; + +/*! + * ignore + */ + +module.exports = exports = ObjectId; diff --git a/5-2/service/node_modules/mongoose/lib/drivers/index.js b/5-2/service/node_modules/mongoose/lib/drivers/index.js new file mode 100644 index 0000000..5a842ba --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/index.js @@ -0,0 +1,17 @@ +/*! + * ignore + */ + +var driver; + +if (typeof window === 'undefined') { + driver = require(global.MONGOOSE_DRIVER_PATH || './node-mongodb-native'); +} else { + driver = require('./browser'); +} + +/*! + * ignore + */ + +module.exports = driver; diff --git a/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js new file mode 100644 index 0000000..e921d60 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js @@ -0,0 +1,45 @@ +/*! + * Module dependencies. + */ + +var mongodb = require('mongodb'); +var ReadPref = mongodb.ReadPreference; + +/*! + * Converts arguments to ReadPrefs the driver + * can understand. + * + * @param {String|Array} pref + * @param {Array} [tags] + */ + +module.exports = function readPref(pref, tags) { + if (Array.isArray(pref)) { + tags = pref[1]; + pref = pref[0]; + } + + if (pref instanceof ReadPref) { + return pref; + } + + switch (pref) { + case 'p': + pref = 'primary'; + break; + case 'pp': + pref = 'primaryPreferred'; + break; + case 's': + pref = 'secondary'; + break; + case 'sp': + pref = 'secondaryPreferred'; + break; + case 'n': + pref = 'nearest'; + break; + } + + return new ReadPref(pref, tags); +}; diff --git a/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js new file mode 100644 index 0000000..657efde --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js @@ -0,0 +1,8 @@ + +/*! + * Module dependencies. + */ + +var Binary = require('mongodb').Binary; + +module.exports = exports = Binary; diff --git a/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js new file mode 100644 index 0000000..5fc7319 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js @@ -0,0 +1,245 @@ +/*! + * Module dependencies. + */ + +var MongooseCollection = require('../../collection'), + Collection = require('mongodb').Collection, + utils = require('../../utils'); + +/** + * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation. + * + * All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management. + * + * @inherits Collection + * @api private + */ + +function NativeCollection() { + this.collection = null; + MongooseCollection.apply(this, arguments); +} + +/*! + * Inherit from abstract Collection. + */ + +NativeCollection.prototype.__proto__ = MongooseCollection.prototype; + +/** + * Called when the connection opens. + * + * @api private + */ + +NativeCollection.prototype.onOpen = function() { + var _this = this; + + // always get a new collection in case the user changed host:port + // of parent db instance when re-opening the connection. + + if (!_this.opts.capped.size) { + // non-capped + return _this.conn.db.collection(_this.name, callback); + } + + // capped + return _this.conn.db.collection(_this.name, function(err, c) { + if (err) return callback(err); + + // discover if this collection exists and if it is capped + _this.conn.db.listCollections({name: _this.name}).toArray(function(err, docs) { + if (err) { + return callback(err); + } + var doc = docs[0]; + var exists = !!doc; + + if (exists) { + if (doc.options && doc.options.capped) { + callback(null, c); + } else { + var msg = 'A non-capped collection exists with the name: ' + _this.name + '\n\n' + + ' To use this collection as a capped collection, please ' + + 'first convert it.\n' + + ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped'; + err = new Error(msg); + callback(err); + } + } else { + // create + var opts = utils.clone(_this.opts.capped); + opts.capped = true; + _this.conn.db.createCollection(_this.name, opts, callback); + } + }); + }); + + function callback(err, collection) { + if (err) { + // likely a strict mode error + _this.conn.emit('error', err); + } else { + _this.collection = collection; + MongooseCollection.prototype.onOpen.call(_this); + } + } +}; + +/** + * Called when the connection closes + * + * @api private + */ + +NativeCollection.prototype.onClose = function() { + MongooseCollection.prototype.onClose.call(this); +}; + +/*! + * Copy the collection methods and make them subject to queues + */ + +function iter(i) { + NativeCollection.prototype[i] = function() { + if (this.buffer) { + this.addQueue(i, arguments); + return; + } + + var collection = this.collection, + args = arguments, + _this = this, + debug = _this.conn.base.options.debug; + + if (debug) { + if (typeof debug === 'function') { + debug.apply(debug + , [_this.name, i].concat(utils.args(args, 0, args.length - 1))); + } else { + this.$print(_this.name, i, args); + } + } + + return collection[i].apply(collection, args); + }; +} + +for (var i in Collection.prototype) { + // Janky hack to work around gh-3005 until we can get rid of the mongoose + // collection abstraction + try { + if (typeof Collection.prototype[i] !== 'function') { + continue; + } + } catch (e) { + continue; + } + + iter(i); +} + +/** + * Debug print helper + * + * @api public + * @method $print + */ + +NativeCollection.prototype.$print = function(name, i, args) { + console.error( + '\x1B[0;36mMongoose:\x1B[0m %s.%s(%s) %s %s %s', + name, + i, + this.$format(args[0]), + this.$format(args[1]), + this.$format(args[2]), + this.$format(args[3])); +}; + +/** + * Formatter for debug print args + * + * @api public + * @method $format + */ + +NativeCollection.prototype.$format = function(arg) { + var type = typeof arg; + if (type === 'function' || type === 'undefined') return ''; + return format(arg); +}; + +/*! + * Debug print helper + */ + +function map(o) { + return format(o, true); +} +function formatObjectId(x, key) { + var representation = 'ObjectId("' + x[key].toHexString() + '")'; + x[key] = {inspect: function() { return representation; }}; +} +function formatDate(x, key) { + var representation = 'new Date("' + x[key].toUTCString() + '")'; + x[key] = {inspect: function() { return representation; }}; +} +function format(obj, sub) { + var x = utils.clone(obj, {retainKeyOrder: 1}); + var representation; + + if (x != null) { + if (x.constructor.name === 'Binary') { + x = '[object Buffer]'; + } else if (x.constructor.name === 'ObjectID') { + representation = 'ObjectId("' + x.toHexString() + '")'; + x = {inspect: function() { return representation; }}; + } else if (x.constructor.name === 'Date') { + representation = 'new Date("' + x.toUTCString() + '")'; + x = {inspect: function() { return representation; }}; + } else if (x.constructor.name === 'Object') { + var keys = Object.keys(x); + var numKeys = keys.length; + var key; + for (var i = 0; i < numKeys; ++i) { + key = keys[i]; + if (x[key]) { + if (x[key].constructor.name === 'Binary') { + x[key] = '[object Buffer]'; + } else if (x[key].constructor.name === 'Object') { + x[key] = format(x[key], true); + } else if (x[key].constructor.name === 'ObjectID') { + formatObjectId(x, key); + } else if (x[key].constructor.name === 'Date') { + formatDate(x, key); + } else if (Array.isArray(x[key])) { + x[key] = x[key].map(map); + } + } + } + } + if (sub) return x; + } + + return require('util') + .inspect(x, false, 10, true) + .replace(/\n/g, '') + .replace(/\s{2,}/g, ' '); +} + +/** + * Retreives information about this collections indexes. + * + * @param {Function} callback + * @method getIndexes + * @api public + */ + +NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation; + +/*! + * Module exports. + */ + +module.exports = NativeCollection; diff --git a/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js new file mode 100644 index 0000000..0e417f7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js @@ -0,0 +1,357 @@ +/*! + * Module dependencies. + */ + +var MongooseConnection = require('../../connection'), + mongo = require('mongodb'), + Db = mongo.Db, + Server = mongo.Server, + Mongos = mongo.Mongos, + STATES = require('../../connectionstate'), + ReplSetServers = mongo.ReplSet; + +/** + * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation. + * + * @inherits Connection + * @api private + */ + +function NativeConnection() { + MongooseConnection.apply(this, arguments); + this._listening = false; +} + +/** + * Expose the possible connection states. + * @api public + */ + +NativeConnection.STATES = STATES; + +/*! + * Inherits from Connection. + */ + +NativeConnection.prototype.__proto__ = MongooseConnection.prototype; + +/** + * Opens the connection to MongoDB. + * + * @param {Function} fn + * @return {Connection} this + * @api private + */ + +NativeConnection.prototype.doOpen = function(fn) { + var server = new Server(this.host, this.port, this.options.server); + + if (this.options && this.options.mongos) { + var mongos = new Mongos([server], this.options.mongos); + this.db = new Db(this.name, mongos, this.options.db); + } else { + this.db = new Db(this.name, server, this.options.db); + } + + var _this = this; + this.db.open(function(err) { + if (err) return fn(err); + listen(_this); + fn(); + }); + + return this; +}; + +/** + * Switches to a different database using the same connection pool. + * + * Returns a new connection object, with the new db. + * + * @param {String} name The database name + * @return {Connection} New Connection Object + * @api public + */ + +NativeConnection.prototype.useDb = function(name) { + // we have to manually copy all of the attributes... + var newConn = new this.constructor(); + newConn.name = name; + newConn.base = this.base; + newConn.collections = {}; + newConn.models = {}; + newConn.replica = this.replica; + newConn.hosts = this.hosts; + newConn.host = this.host; + newConn.port = this.port; + newConn.user = this.user; + newConn.pass = this.pass; + newConn.options = this.options; + newConn._readyState = this._readyState; + newConn._closeCalled = this._closeCalled; + newConn._hasOpened = this._hasOpened; + newConn._listening = false; + + // First, when we create another db object, we are not guaranteed to have a + // db object to work with. So, in the case where we have a db object and it + // is connected, we can just proceed with setting everything up. However, if + // we do not have a db or the state is not connected, then we need to wait on + // the 'open' event of the connection before doing the rest of the setup + // the 'connected' event is the first time we'll have access to the db object + + var _this = this; + + if (this.db && this._readyState === STATES.connected) { + wireup(); + } else { + this.once('connected', wireup); + } + + function wireup() { + newConn.db = _this.db.db(name); + newConn.onOpen(); + // setup the events appropriately + listen(newConn); + } + + newConn.name = name; + + // push onto the otherDbs stack, this is used when state changes + this.otherDbs.push(newConn); + newConn.otherDbs.push(this); + + return newConn; +}; + +/*! + * Register listeners for important events and bubble appropriately. + */ + +function listen(conn) { + if (conn.db._listening) { + return; + } + conn.db._listening = true; + + conn.db.on('close', function() { + if (conn._closeCalled) return; + + // the driver never emits an `open` event. auto_reconnect still + // emits a `close` event but since we never get another + // `open` we can't emit close + if (conn.db.serverConfig.autoReconnect) { + conn.readyState = STATES.disconnected; + conn.emit('close'); + return; + } + conn.onClose(); + }); + conn.db.on('error', function(err) { + conn.emit('error', err); + }); + conn.db.on('reconnect', function() { + conn.readyState = STATES.connected; + conn.emit('reconnected'); + }); + conn.db.on('timeout', function(err) { + var error = new Error(err && err.err || 'connection timeout'); + conn.emit('error', error); + }); + conn.db.on('open', function(err, db) { + if (STATES.disconnected === conn.readyState && db && db.databaseName) { + conn.readyState = STATES.connected; + conn.emit('reconnected'); + } + }); + conn.db.on('parseError', function(err) { + conn.emit('parseError', err); + }); +} + +/** + * Opens a connection to a MongoDB ReplicaSet. + * + * See description of [doOpen](#NativeConnection-doOpen) for server options. In this case `options.replset` is also passed to ReplSetServers. + * + * @param {Function} fn + * @api private + * @return {Connection} this + */ + +NativeConnection.prototype.doOpenSet = function(fn) { + var servers = [], + _this = this; + + this.hosts.forEach(function(server) { + var host = server.host || server.ipc; + var port = server.port || 27017; + servers.push(new Server(host, port, _this.options.server)); + }); + + var server = this.options.mongos + ? new Mongos(servers, this.options.mongos) + : new ReplSetServers(servers, this.options.replset || this.options.replSet); + this.db = new Db(this.name, server, this.options.db); + + this.db.on('fullsetup', function() { + _this.emit('fullsetup'); + }); + + this.db.open(function(err) { + if (err) return fn(err); + fn(); + listen(_this); + }); + + return this; +}; + +/** + * Closes the connection + * + * @param {Function} fn + * @return {Connection} this + * @api private + */ + +NativeConnection.prototype.doClose = function(fn) { + this.db.close(fn); + return this; +}; + +/** + * Prepares default connection options for the node-mongodb-native driver. + * + * _NOTE: `passed` options take precedence over connection string options._ + * + * @param {Object} passed options that were passed directly during connection + * @param {Object} [connStrOptions] options that were passed in the connection string + * @api private + */ + +NativeConnection.prototype.parseOptions = function(passed, connStrOpts) { + var o = passed || {}; + o.db || (o.db = {}); + o.auth || (o.auth = {}); + o.server || (o.server = {}); + o.replset || (o.replset = o.replSet) || (o.replset = {}); + o.server.socketOptions || (o.server.socketOptions = {}); + o.replset.socketOptions || (o.replset.socketOptions = {}); + + var opts = connStrOpts || {}; + Object.keys(opts).forEach(function(name) { + switch (name) { + case 'ssl': + case 'poolSize': + if (typeof o.server[name] === 'undefined') { + o.server[name] = o.replset[name] = opts[name]; + } + break; + case 'slaveOk': + if (typeof o.server.slave_ok === 'undefined') { + o.server.slave_ok = opts[name]; + } + break; + case 'autoReconnect': + if (typeof o.server.auto_reconnect === 'undefined') { + o.server.auto_reconnect = opts[name]; + } + break; + case 'socketTimeoutMS': + case 'connectTimeoutMS': + if (typeof o.server.socketOptions[name] === 'undefined') { + o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name]; + } + break; + case 'authdb': + if (typeof o.auth.authdb === 'undefined') { + o.auth.authdb = opts[name]; + } + break; + case 'authSource': + if (typeof o.auth.authSource === 'undefined') { + o.auth.authSource = opts[name]; + } + break; + case 'retries': + case 'reconnectWait': + case 'rs_name': + if (typeof o.replset[name] === 'undefined') { + o.replset[name] = opts[name]; + } + break; + case 'replicaSet': + if (typeof o.replset.rs_name === 'undefined') { + o.replset.rs_name = opts[name]; + } + break; + case 'readSecondary': + if (typeof o.replset.read_secondary === 'undefined') { + o.replset.read_secondary = opts[name]; + } + break; + case 'nativeParser': + if (typeof o.db.native_parser === 'undefined') { + o.db.native_parser = opts[name]; + } + break; + case 'w': + case 'safe': + case 'fsync': + case 'journal': + case 'wtimeoutMS': + if (typeof o.db[name] === 'undefined') { + o.db[name] = opts[name]; + } + break; + case 'readPreference': + if (typeof o.db.readPreference === 'undefined') { + o.db.readPreference = opts[name]; + } + break; + case 'readPreferenceTags': + if (typeof o.db.read_preference_tags === 'undefined') { + o.db.read_preference_tags = opts[name]; + } + break; + } + }); + + if (!('auto_reconnect' in o.server)) { + o.server.auto_reconnect = true; + } + + // mongoose creates its own ObjectIds + o.db.forceServerObjectId = false; + + // default safe using new nomenclature + if (!('journal' in o.db || 'j' in o.db || + 'fsync' in o.db || 'safe' in o.db || 'w' in o.db)) { + o.db.w = 1; + } + + validate(o); + return o; +}; + +/*! + * Validates the driver db options. + * + * @param {Object} o + */ + +function validate(o) { + if (o.db.w === -1 || o.db.w === 0) { + if (o.db.journal || o.db.fsync || o.db.safe) { + throw new Error( + 'Invalid writeConcern: ' + + 'w set to -1 or 0 cannot be combined with safe|fsync|journal'); + } + } +} + +/*! + * Module exports. + */ + +module.exports = NativeConnection; diff --git a/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js new file mode 100644 index 0000000..fa5dbb4 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js @@ -0,0 +1,7 @@ +/*! + * Module exports. + */ + +exports.Binary = require('./binary'); +exports.ObjectId = require('./objectid'); +exports.ReadPreference = require('./ReadPreference'); diff --git a/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js new file mode 100644 index 0000000..69fc08f --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js @@ -0,0 +1,14 @@ + +/*! + * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId + * @constructor NodeMongoDbObjectId + * @see ObjectId + */ + +var ObjectId = require('mongodb').ObjectId; + +/*! + * ignore + */ + +module.exports = exports = ObjectId; diff --git a/5-2/service/node_modules/mongoose/lib/error.js b/5-2/service/node_modules/mongoose/lib/error.js new file mode 100644 index 0000000..b084e76 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error.js @@ -0,0 +1,55 @@ + +/** + * MongooseError constructor + * + * @param {String} msg Error message + * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error + */ + +function MongooseError(msg) { + Error.call(this); + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.message = msg; + this.name = 'MongooseError'; +} + +/*! + * Inherits from Error. + */ + +MongooseError.prototype = Object.create(Error.prototype); +MongooseError.prototype.constructor = Error; + +/*! + * Module exports. + */ + +module.exports = exports = MongooseError; + +/** + * The default built-in validator error messages. + * + * @see Error.messages #error_messages_MongooseError-messages + * @api public + */ + +MongooseError.messages = require('./error/messages'); + +// backward compat +MongooseError.Messages = MongooseError.messages; + +/*! + * Expose subclasses + */ + +MongooseError.CastError = require('./error/cast'); +MongooseError.ValidationError = require('./error/validation'); +MongooseError.ValidatorError = require('./error/validator'); +MongooseError.VersionError = require('./error/version'); +MongooseError.OverwriteModelError = require('./error/overwriteModel'); +MongooseError.MissingSchemaError = require('./error/missingSchema'); +MongooseError.DivergentArrayError = require('./error/divergentArray'); diff --git a/5-2/service/node_modules/mongoose/lib/error/browserMissingSchema.js b/5-2/service/node_modules/mongoose/lib/error/browserMissingSchema.js new file mode 100644 index 0000000..1c7892e --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/browserMissingSchema.js @@ -0,0 +1,32 @@ +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/*! + * MissingSchema Error constructor. + * + * @inherits MongooseError + */ + +function MissingSchemaError() { + var msg = 'Schema hasn\'t been registered for document.\n' + + 'Use mongoose.Document(name, schema)'; + MongooseError.call(this, msg); + Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee); + this.name = 'MissingSchemaError'; +} + +/*! + * Inherits from MongooseError. + */ + +MissingSchemaError.prototype = Object.create(MongooseError.prototype); +MissingSchemaError.prototype.constructor = MongooseError; + +/*! + * exports + */ + +module.exports = MissingSchemaError; diff --git a/5-2/service/node_modules/mongoose/lib/error/cast.js b/5-2/service/node_modules/mongoose/lib/error/cast.js new file mode 100644 index 0000000..fcace73 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/cast.js @@ -0,0 +1,42 @@ +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/** + * Casting Error constructor. + * + * @param {String} type + * @param {String} value + * @inherits MongooseError + * @api private + */ + +function CastError(type, value, path, reason) { + MongooseError.call(this, 'Cast to ' + type + ' failed for value "' + value + '" at path "' + path + '"'); + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.name = 'CastError'; + this.kind = type; + this.value = value; + this.path = path; + this.reason = reason; +} + +/*! + * Inherits from MongooseError. + */ + +CastError.prototype = Object.create(MongooseError.prototype); +CastError.prototype.constructor = MongooseError; + + +/*! + * exports + */ + +module.exports = CastError; diff --git a/5-2/service/node_modules/mongoose/lib/error/divergentArray.js b/5-2/service/node_modules/mongoose/lib/error/divergentArray.js new file mode 100644 index 0000000..1cbaa25 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/divergentArray.js @@ -0,0 +1,42 @@ + +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/*! + * DivergentArrayError constructor. + * + * @inherits MongooseError + */ + +function DivergentArrayError(paths) { + var msg = 'For your own good, using `document.save()` to update an array ' + + 'which was selected using an $elemMatch projection OR ' + + 'populated using skip, limit, query conditions, or exclusion of ' + + 'the _id field when the operation results in a $pop or $set of ' + + 'the entire array is not supported. The following ' + + 'path(s) would have been modified unsafely:\n' + + ' ' + paths.join('\n ') + '\n' + + 'Use Model.update() to update these arrays instead.'; + // TODO write up a docs page (FAQ) and link to it + + MongooseError.call(this, msg); + Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee); + this.name = 'DivergentArrayError'; +} + +/*! + * Inherits from MongooseError. + */ + +DivergentArrayError.prototype = Object.create(MongooseError.prototype); +DivergentArrayError.prototype.constructor = MongooseError; + + +/*! + * exports + */ + +module.exports = DivergentArrayError; diff --git a/5-2/service/node_modules/mongoose/lib/error/messages.js b/5-2/service/node_modules/mongoose/lib/error/messages.js new file mode 100644 index 0000000..f825a4f --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/messages.js @@ -0,0 +1,42 @@ + +/** + * The default built-in validator error messages. These may be customized. + * + * // customize within each schema or globally like so + * var mongoose = require('mongoose'); + * mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; + * + * As you might have noticed, error messages support basic templating + * + * - `{PATH}` is replaced with the invalid document path + * - `{VALUE}` is replaced with the invalid value + * - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined" + * - `{MIN}` is replaced with the declared min value for the Number.min validator + * - `{MAX}` is replaced with the declared max value for the Number.max validator + * + * Click the "show code" link below to see all defaults. + * + * @property messages + * @receiver MongooseError + * @api public + */ + +var msg = module.exports = exports = {}; + +msg.general = {}; +msg.general.default = 'Validator failed for path `{PATH}` with value `{VALUE}`'; +msg.general.required = 'Path `{PATH}` is required.'; + +msg.Number = {}; +msg.Number.min = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).'; +msg.Number.max = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).'; + +msg.Date = {}; +msg.Date.min = 'Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).'; +msg.Date.max = 'Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).'; + +msg.String = {}; +msg.String.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; +msg.String.match = 'Path `{PATH}` is invalid ({VALUE}).'; +msg.String.minlength = 'Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'; +msg.String.maxlength = 'Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).'; diff --git a/5-2/service/node_modules/mongoose/lib/error/missingSchema.js b/5-2/service/node_modules/mongoose/lib/error/missingSchema.js new file mode 100644 index 0000000..25eabfa --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/missingSchema.js @@ -0,0 +1,33 @@ + +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/*! + * MissingSchema Error constructor. + * + * @inherits MongooseError + */ + +function MissingSchemaError(name) { + var msg = 'Schema hasn\'t been registered for model "' + name + '".\n' + + 'Use mongoose.model(name, schema)'; + MongooseError.call(this, msg); + Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee); + this.name = 'MissingSchemaError'; +} + +/*! + * Inherits from MongooseError. + */ + +MissingSchemaError.prototype = Object.create(MongooseError.prototype); +MissingSchemaError.prototype.constructor = MongooseError; + +/*! + * exports + */ + +module.exports = MissingSchemaError; diff --git a/5-2/service/node_modules/mongoose/lib/error/objectExpected.js b/5-2/service/node_modules/mongoose/lib/error/objectExpected.js new file mode 100644 index 0000000..fa863bc --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/objectExpected.js @@ -0,0 +1,35 @@ +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/** + * Strict mode error constructor + * + * @param {String} type + * @param {String} value + * @inherits MongooseError + * @api private + */ + +function ObjectExpectedError(path, val) { + MongooseError.call(this, 'Tried to set nested object field `' + path + + '` to primitive value `' + val + '` and strict mode is set to throw.'); + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.name = 'ObjectExpectedError'; + this.path = path; +} + +/*! + * Inherits from MongooseError. + */ + +ObjectExpectedError.prototype = Object.create(MongooseError.prototype); +ObjectExpectedError.prototype.constructor = MongooseError; + +module.exports = ObjectExpectedError; diff --git a/5-2/service/node_modules/mongoose/lib/error/overwriteModel.js b/5-2/service/node_modules/mongoose/lib/error/overwriteModel.js new file mode 100644 index 0000000..c14ae7f --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/overwriteModel.js @@ -0,0 +1,31 @@ + +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/*! + * OverwriteModel Error constructor. + * + * @inherits MongooseError + */ + +function OverwriteModelError(name) { + MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.'); + Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee); + this.name = 'OverwriteModelError'; +} + +/*! + * Inherits from MongooseError. + */ + +OverwriteModelError.prototype = Object.create(MongooseError.prototype); +OverwriteModelError.prototype.constructor = MongooseError; + +/*! + * exports + */ + +module.exports = OverwriteModelError; diff --git a/5-2/service/node_modules/mongoose/lib/error/strict.js b/5-2/service/node_modules/mongoose/lib/error/strict.js new file mode 100644 index 0000000..6e34431 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/strict.js @@ -0,0 +1,35 @@ +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/** + * Strict mode error constructor + * + * @param {String} type + * @param {String} value + * @inherits MongooseError + * @api private + */ + +function StrictModeError(path) { + MongooseError.call(this, 'Field `' + path + '` is not in schema and strict ' + + 'mode is set to throw.'); + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.name = 'StrictModeError'; + this.path = path; +} + +/*! + * Inherits from MongooseError. + */ + +StrictModeError.prototype = Object.create(MongooseError.prototype); +StrictModeError.prototype.constructor = MongooseError; + +module.exports = StrictModeError; diff --git a/5-2/service/node_modules/mongoose/lib/error/validation.js b/5-2/service/node_modules/mongoose/lib/error/validation.js new file mode 100644 index 0000000..bcbad61 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/validation.js @@ -0,0 +1,63 @@ +/*! + * Module requirements + */ + +var MongooseError = require('../error.js'); + +/** + * Document Validation Error + * + * @api private + * @param {Document} instance + * @inherits MongooseError + */ + +function ValidationError(instance) { + if (instance && instance.constructor.name === 'model') { + MongooseError.call(this, instance.constructor.modelName + ' validation failed'); + } else { + MongooseError.call(this, 'Validation failed'); + } + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.name = 'ValidationError'; + this.errors = {}; + if (instance) { + instance.errors = this.errors; + } +} + +/*! + * Inherits from MongooseError. + */ + +ValidationError.prototype = Object.create(MongooseError.prototype); +ValidationError.prototype.constructor = MongooseError; + + +/** + * Console.log helper + */ + +ValidationError.prototype.toString = function() { + var ret = this.name + ': '; + var msgs = []; + + Object.keys(this.errors).forEach(function(key) { + if (this === this.errors[key]) { + return; + } + msgs.push(String(this.errors[key])); + }, this); + + return ret + msgs.join(', '); +}; + +/*! + * Module exports + */ + +module.exports = exports = ValidationError; diff --git a/5-2/service/node_modules/mongoose/lib/error/validator.js b/5-2/service/node_modules/mongoose/lib/error/validator.js new file mode 100644 index 0000000..959073b --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/validator.js @@ -0,0 +1,71 @@ +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); +var errorMessages = MongooseError.messages; + +/** + * Schema validator error + * + * @param {Object} properties + * @inherits MongooseError + * @api private + */ + +function ValidatorError(properties) { + var msg = properties.message; + if (!msg) { + msg = errorMessages.general.default; + } + + this.properties = properties; + var message = this.formatMessage(msg, properties); + MongooseError.call(this, message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.name = 'ValidatorError'; + this.kind = properties.type; + this.path = properties.path; + this.value = properties.value; +} + +/*! + * Inherits from MongooseError + */ + +ValidatorError.prototype = Object.create(MongooseError.prototype); +ValidatorError.prototype.constructor = MongooseError; + +/*! + * Formats error messages + */ + +ValidatorError.prototype.formatMessage = function(msg, properties) { + var propertyNames = Object.keys(properties); + for (var i = 0; i < propertyNames.length; ++i) { + var propertyName = propertyNames[i]; + if (propertyName === 'message') { + continue; + } + msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); + } + return msg; +}; + +/*! + * toString helper + */ + +ValidatorError.prototype.toString = function() { + return this.message; +}; + +/*! + * exports + */ + +module.exports = ValidatorError; diff --git a/5-2/service/node_modules/mongoose/lib/error/version.js b/5-2/service/node_modules/mongoose/lib/error/version.js new file mode 100644 index 0000000..815b1bc --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/error/version.js @@ -0,0 +1,32 @@ + +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/** + * Version Error constructor. + * + * @inherits MongooseError + * @api private + */ + +function VersionError() { + MongooseError.call(this, 'No matching document found.'); + Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee); + this.name = 'VersionError'; +} + +/*! + * Inherits from MongooseError. + */ + +VersionError.prototype = Object.create(MongooseError.prototype); +VersionError.prototype.constructor = MongooseError; + +/*! + * exports + */ + +module.exports = VersionError; diff --git a/5-2/service/node_modules/mongoose/lib/index.js b/5-2/service/node_modules/mongoose/lib/index.js new file mode 100644 index 0000000..6c85703 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/index.js @@ -0,0 +1,771 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +var Schema = require('./schema'), + SchemaType = require('./schematype'), + VirtualType = require('./virtualtype'), + STATES = require('./connectionstate'), + Types = require('./types'), + Query = require('./query'), + Model = require('./model'), + Document = require('./document'), + utils = require('./utils'), + format = utils.toCollectionName, + pkg = require('../package.json'); + +var querystring = require('querystring'); + +var Aggregate = require('./aggregate'); +var PromiseProvider = require('./promise_provider'); + +/** + * Mongoose constructor. + * + * The exports object of the `mongoose` module is an instance of this class. + * Most apps will only use this one instance. + * + * @api public + */ + +function Mongoose() { + this.connections = []; + this.plugins = []; + this.models = {}; + this.modelSchemas = {}; + // default global options + this.options = { + pluralization: true + }; + var conn = this.createConnection(); // default connection + conn.models = this.models; +} + +/** + * Wraps the given Mongoose instance into a thenable (pseudo-promise). This + * is so `connect()` and `disconnect()` can return a thenable while maintaining + * backwards compatibility. + * + * @api private + */ + +function MongooseThenable(mongoose, promise) { + for (var key in mongoose) { + if (typeof mongoose[key] === 'function') { + this[key] = function() { + return mongoose[key].apply(mongoose, arguments); + }; + } else { + this[key] = mongoose[key]; + } + } + this.$opPromise = promise; +} + +/** + * Ability to use mongoose object as a pseudo-promise so `.connect().then()` + * and `.disconnect().then()` are viable. + * + * @param {Function} onFulfilled + * @param {Function} onRejected + * @return {Promise} + * @api private + */ + +MongooseThenable.prototype.then = function(onFulfilled, onRejected) { + var Promise = PromiseProvider.get(); + if (!this.$opPromise) { + return new Promise.ES6(function(resolve, reject) { + reject(new Error('Can only call `.then()` if connect() or disconnect() ' + + 'has been called')); + }).then(onFulfilled, onRejected); + } + return this.$opPromise.then(onFulfilled, onRejected); +}; + +/** + * Ability to use mongoose object as a pseudo-promise so `.connect().then()` + * and `.disconnect().then()` are viable. + * + * @param {Function} onFulfilled + * @param {Function} onRejected + * @return {Promise} + * @api private + */ + +MongooseThenable.prototype.catch = function(onRejected) { + return this.then(null, onRejected); +}; + +/** + * Expose connection states for user-land + * + */ +Mongoose.prototype.STATES = STATES; + +/** + * Sets mongoose options + * + * ####Example: + * + * mongoose.set('test', value) // sets the 'test' option to `value` + * + * mongoose.set('debug', true) // enable logging collection methods + arguments to the console + * + * mongoose.set('debug', function(collectionName, methodName, arg1, arg2...) {}); // use custom function to log collection methods + arguments + * + * @param {String} key + * @param {String|Function} value + * @api public + */ + +Mongoose.prototype.set = function(key, value) { + if (arguments.length === 1) { + return this.options[key]; + } + + this.options[key] = value; + return this; +}; + +/** + * Gets mongoose options + * + * ####Example: + * + * mongoose.get('test') // returns the 'test' value + * + * @param {String} key + * @method get + * @api public + */ + +Mongoose.prototype.get = Mongoose.prototype.set; + +/*! + * ReplSet connection string check. + */ + +var rgxReplSet = /^.+,.+$/; + +/** + * Checks if ?replicaSet query parameter is specified in URI + * + * ####Example: + * + * checkReplicaSetInUri('localhost:27000?replicaSet=rs0'); // true + * + * @param {String} uri + * @return {boolean} + * @api private + */ + +var checkReplicaSetInUri = function(uri) { + if (!uri) { + return false; + } + + var queryStringStart = uri.indexOf('?'); + var isReplicaSet = false; + if (queryStringStart !== -1) { + try { + var obj = querystring.parse(uri.substr(queryStringStart + 1)); + if (obj && obj.replicaSet) { + isReplicaSet = true; + } + } catch (e) { + return false; + } + } + + return isReplicaSet; +}; + +/** + * Creates a Connection instance. + * + * Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections. + * + * If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately. This means we can pass `db`, `server`, and `replset` options to the driver. _Note that the `safe` option specified in your schema will overwrite the `safe` db option specified here unless you set your schemas `safe` option to `undefined`. See [this](/docs/guide.html#safe) for more information._ + * + * _Options passed take precedence over options included in connection strings._ + * + * ####Example: + * + * // with mongodb:// URI + * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); + * + * // and options + * var opts = { db: { native_parser: true }} + * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts); + * + * // replica sets + * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database'); + * + * // and options + * var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }} + * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts); + * + * // with [host, database_name[, port] signature + * db = mongoose.createConnection('localhost', 'database', port) + * + * // and options + * var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' } + * db = mongoose.createConnection('localhost', 'database', port, opts) + * + * // initialize now, connect later + * db = mongoose.createConnection(); + * db.open('localhost', 'database', port, [opts]); + * + * @param {String} [uri] a mongodb:// URI + * @param {Object} [options] options to pass to the driver + * @param {Object} [options.config] mongoose-specific options + * @param {Boolean} [options.config.autoIndex] set to false to disable automatic index creation for all models associated with this connection. + * @see Connection#open #connection_Connection-open + * @see Connection#openSet #connection_Connection-openSet + * @return {Connection} the created Connection object + * @api public + */ + +Mongoose.prototype.createConnection = function(uri, options) { + var conn = new Connection(this); + this.connections.push(conn); + + if (arguments.length) { + if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) { + conn.openSet.apply(conn, arguments); + } else if (options && options.replset && + (options.replset.replicaSet || options.replset.rs_name)) { + conn.openSet.apply(conn, arguments); + } else { + conn.open.apply(conn, arguments); + } + } + + return conn; +}; + +/** + * Opens the default mongoose connection. + * + * If arguments are passed, they are proxied to either + * [Connection#open](#connection_Connection-open) or + * [Connection#openSet](#connection_Connection-openSet) appropriately. + * + * _Options passed take precedence over options included in connection strings._ + * + * ####Example: + * + * mongoose.connect('mongodb://user:pass@localhost:port/database'); + * + * // replica sets + * var uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase'; + * mongoose.connect(uri); + * + * // with options + * mongoose.connect(uri, options); + * + * // connecting to multiple mongos + * var uri = 'mongodb://hostA:27501,hostB:27501'; + * var opts = { mongos: true }; + * mongoose.connect(uri, opts); + * + * // optional callback that gets fired when initial connection completed + * var uri = 'mongodb://nonexistent.domain:27000'; + * mongoose.connect(uri, function(error) { + * // if error is truthy, the initial connection failed. + * }) + * + * @param {String} uri(s) + * @param {Object} [options] + * @param {Function} [callback] + * @see Mongoose#createConnection #index_Mongoose-createConnection + * @api public + * @return {MongooseThenable} pseudo-promise wrapper around this + */ + +Mongoose.prototype.connect = function() { + var conn = this.connection; + if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) { + return new MongooseThenable(this, conn.openSet.apply(conn, arguments)); + } + + return new MongooseThenable(this, conn.open.apply(conn, arguments)); +}; + +/** + * Disconnects all connections. + * + * @param {Function} [fn] called after all connection close. + * @return {MongooseThenable} pseudo-promise wrapper around this + * @api public + */ + +Mongoose.prototype.disconnect = function(fn) { + var error; + this.connections.forEach(function(conn) { + conn.close(function(err) { + if (error) { + return; + } + if (err) { + error = err; + } + }); + }); + + var Promise = PromiseProvider.get(); + return new MongooseThenable(this, new Promise.ES6(function(resolve, reject) { + fn && fn(error); + if (error) { + reject(error); + return; + } + resolve(); + })); +}; + +/** + * Defines a model or retrieves it. + * + * Models defined on the `mongoose` instance are available to all connection created by the same `mongoose` instance. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * + * // define an Actor model with this mongoose instance + * mongoose.model('Actor', new Schema({ name: String })); + * + * // create a new connection + * var conn = mongoose.createConnection(..); + * + * // retrieve the Actor model + * var Actor = conn.model('Actor'); + * + * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ + * + * ####Example: + * + * var schema = new Schema({ name: String }, { collection: 'actor' }); + * + * // or + * + * schema.set('collection', 'actor'); + * + * // or + * + * var collectionName = 'actor' + * var M = mongoose.model('Actor', schema, collectionName) + * + * @param {String} name model name + * @param {Schema} [schema] + * @param {String} [collection] name (optional, induced from model name) + * @param {Boolean} [skipInit] whether to skip initialization (defaults to false) + * @api public + */ + +Mongoose.prototype.model = function(name, schema, collection, skipInit) { + if (typeof schema === 'string') { + collection = schema; + schema = false; + } + + if (utils.isObject(schema) && !(schema.instanceOfSchema)) { + schema = new Schema(schema); + } + + if (typeof collection === 'boolean') { + skipInit = collection; + collection = null; + } + + // handle internal options from connection.model() + var options; + if (skipInit && utils.isObject(skipInit)) { + options = skipInit; + skipInit = true; + } else { + options = {}; + } + + // look up schema for the collection. + if (!this.modelSchemas[name]) { + if (schema) { + // cache it so we only apply plugins once + this.modelSchemas[name] = schema; + this._applyPlugins(schema); + } else { + throw new mongoose.Error.MissingSchemaError(name); + } + } + + var model; + var sub; + + // connection.model() may be passing a different schema for + // an existing model name. in this case don't read from cache. + if (this.models[name] && options.cache !== false) { + if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { + throw new mongoose.Error.OverwriteModelError(name); + } + + if (collection) { + // subclass current model with alternate collection + model = this.models[name]; + schema = model.prototype.schema; + sub = model.__subclass(this.connection, schema, collection); + // do not cache the sub model + return sub; + } + + return this.models[name]; + } + + // ensure a schema exists + if (!schema) { + schema = this.modelSchemas[name]; + if (!schema) { + throw new mongoose.Error.MissingSchemaError(name); + } + } + + // Apply relevant "global" options to the schema + if (!('pluralization' in schema.options)) schema.options.pluralization = this.options.pluralization; + + + if (!collection) { + collection = schema.get('collection') || format(name, schema.options); + } + + var connection = options.connection || this.connection; + model = Model.compile(name, schema, collection, connection, this); + + if (!skipInit) { + model.init(); + } + + if (options.cache === false) { + return model; + } + + this.models[name] = model; + return this.models[name]; +}; + +/** + * Returns an array of model names created on this instance of Mongoose. + * + * ####Note: + * + * _Does not include names of models created using `connection.model()`._ + * + * @api public + * @return {Array} + */ + +Mongoose.prototype.modelNames = function() { + var names = Object.keys(this.models); + return names; +}; + +/** + * Applies global plugins to `schema`. + * + * @param {Schema} schema + * @api private + */ + +Mongoose.prototype._applyPlugins = function(schema) { + for (var i = 0, l = this.plugins.length; i < l; i++) { + schema.plugin(this.plugins[i][0], this.plugins[i][1]); + } +}; + +/** + * Declares a global plugin executed on all Schemas. + * + * Equivalent to calling `.plugin(fn)` on each Schema you create. + * + * @param {Function} fn plugin callback + * @param {Object} [opts] optional options + * @return {Mongoose} this + * @see plugins ./plugins.html + * @api public + */ + +Mongoose.prototype.plugin = function(fn, opts) { + this.plugins.push([fn, opts]); + return this; +}; + +/** + * The default connection of the mongoose module. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * mongoose.connect(...); + * mongoose.connection.on('error', cb); + * + * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model). + * + * @property connection + * @return {Connection} + * @api public + */ + +Mongoose.prototype.__defineGetter__('connection', function() { + return this.connections[0]; +}); + +/*! + * Driver depentend APIs + */ + +var driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native'; + +/*! + * Connection + */ + +var Connection = require(driver + '/connection'); + +/*! + * Collection + */ + +var Collection = require(driver + '/collection'); + +/** + * The Mongoose Aggregate constructor + * + * @method Aggregate + * @api public + */ + +Mongoose.prototype.Aggregate = Aggregate; + +/** + * The Mongoose Collection constructor + * + * @method Collection + * @api public + */ + +Mongoose.prototype.Collection = Collection; + +/** + * The Mongoose [Connection](#connection_Connection) constructor + * + * @method Connection + * @api public + */ + +Mongoose.prototype.Connection = Connection; + +/** + * The Mongoose version + * + * @property version + * @api public + */ + +Mongoose.prototype.version = pkg.version; + +/** + * The Mongoose constructor + * + * The exports of the mongoose module is an instance of this class. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var mongoose2 = new mongoose.Mongoose(); + * + * @method Mongoose + * @api public + */ + +Mongoose.prototype.Mongoose = Mongoose; + +/** + * The Mongoose [Schema](#schema_Schema) constructor + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var Schema = mongoose.Schema; + * var CatSchema = new Schema(..); + * + * @method Schema + * @api public + */ + +Mongoose.prototype.Schema = Schema; + +/** + * The Mongoose [SchemaType](#schematype_SchemaType) constructor + * + * @method SchemaType + * @api public + */ + +Mongoose.prototype.SchemaType = SchemaType; + +/** + * The various Mongoose SchemaTypes. + * + * ####Note: + * + * _Alias of mongoose.Schema.Types for backwards compatibility._ + * + * @property SchemaTypes + * @see Schema.SchemaTypes #schema_Schema.Types + * @api public + */ + +Mongoose.prototype.SchemaTypes = Schema.Types; + +/** + * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor + * + * @method VirtualType + * @api public + */ + +Mongoose.prototype.VirtualType = VirtualType; + +/** + * The various Mongoose Types. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var array = mongoose.Types.Array; + * + * ####Types: + * + * - [ObjectId](#types-objectid-js) + * - [Buffer](#types-buffer-js) + * - [SubDocument](#types-embedded-js) + * - [Array](#types-array-js) + * - [DocumentArray](#types-documentarray-js) + * + * Using this exposed access to the `ObjectId` type, we can construct ids on demand. + * + * var ObjectId = mongoose.Types.ObjectId; + * var id1 = new ObjectId; + * + * @property Types + * @api public + */ + +Mongoose.prototype.Types = Types; + +/** + * The Mongoose [Query](#query_Query) constructor. + * + * @method Query + * @api public + */ + +Mongoose.prototype.Query = Query; + +/** + * The Mongoose [Promise](#promise_Promise) constructor. + * + * @method Promise + * @api public + */ + +Object.defineProperty(Mongoose.prototype, 'Promise', { + get: function() { + return PromiseProvider.get(); + }, + set: function(lib) { + PromiseProvider.set(lib); + } +}); + +/** + * Storage layer for mongoose promises + * + * @method PromiseProvider + * @api public + */ + +Mongoose.prototype.PromiseProvider = PromiseProvider; + +/** + * The Mongoose [Model](#model_Model) constructor. + * + * @method Model + * @api public + */ + +Mongoose.prototype.Model = Model; + +/** + * The Mongoose [Document](#document-js) constructor. + * + * @method Document + * @api public + */ + +Mongoose.prototype.Document = Document; + +/** + * The Mongoose DocumentProvider constructor. + * + * @method DocumentProvider + * @api public + */ + +Mongoose.prototype.DocumentProvider = require('./document_provider'); + +/** + * The [MongooseError](#error_MongooseError) constructor. + * + * @method Error + * @api public + */ + +Mongoose.prototype.Error = require('./error'); + +/** + * The Mongoose CastError constructor + * + * @method Error + * @api public + */ + +Mongoose.prototype.CastError = require('./error/cast'); + +/** + * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses. + * + * @property mongo + * @api public + */ + +Mongoose.prototype.mongo = require('mongodb'); + +/** + * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses. + * + * @property mquery + * @api public + */ + +Mongoose.prototype.mquery = require('mquery'); + +/*! + * The exports object is an instance of Mongoose. + * + * @api public + */ + +var mongoose = module.exports = exports = new Mongoose; diff --git a/5-2/service/node_modules/mongoose/lib/internal.js b/5-2/service/node_modules/mongoose/lib/internal.js new file mode 100644 index 0000000..edf3338 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/internal.js @@ -0,0 +1,31 @@ +/*! + * Dependencies + */ + +var StateMachine = require('./statemachine'); +var ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore'); + +module.exports = exports = InternalCache; + +function InternalCache() { + this.strictMode = undefined; + this.selected = undefined; + this.shardval = undefined; + this.saveError = undefined; + this.validationError = undefined; + this.adhocPaths = undefined; + this.removing = undefined; + this.inserting = undefined; + this.version = undefined; + this.getters = {}; + this._id = undefined; + this.populate = undefined; // what we want to populate in this doc + this.populated = undefined;// the _ids that have been populated + this.wasPopulated = false; // if this doc was the result of a population + this.scope = undefined; + this.activePaths = new ActiveRoster; + + // embedded docs + this.ownerDocument = undefined; + this.fullPath = undefined; +} diff --git a/5-2/service/node_modules/mongoose/lib/model.js b/5-2/service/node_modules/mongoose/lib/model.js new file mode 100644 index 0000000..185f83a --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/model.js @@ -0,0 +1,3183 @@ +/*! + * Module dependencies. + */ + +var Document = require('./document'); +var MongooseError = require('./error'); +var VersionError = MongooseError.VersionError; +var DivergentArrayError = MongooseError.DivergentArrayError; +var Query = require('./query'); +var Aggregate = require('./aggregate'); +var Schema = require('./schema'); +var utils = require('./utils'); +var hasOwnProperty = utils.object.hasOwnProperty; +var isMongooseObject = utils.isMongooseObject; +var EventEmitter = require('events').EventEmitter; +var Promise = require('./promise'); +var util = require('util'); +var tick = utils.tick; + +var async = require('async'); +var PromiseProvider = require('./promise_provider'); + +var VERSION_WHERE = 1, + VERSION_INC = 2, + VERSION_ALL = VERSION_WHERE | VERSION_INC; + +/** + * Model constructor + * + * Provides the interface to MongoDB collections as well as creates document instances. + * + * @param {Object} doc values with which to create the document + * @inherits Document + * @event `error`: If listening to this event, it is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. + * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. + * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event. + * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed. + * @api public + */ + +function Model(doc, fields, skipId) { + Document.call(this, doc, fields, skipId); +} + +/*! + * Inherits from Document. + * + * All Model.prototype features are available on + * top level (non-sub) documents. + */ + +Model.prototype.__proto__ = Document.prototype; + +/** + * Connection the model uses. + * + * @api public + * @property db + */ + +Model.prototype.db; + +/** + * Collection the model uses. + * + * @api public + * @property collection + */ + +Model.prototype.collection; + +/** + * The name of the model + * + * @api public + * @property modelName + */ + +Model.prototype.modelName; + +/** + * If this is a discriminator model, `baseModelName` is the name of + * the base model. + * + * @api public + * @property baseModelName + */ + +Model.prototype.baseModelName; + +Model.prototype.$__handleSave = function(options, callback) { + var _this = this; + if (!options.safe && this.schema.options.safe) { + options.safe = this.schema.options.safe; + } + if (typeof options.safe === 'boolean') { + options.safe = null; + } + + if (this.isNew) { + // send entire doc + var toObjectOptions = {}; + if (this.schema.options.toObject && + this.schema.options.toObject.retainKeyOrder) { + toObjectOptions.retainKeyOrder = true; + } + + toObjectOptions.depopulate = 1; + toObjectOptions._skipDepopulateTopLevel = true; + toObjectOptions.transform = false; + + var obj = this.toObject(toObjectOptions); + + if (!utils.object.hasOwnProperty(obj || {}, '_id')) { + // documents must have an _id else mongoose won't know + // what to update later if more changes are made. the user + // wouldn't know what _id was generated by mongodb either + // nor would the ObjectId generated my mongodb necessarily + // match the schema definition. + setTimeout(function() { + callback(new Error('document must have an _id before saving')); + }, 0); + return; + } + + this.$__version(true, obj); + this.collection.insert(obj, options.safe, function(err, ret) { + if (err) { + _this.isNew = true; + _this.emit('isNew', true); + + callback(err); + return; + } + + callback(null, ret); + }); + this.$__reset(); + this.isNew = false; + this.emit('isNew', false); + // Make it possible to retry the insert + this.$__.inserting = true; + } else { + // Make sure we don't treat it as a new object on error, + // since it already exists + this.$__.inserting = false; + + var delta = this.$__delta(); + + if (delta) { + if (delta instanceof Error) { + callback(delta); + return; + } + var where = this.$__where(delta[0]); + + if (where instanceof Error) { + callback(where); + return; + } + + this.collection.update(where, delta[1], options.safe, function(err, ret) { + if (err) { + callback(err); + return; + } + callback(null, ret); + }); + } else { + this.$__reset(); + callback(); + return; + } + + this.emit('isNew', false); + } +}; + +/*! + * ignore + */ + +Model.prototype.$__save = function(options, callback) { + var _this = this; + + _this.$__handleSave(options, function(error, result) { + if (error) { + return callback(error); + } + + _this.$__reset(); + _this.$__storeShard(); + + var numAffected = 0; + if (result) { + if (Array.isArray(result)) { + numAffected = result.length; + } else if (result.result && result.result.n !== undefined) { + numAffected = result.result.n; + } else if (result.result && result.result.nModified !== undefined) { + numAffected = result.result.nModified; + } else { + numAffected = result; + } + } + + // was this an update that required a version bump? + if (_this.$__.version && !_this.$__.inserting) { + var doIncrement = VERSION_INC === (VERSION_INC & _this.$__.version); + _this.$__.version = undefined; + + if (numAffected <= 0) { + // the update failed. pass an error back + var err = new VersionError(); + return callback(err); + } + + // increment version if was successful + if (doIncrement) { + var key = _this.schema.options.versionKey; + var version = _this.getValue(key) | 0; + _this.setValue(key, version + 1); + } + } + + _this.emit('save', _this, numAffected); + callback(null, _this, numAffected); + }); +}; + +/** + * Saves this document. + * + * ####Example: + * + * product.sold = Date.now(); + * product.save(function (err, product, numAffected) { + * if (err) .. + * }) + * + * The callback will receive three parameters + * + * 1. `err` if an error occurred + * 2. `product` which is the saved `product` + * 3. `numAffected` will be 1 when the document was successfully persisted to MongoDB, otherwise 0. Unless you tweak mongoose's internals, you don't need to worry about checking this parameter for errors - checking `err` is sufficient to make sure your document was properly saved. + * + * As an extra measure of flow control, save will return a Promise. + * ####Example: + * product.save().then(function(product) { + * ... + * }); + * + * For legacy reasons, mongoose stores object keys in reverse order on initial + * save. That is, `{ a: 1, b: 2 }` will be saved as `{ b: 2, a: 1 }` in + * MongoDB. To override this behavior, set + * [the `toObject.retainKeyOrder` option](http://mongoosejs.com/docs/api.html#document_Document-toObject) + * to true on your schema. + * + * @param {Object} [options] options optional options + * @param {Object} [options.safe] overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe) + * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. + * @param {Function} [fn] optional callback + * @return {Promise} Promise + * @api public + * @see middleware http://mongoosejs.com/docs/middleware.html + */ + +Model.prototype.save = function(options, fn) { + if (typeof options === 'function') { + fn = options; + options = undefined; + } + + if (!options) { + options = {}; + } + + if (options.__noPromise) { + return this.$__save(options, fn); + } + + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _this.$__save(options, function(error, doc, numAffected) { + if (error) { + fn && fn(error); + reject(error); + return; + } + + fn && fn(null, doc, numAffected); + resolve(doc, numAffected); + }); + }); +}; + +/** + * Determines whether versioning should be skipped for the given path + * + * @param {Document} self + * @param {String} path + * @return {Boolean} true if versioning should be skipped for the given path + */ +function shouldSkipVersioning(self, path) { + var skipVersioning = self.schema.options.skipVersioning; + if (!skipVersioning) return false; + + // Remove any array indexes from the path + path = path.replace(/\.\d+\./, '.'); + + return skipVersioning[path]; +} + +/*! + * Apply the operation to the delta (update) clause as + * well as track versioning for our where clause. + * + * @param {Document} self + * @param {Object} where + * @param {Object} delta + * @param {Object} data + * @param {Mixed} val + * @param {String} [operation] + */ + +function operand(self, where, delta, data, val, op) { + // delta + op || (op = '$set'); + if (!delta[op]) delta[op] = {}; + delta[op][data.path] = val; + + // disabled versioning? + if (self.schema.options.versionKey === false) return; + + // path excluded from versioning? + if (shouldSkipVersioning(self, data.path)) return; + + // already marked for versioning? + if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; + + switch (op) { + case '$set': + case '$unset': + case '$pop': + case '$pull': + case '$pullAll': + case '$push': + case '$pushAll': + case '$addToSet': + break; + default: + // nothing to do + return; + } + + // ensure updates sent with positional notation are + // editing the correct array element. + // only increment the version if an array position changes. + // modifying elements of an array is ok if position does not change. + + if (op === '$push' || op === '$pushAll' || op === '$addToSet') { + self.$__.version = VERSION_INC; + } else if (/^\$p/.test(op)) { + // potentially changing array positions + self.increment(); + } else if (Array.isArray(val)) { + // $set an array + self.increment(); + } else if (/\.\d+\.|\.\d+$/.test(data.path)) { + // now handling $set, $unset + // subpath of array + self.$__.version = VERSION_WHERE; + } +} + +/*! + * Compiles an update and where clause for a `val` with _atomics. + * + * @param {Document} self + * @param {Object} where + * @param {Object} delta + * @param {Object} data + * @param {Array} value + */ + +function handleAtomics(self, where, delta, data, value) { + if (delta.$set && delta.$set[data.path]) { + // $set has precedence over other atomics + return; + } + + if (typeof value.$__getAtomics === 'function') { + value.$__getAtomics().forEach(function(atomic) { + var op = atomic[0]; + var val = atomic[1]; + operand(self, where, delta, data, val, op); + }); + return; + } + + // legacy support for plugins + + var atomics = value._atomics, + ops = Object.keys(atomics), + i = ops.length, + val, + op; + + if (i === 0) { + // $set + + if (isMongooseObject(value)) { + value = value.toObject({depopulate: 1}); + } else if (value.valueOf) { + value = value.valueOf(); + } + + return operand(self, where, delta, data, value); + } + + function iter(mem) { + return isMongooseObject(mem) + ? mem.toObject({depopulate: 1}) + : mem; + } + + while (i--) { + op = ops[i]; + val = atomics[op]; + + if (isMongooseObject(val)) { + val = val.toObject({depopulate: 1}); + } else if (Array.isArray(val)) { + val = val.map(iter); + } else if (val.valueOf) { + val = val.valueOf(); + } + + if (op === '$addToSet') { + val = {$each: val}; + } + + operand(self, where, delta, data, val, op); + } +} + +/** + * Produces a special query document of the modified properties used in updates. + * + * @api private + * @method $__delta + * @memberOf Model + */ + +Model.prototype.$__delta = function() { + var dirty = this.$__dirty(); + if (!dirty.length && VERSION_ALL !== this.$__.version) return; + + var where = {}, + delta = {}, + len = dirty.length, + divergent = [], + d = 0; + + where._id = this._doc._id; + + for (; d < len; ++d) { + var data = dirty[d]; + var value = data.value; + + var match = checkDivergentArray(this, data.path, value); + if (match) { + divergent.push(match); + continue; + } + + if (divergent.length) continue; + + if (undefined === value) { + operand(this, where, delta, data, 1, '$unset'); + } else if (value === null) { + operand(this, where, delta, data, null); + } else if (value._path && value._atomics) { + // arrays and other custom types (support plugins etc) + handleAtomics(this, where, delta, data, value); + } else if (value._path && Buffer.isBuffer(value)) { + // MongooseBuffer + value = value.toObject(); + operand(this, where, delta, data, value); + } else { + value = utils.clone(value, {depopulate: 1}); + operand(this, where, delta, data, value); + } + } + + if (divergent.length) { + return new DivergentArrayError(divergent); + } + + if (this.$__.version) { + this.$__version(where, delta); + } + + return [where, delta]; +}; + +/*! + * Determine if array was populated with some form of filter and is now + * being updated in a manner which could overwrite data unintentionally. + * + * @see https://github.com/Automattic/mongoose/issues/1334 + * @param {Document} doc + * @param {String} path + * @return {String|undefined} + */ + +function checkDivergentArray(doc, path, array) { + // see if we populated this path + var pop = doc.populated(path, true); + + if (!pop && doc.$__.selected) { + // If any array was selected using an $elemMatch projection, we deny the update. + // NOTE: MongoDB only supports projected $elemMatch on top level array. + var top = path.split('.')[0]; + if ((doc.$__.selected[top] && doc.$__.selected[top].$elemMatch) || + doc.$__.selected[top + '.$']) { + return top; + } + } + + if (!(pop && array && array.isMongooseArray)) return; + + // If the array was populated using options that prevented all + // documents from being returned (match, skip, limit) or they + // deselected the _id field, $pop and $set of the array are + // not safe operations. If _id was deselected, we do not know + // how to remove elements. $pop will pop off the _id from the end + // of the array in the db which is not guaranteed to be the + // same as the last element we have here. $set of the entire array + // would be similarily destructive as we never received all + // elements of the array and potentially would overwrite data. + var check = pop.options.match || + pop.options.options && hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted + pop.options.options && pop.options.options.skip || // 0 is permitted + pop.options.select && // deselected _id? + (pop.options.select._id === 0 || + /\s?-_id\s?/.test(pop.options.select)); + + if (check) { + var atomics = array._atomics; + if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) { + return path; + } + } +} + +/** + * Appends versioning to the where and update clauses. + * + * @api private + * @method $__version + * @memberOf Model + */ + +Model.prototype.$__version = function(where, delta) { + var key = this.schema.options.versionKey; + + if (where === true) { + // this is an insert + if (key) this.setValue(key, delta[key] = 0); + return; + } + + // updates + + // only apply versioning if our versionKey was selected. else + // there is no way to select the correct version. we could fail + // fast here and force them to include the versionKey but + // thats a bit intrusive. can we do this automatically? + if (!this.isSelected(key)) { + return; + } + + // $push $addToSet don't need the where clause set + if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { + where[key] = this.getValue(key); + } + + if (VERSION_INC === (VERSION_INC & this.$__.version)) { + if (!delta.$set || typeof delta.$set[key] === 'undefined') { + delta.$inc || (delta.$inc = {}); + delta.$inc[key] = 1; + } + } +}; + +/** + * Signal that we desire an increment of this documents version. + * + * ####Example: + * + * Model.findById(id, function (err, doc) { + * doc.increment(); + * doc.save(function (err) { .. }) + * }) + * + * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey + * @api public + */ + +Model.prototype.increment = function increment() { + this.$__.version = VERSION_ALL; + return this; +}; + +/** + * Returns a query object which applies shardkeys if they exist. + * + * @api private + * @method $__where + * @memberOf Model + */ + +Model.prototype.$__where = function _where(where) { + where || (where = {}); + + var paths, + len; + + if (!where._id) { + where._id = this._doc._id; + } + + if (this.$__.shardval) { + paths = Object.keys(this.$__.shardval); + len = paths.length; + + for (var i = 0; i < len; ++i) { + where[paths[i]] = this.$__.shardval[paths[i]]; + } + } + + if (this._doc._id == null) { + return new Error('No _id found on document!'); + } + + return where; +}; + +/** + * Removes this document from the db. + * + * ####Example: + * product.remove(function (err, product) { + * if (err) return handleError(err); + * Product.findById(product._id, function (err, product) { + * console.log(product) // null + * }) + * }) + * + * + * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recive errors + * + * ####Example: + * product.remove().then(function (product) { + * ... + * }).onRejected(function (err) { + * assert.ok(err) + * }) + * + * @param {function(err,product)} [fn] optional callback + * @return {Promise} Promise + * @api public + */ + +Model.prototype.remove = function remove(options, fn) { + if (typeof options === 'function') { + fn = options; + options = undefined; + } + + if (!options) { + options = {}; + } + + if (this.$__.removing) { + if (fn) { + this.$__.removing.then( + function(res) { fn(null, res); }, + function(err) { fn(err); }); + } + return this; + } + + var _this = this; + var Promise = PromiseProvider.get(); + this.$__.removing = new Promise.ES6(function(resolve, reject) { + var where = _this.$__where(); + if (where instanceof Error) { + reject(where); + fn && fn(where); + return; + } + + if (!options.safe && _this.schema.options.safe) { + options.safe = _this.schema.options.safe; + } + + _this.collection.remove(where, options, function(err) { + if (!err) { + _this.emit('remove', _this); + resolve(_this); + fn && fn(null, _this); + return; + } + + reject(err); + fn && fn(err); + }); + }); + return this.$__.removing; +}; + +/** + * Returns another Model instance. + * + * ####Example: + * + * var doc = new Tank; + * doc.model('User').findById(id, callback); + * + * @param {String} name model name + * @api public + */ + +Model.prototype.model = function model(name) { + return this.db.model(name); +}; + +/** + * Adds a discriminator type. + * + * ####Example: + * + * function BaseSchema() { + * Schema.apply(this, arguments); + * + * this.add({ + * name: String, + * createdAt: Date + * }); + * } + * util.inherits(BaseSchema, Schema); + * + * var PersonSchema = new BaseSchema(); + * var BossSchema = new BaseSchema({ department: String }); + * + * var Person = mongoose.model('Person', PersonSchema); + * var Boss = Person.discriminator('Boss', BossSchema); + * + * @param {String} name discriminator model name + * @param {Schema} schema discriminator model schema + * @api public + */ + +Model.discriminator = function discriminator(name, schema) { + if (!(schema && schema.instanceOfSchema)) { + throw new Error('You must pass a valid discriminator Schema'); + } + + if (this.schema.discriminatorMapping && !this.schema.discriminatorMapping.isRoot) { + throw new Error('Discriminator "' + name + + '" can only be a discriminator of the root model'); + } + + var key = this.schema.options.discriminatorKey; + if (schema.path(key)) { + throw new Error('Discriminator "' + name + + '" cannot have field with name "' + key + '"'); + } + + function clean(a, b) { + a = utils.clone(a); + b = utils.clone(b); + delete a.toJSON; + delete a.toObject; + delete b.toJSON; + delete b.toObject; + delete a._id; + delete b._id; + + if (!utils.deepEqual(a, b)) { + throw new Error('Discriminator options are not customizable ' + + '(except toJSON, toObject, _id)'); + } + } + + function merge(schema, baseSchema) { + utils.merge(schema, baseSchema); + + var obj = {}; + obj[key] = {type: String, default: name}; + schema.add(obj); + schema.discriminatorMapping = {key: key, value: name, isRoot: false}; + + if (baseSchema.options.collection) { + schema.options.collection = baseSchema.options.collection; + } + + // throws error if options are invalid + clean(schema.options, baseSchema.options); + + var toJSON = schema.options.toJSON; + var toObject = schema.options.toObject; + var _id = schema.options._id; + + schema.options = utils.clone(baseSchema.options); + if (toJSON) schema.options.toJSON = toJSON; + if (toObject) schema.options.toObject = toObject; + if (typeof _id !== 'undefined') { + schema.options._id = _id; + } + + schema.callQueue = baseSchema.callQueue.concat(schema.callQueue.slice(schema._defaultMiddleware.length)); + schema._requiredpaths = undefined; // reset just in case Schema#requiredPaths() was called on either schema + } + + // merges base schema into new discriminator schema and sets new type field. + merge(schema, this.schema); + + if (!this.discriminators) { + this.discriminators = {}; + } + + if (!this.schema.discriminatorMapping) { + this.schema.discriminatorMapping = {key: key, value: null, isRoot: true}; + } + + if (this.discriminators[name]) { + throw new Error('Discriminator with name "' + name + '" already exists'); + } + + this.discriminators[name] = this.db.model(name, schema, this.collection.name); + this.discriminators[name].prototype.__proto__ = this.prototype; + Object.defineProperty(this.discriminators[name], 'baseModelName', { + value: this.modelName, + configurable: true, + writable: false + }); + + // apply methods and statics + applyMethods(this.discriminators[name], schema); + applyStatics(this.discriminators[name], schema); + + return this.discriminators[name]; +}; + +// Model (class) features + +/*! + * Give the constructor the ability to emit events. + */ + +for (var i in EventEmitter.prototype) { + Model[i] = EventEmitter.prototype[i]; +} + +/** + * Called when the model compiles. + * + * @api private + */ + +Model.init = function init() { + if ((this.schema.options.autoIndex) || + (this.schema.options.autoIndex === null && this.db.config.autoIndex)) { + this.ensureIndexes({ __noPromise: true }); + } + + this.schema.emit('init', this); +}; + +/** + * Sends `ensureIndex` commands to mongo for each index declared in the schema. + * + * ####Example: + * + * Event.ensureIndexes(function (err) { + * if (err) return handleError(err); + * }); + * + * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. + * + * ####Example: + * + * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) + * var Event = mongoose.model('Event', eventSchema); + * + * Event.on('index', function (err) { + * if (err) console.error(err); // error occurred during index creation + * }) + * + * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ + * + * The `ensureIndex` commands are not sent in parallel. This is to avoid the `MongoError: cannot add index with a background operation in progress` error. See [this ticket](https://github.com/Automattic/mongoose/issues/1365) for more information. + * + * @param {Object} [options] internal options + * @param {Function} [cb] optional callback + * @return {Promise} + * @api public + */ + +Model.ensureIndexes = function ensureIndexes(options, cb) { + if (typeof options === 'function') { + cb = options; + options = null; + } + + if (options && options.__noPromise) { + _ensureIndexes(this, cb); + return; + } + + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _ensureIndexes(_this, function(error) { + if (error) { + cb && cb(error); + reject(error); + } + cb && cb(); + resolve(); + }); + }); +}; + +function _ensureIndexes(model, callback) { + var indexes = model.schema.indexes(); + if (!indexes.length) { + process.nextTick(function() { + callback && callback(); + }); + return; + } + // Indexes are created one-by-one to support how MongoDB < 2.4 deals + // with background indexes. + + var done = function(err) { + if (err && model.schema.options.emitIndexErrors) { + model.emit('error', err); + } + model.emit('index', err); + callback && callback(err); + }; + + var indexSingleDone = function(err, fields, options, name) { + model.emit('index-single-done', err, fields, options, name); + }; + var indexSingleStart = function(fields, options) { + model.emit('index-single-start', fields, options); + }; + + var create = function() { + var index = indexes.shift(); + if (!index) return done(); + + var indexFields = index[0]; + var options = index[1]; + _handleSafe(options); + + indexSingleStart(indexFields, options); + + model.collection.ensureIndex(indexFields, options, tick(function(err, name) { + indexSingleDone(err, indexFields, options, name); + if (err) { + return done(err); + } + create(); + })); + }; + + create(); +} + +function _handleSafe(options) { + if (options.safe) { + if (typeof options.safe === 'boolean') { + options.w = options.safe; + delete options.safe; + } + if (typeof options.safe === 'object') { + options.w = options.safe.w; + options.j = options.safe.j; + options.wtimeout = options.safe.wtimeout; + delete options.safe; + } + } +} + +/** + * Schema the model uses. + * + * @property schema + * @receiver Model + * @api public + */ + +Model.schema; + +/*! + * Connection instance the model uses. + * + * @property db + * @receiver Model + * @api public + */ + +Model.db; + +/*! + * Collection the model uses. + * + * @property collection + * @receiver Model + * @api public + */ + +Model.collection; + +/** + * Base Mongoose instance the model uses. + * + * @property base + * @receiver Model + * @api public + */ + +Model.base; + +/** + * Registered discriminators for this model. + * + * @property discriminators + * @receiver Model + * @api public + */ + +Model.discriminators; + +/** + * Removes documents from the collection. + * + * ####Example: + * + * Comment.remove({ title: 'baby born from alien father' }, function (err) { + * + * }); + * + * ####Note: + * + * To remove documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js): + * + * var query = Comment.remove({ _id: id }); + * query.exec(); + * + * ####Note: + * + * This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, _no middleware (hooks) are executed_. + * + * @param {Object} conditions + * @param {Function} [callback] + * @return {Promise} Promise + * @api public + */ + +Model.remove = function remove(conditions, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + + // get the mongodb collection object + var mq = new Query(conditions, {}, this, this.collection); + + return mq.remove(callback); +}; + +/** + * Finds documents + * + * The `conditions` are cast to their respective SchemaTypes before the command is sent. + * + * ####Examples: + * + * // named john and at least 18 + * MyModel.find({ name: 'john', age: { $gte: 18 }}); + * + * // executes immediately, passing results to callback + * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); + * + * // name LIKE john and only selecting the "name" and "friends" fields, executing immediately + * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) + * + * // passing options + * MyModel.find({ name: /john/i }, null, { skip: 10 }) + * + * // passing options and executing immediately + * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); + * + * // executing a query explicitly + * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }) + * query.exec(function (err, docs) {}); + * + * // using the promise returned from executing a query + * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }); + * var promise = query.exec(); + * promise.addBack(function (err, docs) {}); + * + * @param {Object} conditions + * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo) + * @param {Object} [options] optional + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see promise #promise-js + * @api public + */ + +Model.find = function find(conditions, projection, options, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + projection = null; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + projection = null; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } + + // get the raw mongodb collection object + var mq = new Query({}, {}, this, this.collection); + mq.select(projection); + mq.setOptions(options); + if (this.schema.discriminatorMapping && mq.selectedInclusively()) { + mq.select(this.schema.options.discriminatorKey); + } + + return mq.find(conditions, callback); +}; + +/** + * Finds a single document by its _id field. `findById(id)` is almost* + * equivalent to `findOne({ _id: id })`. + * + * The `id` is cast based on the Schema before sending the command. + * + * Note: `findById()` triggers `findOne` hooks. + * + * * Except for how it treats `undefined`. Because the MongoDB driver + * deletes keys that have value `undefined`, `findById(undefined)` gets + * translated to `findById({ _id: null })`. + * + * ####Example: + * + * // find adventure by id and execute immediately + * Adventure.findById(id, function (err, adventure) {}); + * + * // same as above + * Adventure.findById(id).exec(callback); + * + * // select only the adventures name and length + * Adventure.findById(id, 'name length', function (err, adventure) {}); + * + * // same as above + * Adventure.findById(id, 'name length').exec(callback); + * + * // include all properties except for `length` + * Adventure.findById(id, '-length').exec(function (err, adventure) {}); + * + * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean` + * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {}); + * + * // same as above + * Adventure.findById(id, 'name').lean().exec(function (err, doc) {}); + * + * @param {Object|String|Number} id value of `_id` to query by + * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo) + * @param {Object} [options] optional + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see lean queries #query_Query-lean + * @api public + */ + +Model.findById = function findById(id, projection, options, callback) { + if (typeof id === 'undefined') { + id = null; + } + return this.findOne({_id: id}, projection, options, callback); +}; + +/** + * Finds one document. + * + * The `conditions` are cast to their respective SchemaTypes before the command is sent. + * + * ####Example: + * + * // find one iphone adventures - iphone adventures?? + * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {}); + * + * // same as above + * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); + * + * // select only the adventures name + * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); + * + * // same as above + * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); + * + * // specify options, in this case lean + * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback); + * + * // same as above + * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback); + * + * // chaining findOne queries (same as above) + * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback); + * + * @param {Object} [conditions] + * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo) + * @param {Object} [options] optional + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see lean queries #query_Query-lean + * @api public + */ + +Model.findOne = function findOne(conditions, projection, options, callback) { + if (typeof options === 'function') { + callback = options; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + projection = null; + options = null; + } else if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + projection = null; + options = null; + } + + // get the mongodb collection object + var mq = new Query({}, {}, this, this.collection); + mq.select(projection); + mq.setOptions(options); + if (this.schema.discriminatorMapping && mq.selectedInclusively()) { + mq.select(this.schema.options.discriminatorKey); + } + + return mq.findOne(conditions, callback); +}; + +/** + * Counts number of matching documents in a database collection. + * + * ####Example: + * + * Adventure.count({ type: 'jungle' }, function (err, count) { + * if (err) .. + * console.log('there are %d jungle adventures', count); + * }); + * + * @param {Object} conditions + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.count = function count(conditions, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + + // get the mongodb collection object + var mq = new Query({}, {}, this, this.collection); + + return mq.count(conditions, callback); +}; + +/** + * Creates a Query for a `distinct` operation. + * + * Passing a `callback` immediately executes the query. + * + * ####Example + * + * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { + * if (err) return handleError(err); + * + * assert(Array.isArray(result)); + * console.log('unique urls with more than 100 clicks', result); + * }) + * + * var query = Link.distinct('url'); + * query.exec(callback); + * + * @param {String} field + * @param {Object} [conditions] optional + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.distinct = function distinct(field, conditions, callback) { + // get the mongodb collection object + var mq = new Query({}, {}, this, this.collection); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + + return mq.distinct(field, conditions, callback); +}; + +/** + * Creates a Query, applies the passed conditions, and returns the Query. + * + * For example, instead of writing: + * + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * we can instead write: + * + * User.where('age').gte(21).lte(65).exec(callback); + * + * Since the Query class also supports `where` you can continue chaining + * + * User + * .where('age').gte(21).lte(65) + * .where('name', /^b/i) + * ... etc + * + * @param {String} path + * @param {Object} [val] optional value + * @return {Query} + * @api public + */ + +Model.where = function where(path, val) { + void val; // eslint + // get the mongodb collection object + var mq = new Query({}, {}, this, this.collection).find({}); + return mq.where.apply(mq, arguments); +}; + +/** + * Creates a `Query` and specifies a `$where` condition. + * + * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. + * + * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {}); + * + * @param {String|Function} argument is a javascript string or anonymous function + * @method $where + * @memberOf Model + * @return {Query} + * @see Query.$where #query_Query-%24where + * @api public + */ + +Model.$where = function $where() { + var mq = new Query({}, {}, this, this.collection).find({}); + return mq.$where.apply(mq, arguments); +}; + +/** + * Issues a mongodb findAndModify update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned. + * + * ####Options: + * + * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * + * ####Examples: + * + * A.findOneAndUpdate(conditions, update, options, callback) // executes + * A.findOneAndUpdate(conditions, update, options) // returns Query + * A.findOneAndUpdate(conditions, update, callback) // executes + * A.findOneAndUpdate(conditions, update) // returns Query + * A.findOneAndUpdate() // returns Query + * + * ####Note: + * + * All top level update keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * var query = { name: 'borne' }; + * Model.findOneAndUpdate(query, { name: 'jason borne' }, options, callback) + * + * // is sent as + * Model.findOneAndUpdate(query, { $set: { name: 'jason borne' }}, options, callback) + * + * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`. + * + * ####Note: + * + * Values are cast to their appropriate types when using the findAndModify helpers. + * However, the below are never executed. + * + * - defaults + * - setters + * + * `findAndModify` helpers support limited defaults and validation. You can + * enable these by setting the `setDefaultsOnInsert` and `runValidators` options, + * respectively. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason borne'; + * doc.save(callback); + * }); + * + * @param {Object} [conditions] + * @param {Object} [update] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Model.findOneAndUpdate = function(conditions, update, options, callback) { + if (typeof options === 'function') { + callback = options; + options = null; + } else if (arguments.length === 1) { + if (typeof conditions === 'function') { + var msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n' + + ' ' + this.modelName + '.findOneAndUpdate(update)\n' + + ' ' + this.modelName + '.findOneAndUpdate()\n'; + throw new TypeError(msg); + } + update = conditions; + conditions = undefined; + } + + var fields; + if (options && options.fields) { + fields = options.fields; + options.fields = undefined; + } + + update = utils.clone(update, {depopulate: 1}); + if (this.schema.options.versionKey && options && options.upsert) { + if (!update.$setOnInsert) { + update.$setOnInsert = {}; + } + update.$setOnInsert[this.schema.options.versionKey] = 0; + } + + var mq = new Query({}, {}, this, this.collection); + mq.select(fields); + + return mq.findOneAndUpdate(conditions, update, options, callback); +}; + +/** + * Issues a mongodb findAndModify update command by a document's _id field. + * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`. + * + * Finds a matching document, updates it according to the `update` arg, + * passing any `options`, and returns the found document (if any) to the + * callback. The query executes immediately if `callback` is passed else a + * Query object is returned. + * + * This function triggers `findOneAndUpdate` middleware. + * + * ####Options: + * + * - `new`: bool - true to return the modified document rather than the original. defaults to false + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * + * ####Examples: + * + * A.findByIdAndUpdate(id, update, options, callback) // executes + * A.findByIdAndUpdate(id, update, options) // returns Query + * A.findByIdAndUpdate(id, update, callback) // executes + * A.findByIdAndUpdate(id, update) // returns Query + * A.findByIdAndUpdate() // returns Query + * + * ####Note: + * + * All top level update keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * Model.findByIdAndUpdate(id, { name: 'jason borne' }, options, callback) + * + * // is sent as + * Model.findByIdAndUpdate(id, { $set: { name: 'jason borne' }}, options, callback) + * + * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`. + * + * ####Note: + * + * Values are cast to their appropriate types when using the findAndModify helpers. + * However, the below are never executed. + * + * - defaults + * - setters + * + * `findAndModify` helpers support limited defaults and validation. You can + * enable these by setting the `setDefaultsOnInsert` and `runValidators` options, + * respectively. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason borne'; + * doc.save(callback); + * }); + * + * @param {Object|Number|String} id value of `_id` to query by + * @param {Object} [update] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Model.findByIdAndUpdate = function(id, update, options, callback) { + if (arguments.length === 1) { + if (typeof id === 'function') { + var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' + + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' + + ' ' + this.modelName + '.findByIdAndUpdate()\n'; + throw new TypeError(msg); + } + return this.findOneAndUpdate({_id: id}, undefined); + } + + // if a model is passed in instead of an id + if (id instanceof Document) { + id = id._id; + } + + return this.findOneAndUpdate.call(this, {_id: id}, update, options, callback); +}; + +/** + * Issue a mongodb findAndModify remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * + * Executes immediately if `callback` is passed else a Query object is returned. + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * + * ####Examples: + * + * A.findOneAndRemove(conditions, options, callback) // executes + * A.findOneAndRemove(conditions, options) // return Query + * A.findOneAndRemove(conditions, callback) // executes + * A.findOneAndRemove(conditions) // returns Query + * A.findOneAndRemove() // returns Query + * + * Values are cast to their appropriate types when using the findAndModify helpers. + * However, the below are never executed. + * + * - defaults + * - setters + * + * `findAndModify` helpers support limited defaults and validation. You can + * enable these by setting the `setDefaultsOnInsert` and `runValidators` options, + * respectively. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason borne'; + * doc.save(callback); + * }); + * + * @param {Object} conditions + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Model.findOneAndRemove = function(conditions, options, callback) { + if (arguments.length === 1 && typeof conditions === 'function') { + var msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' + + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' + + ' ' + this.modelName + '.findOneAndRemove()\n'; + throw new TypeError(msg); + } + + if (typeof options === 'function') { + callback = options; + options = undefined; + } + + var fields; + if (options) { + fields = options.select; + options.select = undefined; + } + + var mq = new Query({}, {}, this, this.collection); + mq.select(fields); + + return mq.findOneAndRemove(conditions, options, callback); +}; + +/** + * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * + * Executes immediately if `callback` is passed, else a `Query` object is returned. + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * + * ####Examples: + * + * A.findByIdAndRemove(id, options, callback) // executes + * A.findByIdAndRemove(id, options) // return Query + * A.findByIdAndRemove(id, callback) // executes + * A.findByIdAndRemove(id) // returns Query + * A.findByIdAndRemove() // returns Query + * + * @param {Object|Number|String} id value of `_id` to query by + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @see Model.findOneAndRemove #model_Model.findOneAndRemove + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + */ + +Model.findByIdAndRemove = function(id, options, callback) { + if (arguments.length === 1 && typeof id === 'function') { + var msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' + + ' ' + this.modelName + '.findByIdAndRemove(id)\n' + + ' ' + this.modelName + '.findByIdAndRemove()\n'; + throw new TypeError(msg); + } + + return this.findOneAndRemove({_id: id}, options, callback); +}; + +/** + * Shortcut for creating a new Document that is automatically saved to the db + * if valid. + * + * ####Example: + * + * // pass individual docs + * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) { + * if (err) // ... + * }); + * + * // pass an array + * var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; + * Candy.create(array, function (err, candies) { + * if (err) // ... + * + * var jellybean = candies[0]; + * var snickers = candies[1]; + * // ... + * }); + * + * // callback is optional; use the returned promise if you like: + * var promise = Candy.create({ type: 'jawbreaker' }); + * promise.then(function (jawbreaker) { + * // ... + * }) + * + * @param {Array|Object|*} doc(s) + * @param {Function} [callback] callback + * @return {Promise} + * @api public + */ + +Model.create = function create(doc, callback) { + var args, + cb; + + if (Array.isArray(doc)) { + args = doc; + cb = callback; + } else { + var last = arguments[arguments.length - 1]; + if (typeof last === 'function') { + cb = last; + args = utils.args(arguments, 0, arguments.length - 1); + } else { + args = utils.args(arguments); + } + } + + var Promise = PromiseProvider.get(); + var _this = this; + + var promise = new Promise.ES6(function(resolve, reject) { + if (args.length === 0) { + process.nextTick(function() { + cb && cb(null); + resolve(null); + }); + return; + } + + var toExecute = []; + args.forEach(function(doc) { + toExecute.push(function(callback) { + var toSave = new _this(doc); + var callbackWrapper = function(error, doc) { + if (error) { + return callback(error); + } + callback(null, doc); + }; + + // Hack to avoid getting a promise because of + // $__registerHooksFromSchema + if (toSave.$__original_save) { + toSave.$__original_save({__noPromise: true}, callbackWrapper); + } else { + toSave.save({__noPromise: true}, callbackWrapper); + } + }); + }); + + async.parallel(toExecute, function(error, savedDocs) { + if (error) { + cb && cb(error); + reject(error); + return; + } + + if (doc instanceof Array) { + resolve(savedDocs); + cb && cb.call(_this, null, savedDocs); + } else { + resolve.apply(promise, savedDocs); + if (cb) { + savedDocs.unshift(null); + cb.apply(_this, savedDocs); + } + } + }); + }); + + return promise; +}; + +/** + * Shortcut for validating an array of documents and inserting them into + * MongoDB if they're all valid. This function is faster than `.create()` + * because it only sends one operation to the server, rather than one for each + * document. + * + * This function does **not** trigger save middleware. + * + * ####Example: + * + * var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }]; + * Movies.insertMany(arr, function(error, docs) {}); + * + * @param {Array|Object|*} doc(s) + * @param {Function} [callback] callback + * @return {Promise} + * @api public + */ + +Model.insertMany = function(arr, callback) { + var _this = this; + var Promise = PromiseProvider.get(); + + return new Promise.ES6(function(resolve, reject) { + var toExecute = []; + arr.forEach(function(doc) { + toExecute.push(function(callback) { + doc = new _this(doc); + doc.validate({__noPromise: true}, function(error) { + if (error) { + return callback(error); + } + callback(null, doc); + }); + }); + }); + + async.parallel(toExecute, function(error, docs) { + if (error) { + reject(error); + callback && callback(error); + return; + } + var docObjects = docs.map(function(doc) { + return doc.toObject({virtuals: false}); + }); + _this.collection.insertMany(docObjects, function(error) { + if (error) { + reject(error); + callback && callback(error); + return; + } + resolve(docs); + callback && callback(null, docs); + }); + }); + }); +}; + +/** + * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. + * The document returned has no paths marked as modified initially. + * + * ####Example: + * + * // hydrate previous data into a Mongoose document + * var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' }); + * + * @param {Object} obj + * @return {Document} + * @api public + */ + +Model.hydrate = function(obj) { + var model = require('./queryhelpers').createModel(this, obj); + model.init(obj); + return model; +}; + +/** + * Updates documents in the database without returning them. + * + * ####Examples: + * + * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); + * MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, raw) { + * if (err) return handleError(err); + * console.log('The raw response from Mongo was ', raw); + * }); + * + * ####Valid options: + * + * - `safe` (boolean) safe mode (defaults to value set in schema (true)) + * - `upsert` (boolean) whether to create the doc if it doesn't match (false) + * - `multi` (boolean) whether multiple documents should be updated (false) + * - `strict` (boolean) overrides the `strict` option for this update + * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false) + * + * All `update` values are cast to their appropriate SchemaTypes before being sent. + * + * The `callback` function receives `(err, rawResponse)`. + * + * - `err` is the error if any occurred + * - `rawResponse` is the full response from Mongo + * + * ####Note: + * + * All top level keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * var query = { name: 'borne' }; + * Model.update(query, { name: 'jason borne' }, options, callback) + * + * // is sent as + * Model.update(query, { $set: { name: 'jason borne' }}, options, callback) + * // if overwrite option is false. If overwrite is true, sent without the $set wrapper. + * + * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason borne' }`. + * + * ####Note: + * + * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. + * + * ####Note: + * + * To update documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js): + * + * Comment.update({ _id: id }, { $set: { text: 'changed' }}).exec(); + * + * ####Note: + * + * Although values are casted to their appropriate types when using update, the following are *not* applied: + * + * - defaults + * - setters + * - validators + * - middleware + * + * If you need those features, use the traditional approach of first retrieving the document. + * + * Model.findOne({ name: 'borne' }, function (err, doc) { + * if (err) .. + * doc.name = 'jason borne'; + * doc.save(callback); + * }) + * + * @see strict http://mongoosejs.com/docs/guide.html#strict + * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output + * @param {Object} conditions + * @param {Object} doc + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.update = function update(conditions, doc, options, callback) { + var mq = new Query({}, {}, this, this.collection); + // gh-2406 + // make local deep copy of conditions + if (conditions instanceof Document) { + conditions = conditions.toObject(); + } else { + conditions = utils.clone(conditions, {retainKeyOrder: true}); + } + options = typeof options === 'function' ? options : utils.clone(options); + + return mq.update(conditions, doc, options, callback); +}; + +/** + * Executes a mapReduce command. + * + * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options. + * + * ####Example: + * + * var o = {}; + * o.map = function () { emit(this.name, 1) } + * o.reduce = function (k, vals) { return vals.length } + * User.mapReduce(o, function (err, results) { + * console.log(results) + * }) + * + * ####Other options: + * + * - `query` {Object} query filter object. + * - `sort` {Object} sort input objects using this key + * - `limit` {Number} max number of documents + * - `keeptemp` {Boolean, default:false} keep temporary data + * - `finalize` {Function} finalize function + * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution + * - `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} + * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. + * + * ####* out options: + * + * - `{inline:1}` the results are returned in an array + * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection + * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions + * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old + * + * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the `lean` option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). + * + * ####Example: + * + * var o = {}; + * o.map = function () { emit(this.name, 1) } + * o.reduce = function (k, vals) { return vals.length } + * o.out = { replace: 'createdCollectionNameForResults' } + * o.verbose = true; + * + * User.mapReduce(o, function (err, model, stats) { + * console.log('map reduce took %d ms', stats.processtime) + * model.find().where('value').gt(10).exec(function (err, docs) { + * console.log(docs); + * }); + * }) + * + * // a promise is returned so you may instead write + * var promise = User.mapReduce(o); + * promise.then(function (model, stats) { + * console.log('map reduce took %d ms', stats.processtime) + * return model.find().where('value').gt(10).exec(); + * }).then(function (docs) { + * console.log(docs); + * }).then(null, handleError).end() + * + * @param {Object} o an object specifying map-reduce options + * @param {Function} [callback] optional callback + * @see http://www.mongodb.org/display/DOCS/MapReduce + * @return {Promise} + * @api public + */ + +Model.mapReduce = function mapReduce(o, callback) { + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + if (!Model.mapReduce.schema) { + var opts = {noId: true, noVirtualId: true, strict: false}; + Model.mapReduce.schema = new Schema({}, opts); + } + + if (!o.out) o.out = {inline: 1}; + if (o.verbose !== false) o.verbose = true; + + o.map = String(o.map); + o.reduce = String(o.reduce); + + if (o.query) { + var q = new Query(o.query); + q.cast(_this); + o.query = q._conditions; + q = undefined; + } + + _this.collection.mapReduce(null, null, o, function(err, ret, stats) { + if (err) { + callback && callback(err); + reject(err); + return; + } + + if (ret.findOne && ret.mapReduce) { + // returned a collection, convert to Model + var model = Model.compile( + '_mapreduce_' + ret.collectionName + , Model.mapReduce.schema + , ret.collectionName + , _this.db + , _this.base); + + model._mapreduce = true; + + callback && callback(null, model, stats); + return resolve(model, stats); + } + + callback && callback(null, ret, stats); + resolve(ret, stats); + }); + }); +}; + +/** + * geoNear support for Mongoose + * + * ####Options: + * - `lean` {Boolean} return the raw object + * - All options supported by the driver are also supported + * + * ####Example: + * + * // Legacy point + * Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) { + * console.log(results); + * }); + * + * // geoJson + * var point = { type : "Point", coordinates : [9,9] }; + * Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) { + * console.log(results); + * }); + * + * @param {Object|Array} GeoJSON point or legacy coordinate pair [x,y] to search near + * @param {Object} options for the qurery + * @param {Function} [callback] optional callback for the query + * @return {Promise} + * @see http://docs.mongodb.org/manual/core/2dsphere/ + * @see http://mongodb.github.io/node-mongodb-native/api-generated/collection.html?highlight=geonear#geoNear + * @api public + */ + +Model.geoNear = function(near, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var _this = this; + var Promise = PromiseProvider.get(); + if (!near) { + return new Promise.ES6(function(resolve, reject) { + var error = new Error('Must pass a near option to geoNear'); + reject(error); + callback && callback(error); + }); + } + + var x, y; + + return new Promise.ES6(function(resolve, reject) { + var handler = function(err, res) { + if (err) { + reject(err); + callback && callback(err); + return; + } + if (options.lean) { + resolve(res.results, res.stats); + callback && callback(null, res.results, res.stats); + return; + } + + var count = res.results.length; + // if there are no results, fulfill the promise now + if (count === 0) { + resolve(res.results, res.stats); + callback && callback(null, res.results, res.stats); + return; + } + + var errSeen = false; + + function init(err) { + if (err && !errSeen) { + errSeen = true; + reject(err); + callback && callback(err); + return; + } + if (--count <= 0) { + resolve(res.results, res.stats); + callback && callback(null, res.results, res.stats); + } + } + + for (var i = 0; i < res.results.length; i++) { + var temp = res.results[i].obj; + res.results[i].obj = new _this(); + res.results[i].obj.init(temp, init); + } + }; + + if (Array.isArray(near)) { + if (near.length !== 2) { + var error = new Error('If using legacy coordinates, must be an array ' + + 'of size 2 for geoNear'); + reject(error); + callback && callback(error); + return; + } + x = near[0]; + y = near[1]; + _this.collection.geoNear(x, y, options, handler); + } else { + if (near.type !== 'Point' || !Array.isArray(near.coordinates)) { + error = new Error('Must pass either a legacy coordinate array or ' + + 'GeoJSON Point to geoNear'); + reject(error); + callback && callback(error); + return; + } + + _this.collection.geoNear(near, options, handler); + } + }); +}; + +/** + * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. + * + * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. + * + * ####Example: + * + * // Find the max balance of all accounts + * Users.aggregate( + * { $group: { _id: null, maxBalance: { $max: '$balance' }}} + * , { $project: { _id: 0, maxBalance: 1 }} + * , function (err, res) { + * if (err) return handleError(err); + * console.log(res); // [ { maxBalance: 98000 } ] + * }); + * + * // Or use the aggregation pipeline builder. + * Users.aggregate() + * .group({ _id: null, maxBalance: { $max: '$balance' } }) + * .select('-id maxBalance') + * .exec(function (err, res) { + * if (err) return handleError(err); + * console.log(res); // [ { maxBalance: 98 } ] + * }); + * + * ####NOTE: + * + * - Arguments are not cast to the model's schema because `$project` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. + * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). + * - Requires MongoDB >= 2.1 + * + * @see Aggregate #aggregate_Aggregate + * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ + * @param {Object|Array} [...] aggregation pipeline operator(s) or operator array + * @param {Function} [callback] + * @return {Aggregate|Promise} + * @api public + */ + +Model.aggregate = function aggregate() { + var args = [].slice.call(arguments), + aggregate, + callback; + + if (typeof args[args.length - 1] === 'function') { + callback = args.pop(); + } + + if (args.length === 1 && util.isArray(args[0])) { + aggregate = new Aggregate(args[0]); + } else { + aggregate = new Aggregate(args); + } + + aggregate.model(this); + + if (typeof callback === 'undefined') { + return aggregate; + } + + return aggregate.exec(callback); +}; + +/** + * Implements `$geoSearch` functionality for Mongoose + * + * ####Example: + * + * var options = { near: [10, 10], maxDistance: 5 }; + * Locations.geoSearch({ type : "house" }, options, function(err, res) { + * console.log(res); + * }); + * + * ####Options: + * - `near` {Array} x,y point to search for + * - `maxDistance` {Number} the maximum distance from the point near that a result can be + * - `limit` {Number} The maximum number of results to return + * - `lean` {Boolean} return the raw object instead of the Mongoose Model + * + * @param {Object} conditions an object that specifies the match condition (required) + * @param {Object} options for the geoSearch, some (near, maxDistance) are required + * @param {Function} [callback] optional callback + * @return {Promise} + * @see http://docs.mongodb.org/manual/reference/command/geoSearch/ + * @see http://docs.mongodb.org/manual/core/geohaystack/ + * @api public + */ + +Model.geoSearch = function(conditions, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + var error; + if (conditions === undefined || !utils.isObject(conditions)) { + error = new Error('Must pass conditions to geoSearch'); + } else if (!options.near) { + error = new Error('Must specify the near option in geoSearch'); + } else if (!Array.isArray(options.near)) { + error = new Error('near option must be an array [x, y]'); + } + + if (error) { + callback && callback(error); + reject(error); + return; + } + + // send the conditions in the options object + options.search = conditions; + + _this.collection.geoHaystackSearch(options.near[0], options.near[1], options, function(err, res) { + // have to deal with driver problem. Should be fixed in a soon-ish release + // (7/8/2013) + if (err) { + callback && callback(err); + reject(err); + return; + } + + var count = res.results.length; + if (options.lean || count === 0) { + callback && callback(null, res.results, res.stats); + resolve(res.results, res.stats); + return; + } + + var errSeen = false; + + function init(err) { + if (err && !errSeen) { + callback && callback(err); + reject(err); + return; + } + + if (!--count && !errSeen) { + callback && callback(null, res.results, res.stats); + resolve(res.results, res.stats); + } + } + + for (var i = 0; i < res.results.length; i++) { + var temp = res.results[i]; + res.results[i] = new _this(); + res.results[i].init(temp, {}, init); + } + }); + }); +}; + +/** + * Populates document references. + * + * ####Available options: + * + * - path: space delimited path(s) to populate + * - select: optional fields to select + * - match: optional query conditions to match + * - model: optional name of the model to use for population + * - options: optional query options like sort, limit, etc + * + * ####Examples: + * + * // populates a single object + * User.findById(id, function (err, user) { + * var opts = [ + * { path: 'company', match: { x: 1 }, select: 'name' } + * , { path: 'notes', options: { limit: 10 }, model: 'override' } + * ] + * + * User.populate(user, opts, function (err, user) { + * console.log(user); + * }) + * }) + * + * // populates an array of objects + * User.find(match, function (err, users) { + * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }] + * + * var promise = User.populate(users, opts); + * promise.then(console.log).end(); + * }) + * + * // imagine a Weapon model exists with two saved documents: + * // { _id: 389, name: 'whip' } + * // { _id: 8921, name: 'boomerang' } + * + * var user = { name: 'Indiana Jones', weapon: 389 } + * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) { + * console.log(user.weapon.name) // whip + * }) + * + * // populate many plain objects + * var users = [{ name: 'Indiana Jones', weapon: 389 }] + * users.push({ name: 'Batman', weapon: 8921 }) + * Weapon.populate(users, { path: 'weapon' }, function (err, users) { + * users.forEach(function (user) { + * console.log('%s uses a %s', users.name, user.weapon.name) + * // Indiana Jones uses a whip + * // Batman uses a boomerang + * }) + * }) + * // Note that we didn't need to specify the Weapon model because + * // we were already using it's populate() method. + * + * @param {Document|Array} docs Either a single document or array of documents to populate. + * @param {Object} options A hash of key/val (path, options) used for population. + * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. + * @return {Promise} + * @api public + */ + +Model.populate = function(docs, paths, cb) { + var _this = this; + + // normalized paths + var noPromise = paths && !!paths.__noPromise; + paths = utils.populate(paths); + + if (noPromise) { + _populate(this, docs, paths, cb); + } else { + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _populate(_this, docs, paths, function(error, docs) { + if (error) { + cb && cb(error); + reject(error); + } else { + cb && cb(null, docs); + resolve(docs); + } + }); + }); + } +}; + +/*! + * Populate helper + * + * @param {Model} model the model to use + * @param {Document|Array} docs Either a single document or array of documents to populate. + * @param {Object} paths + * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. + * @return {Function} + * @api private + */ + +function _populate(model, docs, paths, cb) { + var pending = paths.length; + + if (pending === 0) { + return cb(null, docs); + } + + // each path has its own query options and must be executed separately + var i = pending; + var path; + while (i--) { + path = paths[i]; + if (typeof path.model === 'function') { + model = path.model; + } + populate(model, docs, path, subPopulate.call(model, docs, path, next)); + } + + function next(err) { + if (err) { + return cb(err); + } + if (--pending) { + return; + } + cb(null, docs); + } +} + +/*! + * Populates deeply if `populate` option is present. + * + * @param {Document|Array} docs + * @param {Object} options + * @param {Function} cb + * @return {Function} + * @api private + */ +function subPopulate(docs, options, cb) { + var _this = this; + var prefix = options.path + '.'; + var pop = options.populate; + + if (!pop) { + return cb; + } + + // normalize as array + if (!Array.isArray(pop)) { + pop = [pop]; + } + + return function(err) { + var pending = pop.length; + + function next(err) { + if (err) return cb(err); + if (--pending) return; + cb(); + } + + if (err || !pending) return cb(err); + + pop.forEach(function(subOptions) { + subOptions = utils.clone(subOptions); + // path needs parent's path prefixed to it + if (!subOptions._originalPath) { + subOptions._originalPath = subOptions.path; + subOptions.path = prefix + subOptions.path; + } + + var schema = _this.schema._getSchema(prefix); + if (typeof subOptions.model === 'string') { + subOptions.model = _this.model(subOptions.model); + } else if (schema && schema.caster && schema.caster.options && + schema.caster.options.ref) { + var subSchema = _this.model(schema.caster.options.ref).schema. + _getSchema(subOptions._originalPath); + if (subSchema && subSchema.options && subSchema.options.ref) { + subOptions.model = _this.model(subSchema.options.ref); + } + } + Model.populate.call(subOptions.model || _this, docs, subOptions, next); + }); + }; +} + +/*! + * Populates `docs` + */ +var excludeIdReg = /\s?-_id\s?/, + excludeIdRegGlobal = /\s?-_id\s?/g; + +function populate(model, docs, options, cb) { + var modelsMap, rawIds; + + // normalize single / multiple docs passed + if (!Array.isArray(docs)) { + docs = [docs]; + } + + if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) { + return cb(); + } + + modelsMap = getModelsMapForPopulate(model, docs, options); + rawIds = getIdsForAndAddIdsInMapPopulate(modelsMap); + + var i, len = modelsMap.length, + mod, match, select, promise, vals = []; + + promise = new Promise(function(err, vals, options, assignmentOpts) { + if (err) return cb(err); + + var lean = options.options && options.options.lean, + len = vals.length, + rawOrder = {}, rawDocs = {}, key, val; + + // optimization: + // record the document positions as returned by + // the query result. + for (var i = 0; i < len; i++) { + val = vals[i]; + key = String(utils.getValue('_id', val)); + rawDocs[key] = val; + rawOrder[key] = i; + + // flag each as result of population + if (!lean) val.$__.wasPopulated = true; + } + + assignVals({ + rawIds: rawIds, + rawDocs: rawDocs, + rawOrder: rawOrder, + docs: docs, + path: options.path, + options: assignmentOpts + }); + cb(); + }); + + function flatten(item) { + // no need to include undefined values in our query + return undefined !== item; + } + + var _remaining = len; + for (i = 0; i < len; i++) { + mod = modelsMap[i]; + select = mod.options.select; + + if (mod.options.match) { + match = utils.object.shallowCopy(mod.options.match); + } else { + match = {}; + } + + var ids = utils.array.flatten(mod.ids, flatten); + + ids = utils.array.unique(ids); + + if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) { + return cb(); + } + + match._id || (match._id = { + $in: ids + }); + + var assignmentOpts = {}; + assignmentOpts.sort = mod.options.options && mod.options.options.sort || undefined; + assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0); + + if (assignmentOpts.excludeId) { + // override the exclusion from the query so we can use the _id + // for document matching during assignment. we'll delete the + // _id back off before returning the result. + if (typeof select === 'string') { + select = select.replace(excludeIdRegGlobal, ' '); + } else { + // preserve original select conditions by copying + select = utils.object.shallowCopy(select); + delete select._id; + } + } + + if (mod.options.options && mod.options.options.limit) { + assignmentOpts.originalLimit = mod.options.options.limit; + mod.options.options.limit = mod.options.options.limit * ids.length; + } + + mod.Model.find(match, select, mod.options.options, next.bind(this, mod.options, assignmentOpts)); + } + + function next(options, assignmentOpts, err, valsFromDb) { + if (err) return promise.resolve(err); + vals = vals.concat(valsFromDb); + if (--_remaining === 0) { + promise.resolve(err, vals, options, assignmentOpts); + } + } +} + +function getModelsMapForPopulate(model, docs, options) { + var i, doc, len = docs.length, + available = {}, + map = [], + modelNameFromQuery = options.model && options.model.modelName || options.model, + schema, refPath, Model, currentOptions, modelNames, modelName, discriminatorKey, modelForFindSchema; + + schema = model._getSchema(options.path); + + if (schema && schema.caster) { + schema = schema.caster; + } + + if (!schema && model.discriminators) { + discriminatorKey = model.schema.discriminatorMapping.key; + } + + refPath = schema && schema.options && schema.options.refPath; + + for (i = 0; i < len; i++) { + doc = docs[i]; + + if (refPath) { + modelNames = utils.getValue(refPath, doc); + } else { + if (!modelNameFromQuery) { + var schemaForCurrentDoc; + + if (!schema && discriminatorKey) { + modelForFindSchema = utils.getValue(discriminatorKey, doc); + + if (modelForFindSchema) { + schemaForCurrentDoc = model.db.model(modelForFindSchema)._getSchema(options.path); + + if (schemaForCurrentDoc && schemaForCurrentDoc.caster) { + schemaForCurrentDoc = schemaForCurrentDoc.caster; + } + } + } else { + schemaForCurrentDoc = schema; + } + + modelNames = [ + schemaForCurrentDoc && schemaForCurrentDoc.options && schemaForCurrentDoc.options.ref // declared in schema + || model.modelName // an ad-hoc structure + ]; + } else { + modelNames = [modelNameFromQuery]; // query options + } + } + + if (!modelNames) { + continue; + } + + if (!Array.isArray(modelNames)) { + modelNames = [modelNames]; + } + + var k = modelNames.length; + while (k--) { + modelName = modelNames[k]; + if (!available[modelName]) { + Model = model.db.model(modelName); + currentOptions = { + model: Model + }; + + if (schema && !discriminatorKey) { + options.model = Model; + } + + utils.merge(currentOptions, options); + + available[modelName] = { + Model: Model, + options: currentOptions, + docs: [doc], + ids: [] + }; + map.push(available[modelName]); + } else { + available[modelName].docs.push(doc); + } + } + } + + return map; +} + +function getIdsForAndAddIdsInMapPopulate(modelsMap) { + var rawIds = [], // for the correct position + i, j, doc, docs, id, len, len2, ret, isDocument, options, path; + + len2 = modelsMap.length; + for (j = 0; j < len2; j++) { + docs = modelsMap[j].docs; + len = docs.length; + options = modelsMap[j].options; + path = options.path; + + for (i = 0; i < len; i++) { + ret = undefined; + doc = docs[i]; + id = String(utils.getValue('_id', doc)); + isDocument = !!doc.$__; + + if (!ret || Array.isArray(ret) && ret.length === 0) { + ret = utils.getValue(path, doc); + } + + if (ret) { + ret = convertTo_id(ret); + + options._docs[id] = Array.isArray(ret) ? ret.slice() : ret; + } + + rawIds.push(ret); + modelsMap[j].ids.push(ret); + + if (isDocument) { + // cache original populated _ids and model used + doc.populated(path, options._docs[id], options); + } + } + } + + return rawIds; +} + +/*! + * Retrieve the _id of `val` if a Document or Array of Documents. + * + * @param {Array|Document|Any} val + * @return {Array|Document|Any} + */ + +function convertTo_id(val) { + if (val instanceof Model) return val._id; + + if (Array.isArray(val)) { + for (var i = 0; i < val.length; ++i) { + if (val[i] instanceof Model) { + val[i] = val[i]._id; + } + } + return val; + } + + return val; +} + +/*! + * Assigns documents returned from a population query back + * to the original document path. + */ + +function assignVals(o) { + // replace the original ids in our intermediate _ids structure + // with the documents found by query + + assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, o.options); + + // now update the original documents being populated using the + // result structure that contains real documents. + + var docs = o.docs; + var path = o.path; + var rawIds = o.rawIds; + var options = o.options; + + function setValue(val) { + return valueFilter(val, options); + } + + for (var i = 0; i < docs.length; ++i) { + if (utils.getValue(path, docs[i]) == null) { + continue; + } + utils.setValue(path, rawIds[i], docs[i], setValue); + } +} + +/*! + * 1) Apply backwards compatible find/findOne behavior to sub documents + * + * find logic: + * a) filter out non-documents + * b) remove _id from sub docs when user specified + * + * findOne + * a) if no doc found, set to null + * b) remove _id from sub docs when user specified + * + * 2) Remove _ids when specified by users query. + * + * background: + * _ids are left in the query even when user excludes them so + * that population mapping can occur. + */ + +function valueFilter(val, assignmentOpts) { + if (Array.isArray(val)) { + // find logic + var ret = []; + var numValues = val.length; + for (var i = 0; i < numValues; ++i) { + var subdoc = val[i]; + if (!isDoc(subdoc)) continue; + maybeRemoveId(subdoc, assignmentOpts); + ret.push(subdoc); + if (assignmentOpts.originalLimit && + ret.length >= assignmentOpts.originalLimit) { + break; + } + } + + // Since we don't want to have to create a new mongoosearray, make sure to + // modify the array in place + while (val.length > ret.length) { + Array.prototype.pop.apply(val, []); + } + for (i = 0; i < ret.length; ++i) { + val[i] = ret[i]; + } + return val; + } + + // findOne + if (isDoc(val)) { + maybeRemoveId(val, assignmentOpts); + return val; + } + + return null; +} + +/*! + * Remove _id from `subdoc` if user specified "lean" query option + */ + +function maybeRemoveId(subdoc, assignmentOpts) { + if (assignmentOpts.excludeId) { + if (typeof subdoc.setValue === 'function') { + delete subdoc._doc._id; + } else { + delete subdoc._id; + } + } +} + +/*! + * Determine if `doc` is a document returned + * by a populate query. + */ + +function isDoc(doc) { + if (doc == null) { + return false; + } + + var type = typeof doc; + if (type === 'string') { + return false; + } + + if (type === 'number') { + return false; + } + + if (Buffer.isBuffer(doc)) { + return false; + } + + if (doc.constructor.name === 'ObjectID') { + return false; + } + + // only docs + return true; +} + +/*! + * Assign `vals` returned by mongo query to the `rawIds` + * structure returned from utils.getVals() honoring + * query sort order if specified by user. + * + * This can be optimized. + * + * Rules: + * + * if the value of the path is not an array, use findOne rules, else find. + * for findOne the results are assigned directly to doc path (including null results). + * for find, if user specified sort order, results are assigned directly + * else documents are put back in original order of array if found in results + * + * @param {Array} rawIds + * @param {Array} vals + * @param {Boolean} sort + * @api private + */ + +function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, recursed) { + // honor user specified sort order + var newOrder = []; + var sorting = options.sort && rawIds.length > 1; + var doc; + var sid; + var id; + + for (var i = 0; i < rawIds.length; ++i) { + id = rawIds[i]; + + if (Array.isArray(id)) { + // handle [ [id0, id2], [id3] ] + assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, true); + newOrder.push(id); + continue; + } + + if (id === null && !sorting) { + // keep nulls for findOne unless sorting, which always + // removes them (backward compat) + newOrder.push(id); + continue; + } + + sid = String(id); + + if (recursed) { + // apply find behavior + + // assign matching documents in original order unless sorting + doc = resultDocs[sid]; + if (doc) { + if (sorting) { + newOrder[resultOrder[sid]] = doc; + } else { + newOrder.push(doc); + } + } else { + newOrder.push(id); + } + } else { + // apply findOne behavior - if document in results, assign, else assign null + newOrder[i] = doc = resultDocs[sid] || null; + } + } + + rawIds.length = 0; + if (newOrder.length) { + // reassign the documents based on corrected order + + // forEach skips over sparse entries in arrays so we + // can safely use this to our advantage dealing with sorted + // result sets too. + newOrder.forEach(function(doc, i) { + rawIds[i] = doc; + }); + } +} + +/** + * Finds the schema for `path`. This is different than + * calling `schema.path` as it also resolves paths with + * positional selectors (something.$.another.$.path). + * + * @param {String} path + * @return {Schema} + * @api private + */ + +Model._getSchema = function _getSchema(path) { + return this.schema._getSchema(path); +}; + +/*! + * Compiler utility. + * + * @param {String} name model name + * @param {Schema} schema + * @param {String} collectionName + * @param {Connection} connection + * @param {Mongoose} base mongoose instance + */ + +Model.compile = function compile(name, schema, collectionName, connection, base) { + var versioningEnabled = schema.options.versionKey !== false; + + if (versioningEnabled && !schema.paths[schema.options.versionKey]) { + // add versioning to top level documents only + var o = {}; + o[schema.options.versionKey] = Number; + schema.add(o); + } + + // generate new class + function model(doc, fields, skipId) { + if (!(this instanceof model)) { + return new model(doc, fields, skipId); + } + Model.call(this, doc, fields, skipId); + } + + model.hooks = schema.s.hooks.clone(); + model.base = base; + model.modelName = name; + model.__proto__ = Model; + model.prototype.__proto__ = Model.prototype; + model.model = Model.prototype.model; + model.db = model.prototype.db = connection; + model.discriminators = model.prototype.discriminators = undefined; + + model.prototype.$__setSchema(schema); + + var collectionOptions = { + bufferCommands: schema.options.bufferCommands, + capped: schema.options.capped + }; + + model.prototype.collection = connection.collection( + collectionName + , collectionOptions + ); + + // apply methods and statics + applyMethods(model, schema); + applyStatics(model, schema); + + model.schema = model.prototype.schema; + model.collection = model.prototype.collection; + + return model; +}; + +/*! + * Register methods for this model + * + * @param {Model} model + * @param {Schema} schema + */ +var applyMethods = function(model, schema) { + function apply(method, schema) { + Object.defineProperty(model.prototype, method, { + get: function() { + var h = {}; + for (var k in schema.methods[method]) { + h[k] = schema.methods[method][k].bind(this); + } + return h; + }, + configurable: true + }); + } + for (var method in schema.methods) { + if (typeof schema.methods[method] === 'function') { + model.prototype[method] = schema.methods[method]; + } else { + apply(method, schema); + } + } +}; + +/*! + * Register statics for this model + * @param {Model} model + * @param {Schema} schema + */ +var applyStatics = function(model, schema) { + for (var i in schema.statics) { + model[i] = schema.statics[i]; + } +}; + +/*! + * Subclass this model with `conn`, `schema`, and `collection` settings. + * + * @param {Connection} conn + * @param {Schema} [schema] + * @param {String} [collection] + * @return {Model} + */ + +Model.__subclass = function subclass(conn, schema, collection) { + // subclass model using this connection and collection name + var _this = this; + + var Model = function Model(doc, fields, skipId) { + if (!(this instanceof Model)) { + return new Model(doc, fields, skipId); + } + _this.call(this, doc, fields, skipId); + }; + + Model.__proto__ = _this; + Model.prototype.__proto__ = _this.prototype; + Model.db = Model.prototype.db = conn; + + var s = schema && typeof schema !== 'string' + ? schema + : _this.prototype.schema; + + var options = s.options || {}; + + if (!collection) { + collection = _this.prototype.schema.get('collection') + || utils.toCollectionName(_this.modelName, options); + } + + var collectionOptions = { + bufferCommands: s ? options.bufferCommands : true, + capped: s && options.capped + }; + + Model.prototype.collection = conn.collection(collection, collectionOptions); + Model.collection = Model.prototype.collection; + Model.init(); + return Model; +}; + +/*! + * Module exports. + */ + +module.exports = exports = Model; diff --git a/5-2/service/node_modules/mongoose/lib/promise.js b/5-2/service/node_modules/mongoose/lib/promise.js new file mode 100644 index 0000000..403eaa3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/promise.js @@ -0,0 +1,291 @@ +/*! + * Module dependencies + */ + +var MPromise = require('mpromise'); +var util = require('util'); + +/** + * Promise constructor. + * + * Promises are returned from executed queries. Example: + * + * var query = Candy.find({ bar: true }); + * var promise = query.exec(); + * + * DEPRECATED. Mongoose 5.0 will use native promises by default (or bluebird, + * if native promises are not present) but still + * support plugging in your own ES6-compatible promises library. Mongoose 5.0 + * will **not** support mpromise. + * + * @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature + * @inherits mpromise https://github.com/aheckmann/mpromise + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `err`: Emits when the promise is rejected + * @event `complete`: Emits when the promise is fulfilled + * @api public + * @deprecated + */ + +function Promise(fn) { + MPromise.call(this, fn); +} + +/** + * ES6-style promise constructor wrapper around mpromise. + * + * @param {Function} resolver + * @return {Promise} new promise + * @api public + */ +Promise.ES6 = function(resolver) { + var promise = new Promise(); + + // No try/catch for backwards compatibility + resolver( + function() { + promise.complete.apply(promise, arguments); + }, + function(e) { + promise.error(e); + }); + + return promise; +}; + +/*! + * Inherit from mpromise + */ + +Promise.prototype = Object.create(MPromise.prototype, { + constructor: { + value: Promise, + enumerable: false, + writable: true, + configurable: true + } +}); + +/*! + * Override event names for backward compatibility. + */ + +Promise.SUCCESS = 'complete'; +Promise.FAILURE = 'err'; + +/** + * 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. + * + * @see mpromise#on https://github.com/aheckmann/mpromise#on + * @method on + * @memberOf Promise + * @param {String} event + * @param {Function} listener + * @return {Promise} this + * @api public + */ + +/** + * Rejects this promise with `reason`. + * + * If the promise has already been fulfilled or rejected, not action is taken. + * + * @see mpromise#reject https://github.com/aheckmann/mpromise#reject + * @method reject + * @memberOf Promise + * @param {Object|String|Error} reason + * @return {Promise} this + * @api public + */ + +/** + * Rejects this promise with `err`. + * + * If the promise has already been fulfilled or rejected, not action is taken. + * + * Differs from [#reject](#promise_Promise-reject) by first casting `err` to an `Error` if it is not `instanceof Error`. + * + * @api public + * @param {Error|String} err + * @return {Promise} this + */ + +Promise.prototype.error = function(err) { + if (!(err instanceof Error)) { + if (err instanceof Object) { + err = util.inspect(err); + } + err = new Error(err); + } + return this.reject(err); +}; + +/** + * Resolves this promise to a rejected state if `err` is passed or a fulfilled state if no `err` is passed. + * + * If the promise has already been fulfilled or rejected, not action is taken. + * + * `err` will be cast to an Error if not already instanceof Error. + * + * _NOTE: overrides [mpromise#resolve](https://github.com/aheckmann/mpromise#resolve) to provide error casting._ + * + * @param {Error} [err] error or null + * @param {Object} [val] value to fulfill the promise with + * @api public + * @deprecated + */ + +Promise.prototype.resolve = function(err) { + if (err) return this.error(err); + return this.fulfill.apply(this, Array.prototype.slice.call(arguments, 1)); +}; + +/** + * Adds a single function as a listener to both err and complete. + * + * It will be executed with traditional node.js argument position when the promise is resolved. + * + * promise.addBack(function (err, args...) { + * if (err) return handleError(err); + * console.log('success'); + * }) + * + * Alias of [mpromise#onResolve](https://github.com/aheckmann/mpromise#onresolve). + * + * _Deprecated. Use `onResolve` instead._ + * + * @method addBack + * @param {Function} listener + * @return {Promise} this + * @deprecated + */ + +Promise.prototype.addBack = Promise.prototype.onResolve; + +/** + * Fulfills this promise with passed arguments. + * + * @method fulfill + * @receiver Promise + * @see https://github.com/aheckmann/mpromise#fulfill + * @param {any} args + * @api public + * @deprecated + */ + +/** + * Fulfills this promise with passed arguments. + * + * Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill). + * + * _Deprecated. Use `fulfill` instead._ + * + * @method complete + * @receiver Promise + * @param {any} args + * @api public + * @deprecated + */ + +Promise.prototype.complete = MPromise.prototype.fulfill; + +/** + * Adds a listener to the `complete` (success) event. + * + * Alias of [mpromise#onFulfill](https://github.com/aheckmann/mpromise#onfulfill). + * + * _Deprecated. Use `onFulfill` instead._ + * + * @method addCallback + * @param {Function} listener + * @return {Promise} this + * @api public + * @deprecated + */ + +Promise.prototype.addCallback = Promise.prototype.onFulfill; + +/** + * Adds a listener to the `err` (rejected) event. + * + * Alias of [mpromise#onReject](https://github.com/aheckmann/mpromise#onreject). + * + * _Deprecated. Use `onReject` instead._ + * + * @method addErrback + * @param {Function} listener + * @return {Promise} this + * @api public + * @deprecated + */ + +Promise.prototype.addErrback = Promise.prototype.onReject; + +/** + * 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. + * + * ####Example: + * + * var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec(); + * promise.then(function (meetups) { + * var ids = meetups.map(function (m) { + * return m._id; + * }); + * return People.find({ meetups: { $in: ids }).exec(); + * }).then(function (people) { + * if (people.length < 10000) { + * throw new Error('Too few people!!!'); + * } else { + * throw new Error('Still need more people!!!'); + * } + * }).then(null, function (err) { + * assert.ok(err instanceof Error); + * }); + * + * @see promises-A+ https://github.com/promises-aplus/promises-spec + * @see mpromise#then https://github.com/aheckmann/mpromise#then + * @method then + * @memberOf Promise + * @param {Function} onFulFill + * @param {Function} onReject + * @return {Promise} newPromise + * @deprecated + */ + +/** + * 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 + * @see mpromise#end https://github.com/aheckmann/mpromise#end + * @method end + * @memberOf Promise + * @deprecated + */ + +/*! + * expose + */ + +module.exports = Promise; diff --git a/5-2/service/node_modules/mongoose/lib/promise_provider.js b/5-2/service/node_modules/mongoose/lib/promise_provider.js new file mode 100644 index 0000000..368cf85 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/promise_provider.js @@ -0,0 +1,51 @@ +/*! + * Module dependencies. + */ + +var MPromise = require('./promise'); + +/** + * Helper for multiplexing promise implementations + * + * @api private + */ + +var Promise = { + _promise: MPromise +}; + +/** + * Get the current promise constructor + * + * @api private + */ +Promise.get = function() { + return Promise._promise; +}; + +/** + * Set the current promise constructor + * + * @api private + */ + +Promise.set = function(lib) { + if (lib === MPromise) { + return Promise.reset(); + } + Promise._promise = require('./ES6Promise'); + Promise._promise.use(lib); + require('mquery').Promise = Promise._promise.ES6; +}; + +/** + * Resets to using mpromise + * + * @api private + */ + +Promise.reset = function() { + Promise._promise = MPromise; +}; + +module.exports = Promise; diff --git a/5-2/service/node_modules/mongoose/lib/query.js b/5-2/service/node_modules/mongoose/lib/query.js new file mode 100644 index 0000000..ac426e2 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/query.js @@ -0,0 +1,3146 @@ +/*! + * Module dependencies. + */ + +var mquery = require('mquery'); +var util = require('util'); +var readPref = require('./drivers').ReadPreference; +var PromiseProvider = require('./promise_provider'); +var updateValidators = require('./services/updateValidators'); +var utils = require('./utils'); +var helpers = require('./queryhelpers'); +var QueryStream = require('./querystream'); +var StrictModeError = require('./error/strict'); +var cast = require('./cast'); + +/** + * Query constructor used for building queries. + * + * ####Example: + * + * var query = new Query(); + * query.setOptions({ lean : true }); + * query.collection(model.collection); + * query.where('age').gte(21).exec(callback); + * + * @param {Object} [options] + * @param {Object} [model] + * @param {Object} [conditions] + * @param {Object} [collection] Mongoose collection + * @api private + */ + +function Query(conditions, options, model, collection) { + // this stuff is for dealing with custom queries created by #toConstructor + if (!this._mongooseOptions) { + this._mongooseOptions = {}; + } + + // this is the case where we have a CustomQuery, we need to check if we got + // options passed in, and if we did, merge them in + if (options) { + var keys = Object.keys(options); + for (var i = 0; i < keys.length; ++i) { + var k = keys[i]; + this._mongooseOptions[k] = options[k]; + } + } + + if (collection) { + this.mongooseCollection = collection; + } + + if (model) { + this.model = model; + this.schema = model.schema; + } + + // this is needed because map reduce returns a model that can be queried, but + // all of the queries on said model should be lean + if (this.model && this.model._mapreduce) { + this.lean(); + } + + // inherit mquery + mquery.call(this, this.mongooseCollection, options); + + if (conditions) { + this.find(conditions); + } + + if (this.schema) { + this._count = this.model.hooks.createWrapper('count', + Query.prototype._count, this); + this._execUpdate = this.model.hooks.createWrapper('update', + Query.prototype._execUpdate, this); + this._find = this.model.hooks.createWrapper('find', + Query.prototype._find, this); + this._findOne = this.model.hooks.createWrapper('findOne', + Query.prototype._findOne, this); + this._findOneAndRemove = this.model.hooks.createWrapper('findOneAndRemove', + Query.prototype._findOneAndRemove, this); + this._findOneAndUpdate = this.model.hooks.createWrapper('findOneAndUpdate', + Query.prototype._findOneAndUpdate, this); + } +} + +/*! + * inherit mquery + */ + +Query.prototype = new mquery; +Query.prototype.constructor = Query; +Query.base = mquery.prototype; + +/** + * Flag to opt out of using `$geoWithin`. + * + * mongoose.Query.use$geoWithin = false; + * + * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work. + * + * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ + * @default true + * @property use$geoWithin + * @memberOf Query + * @receiver Query + * @api public + */ + +Query.use$geoWithin = mquery.use$geoWithin; + +/** + * Converts this query to a customized, reusable query constructor with all arguments and options retained. + * + * ####Example + * + * // Create a query for adventure movies and read from the primary + * // node in the replica-set unless it is down, in which case we'll + * // read from a secondary node. + * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred'); + * + * // create a custom Query constructor based off these settings + * var Adventure = query.toConstructor(); + * + * // Adventure is now a subclass of mongoose.Query and works the same way but with the + * // default query parameters and options set. + * Adventure().exec(callback) + * + * // further narrow down our query results while still using the previous settings + * Adventure().where({ name: /^Life/ }).exec(callback); + * + * // since Adventure is a stand-alone constructor we can also add our own + * // helper methods and getters without impacting global queries + * Adventure.prototype.startsWith = function (prefix) { + * this.where({ name: new RegExp('^' + prefix) }) + * return this; + * } + * Object.defineProperty(Adventure.prototype, 'highlyRated', { + * get: function () { + * this.where({ rating: { $gt: 4.5 }}); + * return this; + * } + * }) + * Adventure().highlyRated.startsWith('Life').exec(callback) + * + * New in 3.7.3 + * + * @return {Query} subclass-of-Query + * @api public + */ + +Query.prototype.toConstructor = function toConstructor() { + var CustomQuery = function(criteria, options) { + if (!(this instanceof CustomQuery)) { + return new CustomQuery(criteria, options); + } + this._mongooseOptions = utils.clone(p._mongooseOptions); + Query.call(this, criteria, options || null); + }; + + util.inherits(CustomQuery, Query); + + // set inherited defaults + var p = CustomQuery.prototype; + + p.options = {}; + + p.setOptions(this.options); + + p.op = this.op; + p._conditions = utils.clone(this._conditions); + p._fields = utils.clone(this._fields); + p._update = utils.clone(this._update); + p._path = this._path; + p._distinct = this._distinct; + p._collection = this._collection; + p.model = this.model; + p.mongooseCollection = this.mongooseCollection; + p._mongooseOptions = this._mongooseOptions; + + return CustomQuery; +}; + +/** + * Specifies a javascript function or expression to pass to MongoDBs query system. + * + * ####Example + * + * query.$where('this.comments.length === 10 || this.name.length === 5') + * + * // or + * + * query.$where(function () { + * return this.comments.length === 10 || this.name.length === 5; + * }) + * + * ####NOTE: + * + * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. + * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.** + * + * @see $where http://docs.mongodb.org/manual/reference/operator/where/ + * @method $where + * @param {String|Function} js javascript string or function + * @return {Query} this + * @memberOf Query + * @method $where + * @api public + */ + +/** + * Specifies a `path` for use with chaining. + * + * ####Example + * + * // instead of writing: + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * // we can instead write: + * User.where('age').gte(21).lte(65); + * + * // passing query conditions is permitted + * User.find().where({ name: 'vonderful' }) + * + * // chaining + * User + * .where('age').gte(21).lte(65) + * .where('name', /^vonderful/i) + * .where('friends').slice(10) + * .exec(callback) + * + * @method where + * @memberOf Query + * @param {String|Object} [path] + * @param {any} [val] + * @return {Query} this + * @api public + */ + +/** + * Specifies the complementary comparison value for paths specified with `where()` + * + * ####Example + * + * User.where('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @method equals + * @memberOf Query + * @param {Object} val + * @return {Query} this + * @api public + */ + +/** + * Specifies arguments for an `$or` condition. + * + * ####Example + * + * query.or([{ color: 'red' }, { status: 'emergency' }]) + * + * @see $or http://docs.mongodb.org/manual/reference/operator/or/ + * @method or + * @memberOf Query + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +/** + * Specifies arguments for a `$nor` condition. + * + * ####Example + * + * query.nor([{ color: 'green' }, { status: 'ok' }]) + * + * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/ + * @method nor + * @memberOf Query + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +/** + * Specifies arguments for a `$and` condition. + * + * ####Example + * + * query.and([{ color: 'green' }, { status: 'ok' }]) + * + * @method and + * @memberOf Query + * @see $and http://docs.mongodb.org/manual/reference/operator/and/ + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +/** + * Specifies a $gt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * Thing.find().where('age').gt(21) + * + * // or + * Thing.find().gt('age', 21) + * + * @method gt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/ + * @api public + */ + +/** + * Specifies a $gte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method gte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/ + * @api public + */ + +/** + * Specifies a $lt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/ + * @api public + */ + +/** + * Specifies a $lte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lte + * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/ + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $ne query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/ + * @method ne + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $in query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $in http://docs.mongodb.org/manual/reference/operator/in/ + * @method in + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $nin query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/ + * @method nin + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $all query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $all http://docs.mongodb.org/manual/reference/operator/all/ + * @method all + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $size query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * MyModel.where('tags').size(0).exec(function (err, docs) { + * if (err) return handleError(err); + * + * assert(Array.isArray(docs)); + * console.log('documents with 0 tags', docs); + * }) + * + * @see $size http://docs.mongodb.org/manual/reference/operator/size/ + * @method size + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $regex query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/ + * @method regex + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $maxDistance query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + * @method maxDistance + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a `$mod` condition + * + * @method mod + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/ + * @api public + */ + +/** + * Specifies an `$exists` condition + * + * ####Example + * + * // { name: { $exists: true }} + * Thing.where('name').exists() + * Thing.where('name').exists(true) + * Thing.find().exists('name') + * + * // { name: { $exists: false }} + * Thing.where('name').exists(false); + * Thing.find().exists('name', false); + * + * @method exists + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/ + * @api public + */ + +/** + * Specifies an `$elemMatch` condition + * + * ####Example + * + * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) + * + * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + * + * query.elemMatch('comment', function (elem) { + * elem.where('author').equals('autobot'); + * elem.where('votes').gte(5); + * }) + * + * query.where('comment').elemMatch(function (elem) { + * elem.where({ author: 'autobot' }); + * elem.where('votes').gte(5); + * }) + * + * @method elemMatch + * @memberOf Query + * @param {String|Object|Function} path + * @param {Object|Function} criteria + * @return {Query} this + * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/ + * @api public + */ + +/** + * Defines a `$within` or `$geoWithin` argument for geo-spatial queries. + * + * ####Example + * + * query.where(path).within().box() + * query.where(path).within().circle() + * query.where(path).within().geometry() + * + * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); + * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); + * query.where('loc').within({ polygon: [[],[],[],[]] }); + * + * query.where('loc').within([], [], []) // polygon + * query.where('loc').within([], []) // box + * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry + * + * **MUST** be used after `where()`. + * + * ####NOTE: + * + * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin). + * + * ####NOTE: + * + * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). + * + * @method within + * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ + * @see $box http://docs.mongodb.org/manual/reference/operator/box/ + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see $center http://docs.mongodb.org/manual/reference/operator/center/ + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @memberOf Query + * @return {Query} this + * @api public + */ + +/** + * Specifies a $slice projection for an array. + * + * ####Example + * + * query.slice('comments', 5) + * query.slice('comments', -5) + * query.slice('comments', [10, 5]) + * query.where('comments').slice(5) + * query.where('comments').slice([-10, 5]) + * + * @method slice + * @memberOf Query + * @param {String} [path] + * @param {Number} val number/range of elements to slice + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements + * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice + * @api public + */ + +/** + * Specifies the maximum number of documents the query will return. + * + * ####Example + * + * query.limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method limit + * @memberOf Query + * @param {Number} val + * @api public + */ + +/** + * Specifies the number of documents to skip. + * + * ####Example + * + * query.skip(100).limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method skip + * @memberOf Query + * @param {Number} val + * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/ + * @api public + */ + +/** + * Specifies the maxScan option. + * + * ####Example + * + * query.maxScan(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method maxScan + * @memberOf Query + * @param {Number} val + * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/ + * @api public + */ + +/** + * Specifies the batchSize option. + * + * ####Example + * + * query.batchSize(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method batchSize + * @memberOf Query + * @param {Number} val + * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/ + * @api public + */ + +/** + * Specifies the `comment` option. + * + * ####Example + * + * query.comment('login query') + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method comment + * @memberOf Query + * @param {Number} val + * @see comment http://docs.mongodb.org/manual/reference/operator/comment/ + * @api public + */ + +/** + * Specifies this query as a `snapshot` query. + * + * ####Example + * + * query.snapshot() // true + * query.snapshot(true) + * query.snapshot(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method snapshot + * @memberOf Query + * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/ + * @return {Query} this + * @api public + */ + +/** + * Sets query hints. + * + * ####Example + * + * query.hint({ indexA: 1, indexB: -1}) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method hint + * @memberOf Query + * @param {Object} val a hint object + * @return {Query} this + * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/ + * @api public + */ + +/** + * Specifies which document fields to include or exclude (also known as the query "projection") + * + * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select). + * + * ####Example + * + * // include a and b, exclude other fields + * query.select('a b'); + * + * // exclude c and d, include other fields + * query.select('-c -d'); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * query.select({ a: 1, b: 1 }); + * query.select({ c: 0, d: 0 }); + * + * // force inclusion of field excluded at schema level + * query.select('+path') + * + * ####NOTE: + * + * Cannot be used with `distinct()`. + * + * _v2 had slightly different syntax such as allowing arrays of field names. This support was removed in v3._ + * + * @method select + * @memberOf Query + * @param {Object|String} arg + * @return {Query} this + * @see SchemaType + * @api public + */ + +/** + * _DEPRECATED_ Sets the slaveOk option. + * + * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read). + * + * ####Example: + * + * query.slaveOk() // true + * query.slaveOk(true) + * query.slaveOk(false) + * + * @method slaveOk + * @memberOf Query + * @deprecated use read() preferences instead if on mongodb >= 2.2 + * @param {Boolean} v defaults to true + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/ + * @see read() #query_Query-read + * @return {Query} this + * @api public + */ + +/** + * Determines the MongoDB nodes from which to read. + * + * ####Preferences: + * + * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. + * secondary Read from secondary if available, otherwise error. + * primaryPreferred Read from primary if available, otherwise a secondary. + * secondaryPreferred Read from a secondary if available, otherwise read from the primary. + * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + * + * Aliases + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * ####Example: + * + * new Query().read('primary') + * new Query().read('p') // same as primary + * + * new Query().read('primaryPreferred') + * new Query().read('pp') // same as primaryPreferred + * + * new Query().read('secondary') + * new Query().read('s') // same as secondary + * + * new Query().read('secondaryPreferred') + * new Query().read('sp') // same as secondaryPreferred + * + * new Query().read('nearest') + * new Query().read('n') // same as nearest + * + * // read from secondaries with matching tags + * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) + * + * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + * + * @method read + * @memberOf Query + * @param {String} pref one of the listed preference options or aliases + * @param {Array} [tags] optional tags for this query + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + * @return {Query} this + * @api public + */ + +Query.prototype.read = function read(pref, tags) { + // first cast into a ReadPreference object to support tags + var read = readPref.call(readPref, pref, tags); + return Query.base.read.call(this, read); +}; + +/** + * Merges another Query or conditions object into this one. + * + * When a Query is passed, conditions, field selection and options are merged. + * + * New in 3.7.0 + * + * @method merge + * @memberOf Query + * @param {Query|Object} source + * @return {Query} this + */ + +/** + * Sets query options. + * + * ####Options: + * + * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * + * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * + * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * + * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * + * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan) * + * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * + * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * + * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * + * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * + * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference) ** + * - [lean](./api.html#query_Query-lean) * + * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) + * + * _* denotes a query helper method is also available_ + * _** query helper method to set `readPreference` is `read()`_ + * + * @param {Object} options + * @api public + */ + +Query.prototype.setOptions = function(options, overwrite) { + // overwrite is only for internal use + if (overwrite) { + // ensure that _mongooseOptions & options are two different objects + this._mongooseOptions = (options && utils.clone(options)) || {}; + this.options = options || {}; + + if ('populate' in options) { + this.populate(this._mongooseOptions); + } + return this; + } + + if (!(options && options.constructor.name === 'Object')) { + return this; + } + + return Query.base.setOptions.call(this, options); +}; + +/** + * Returns the current query conditions as a JSON object. + * + * ####Example: + * + * var query = new Query(); + * query.find({ a: 1 }).where('b').gt(2); + * query.getQuery(); // { a: 1, b: { $gt: 2 } } + * + * @return {Object} current query conditions + * @api public + */ + +Query.prototype.getQuery = function() { + return this._conditions; +}; + +/** + * Returns the current update operations as a JSON object. + * + * ####Example: + * + * var query = new Query(); + * query.update({}, { $set: { a: 5 } }); + * query.getUpdate(); // { $set: { a: 5 } } + * + * @return {Object} current update operations + * @api public + */ + +Query.prototype.getUpdate = function() { + return this._update; +}; + +/** + * Returns fields selection for this query. + * + * @method _fieldsForExec + * @return {Object} + * @api private + * @receiver Query + */ + +/** + * Return an update document with corrected $set operations. + * + * @method _updateForExec + * @api private + * @receiver Query + */ + +/** + * Makes sure _path is set. + * + * @method _ensurePath + * @param {String} method + * @api private + * @receiver Query + */ + +/** + * Determines if `conds` can be merged using `mquery().merge()` + * + * @method canMerge + * @memberOf Query + * @param {Object} conds + * @return {Boolean} + * @api private + */ + +/** + * Returns default options for this query. + * + * @param {Model} model + * @api private + */ + +Query.prototype._optionsForExec = function(model) { + var options = Query.base._optionsForExec.call(this); + + delete options.populate; + model = model || this.model; + + if (!model) { + return options; + } + + if (!('safe' in options) && model.schema.options.safe) { + options.safe = model.schema.options.safe; + } + + if (!('readPreference' in options) && model.schema.options.read) { + options.readPreference = model.schema.options.read; + } + + return options; +}; + +/** + * Sets the lean option. + * + * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied. + * + * ####Example: + * + * new Query().lean() // true + * new Query().lean(true) + * new Query().lean(false) + * + * Model.find().lean().exec(function (err, docs) { + * docs[0] instanceof mongoose.Document // false + * }); + * + * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream). + * + * @param {Boolean} bool defaults to true + * @return {Query} this + * @api public + */ + +Query.prototype.lean = function(v) { + this._mongooseOptions.lean = arguments.length ? !!v : true; + return this; +}; + +/** + * Thunk around find() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._find = function(callback) { + if (this._castError) { + callback(this._castError); + return this; + } + + this._applyPaths(); + this._fields = this._castFields(this._fields); + + var fields = this._fieldsForExec(); + var options = this._mongooseOptions; + var _this = this; + + var cb = function(err, docs) { + if (err) { + return callback(err); + } + + if (docs.length === 0) { + return callback(null, docs); + } + + if (!options.populate) { + return options.lean === true + ? callback(null, docs) + : completeMany(_this.model, docs, fields, _this, null, callback); + } + + var pop = helpers.preparePopulationOptionsMQ(_this, options); + pop.__noPromise = true; + _this.model.populate(docs, pop, function(err, docs) { + if (err) return callback(err); + return options.lean === true + ? callback(null, docs) + : completeMany(_this.model, docs, fields, _this, pop, callback); + }); + }; + + return Query.base.find.call(this, {}, cb); +}; + +/** + * Finds documents. + * + * When no `callback` is passed, the query is not executed. When the query is executed, the result will be an array of documents. + * + * ####Example + * + * query.find({ name: 'Los Pollos Hermanos' }).find(callback) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.find = function(conditions, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + + conditions = utils.toObject(conditions); + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + prepareDiscriminatorCriteria(this); + + try { + this.cast(this.model); + this._castError = null; + } catch (err) { + this._castError = err; + } + + // if we don't have a callback, then just return the query object + if (!callback) { + return Query.base.find.call(this); + } + + this._find(callback); + + return this; +}; + +/*! + * hydrates many documents + * + * @param {Model} model + * @param {Array} docs + * @param {Object} fields + * @param {Query} self + * @param {Array} [pop] array of paths used in population + * @param {Function} callback + */ + +function completeMany(model, docs, fields, self, pop, callback) { + var arr = []; + var count = docs.length; + var len = count; + var opts = pop ? + {populated: pop} + : undefined; + function init(err) { + if (err) return callback(err); + --count || callback(null, arr); + } + for (var i = 0; i < len; ++i) { + arr[i] = helpers.createModel(model, docs[i], fields); + arr[i].init(docs[i], opts, init); + } +} + +/** + * Thunk around findOne() + * + * @param {Function} [callback] + * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ + * @api private + */ + +Query.prototype._findOne = function(callback) { + if (this._castError) { + return callback(this._castError); + } + + this._applyPaths(); + this._fields = this._castFields(this._fields); + + var options = this._mongooseOptions; + var projection = this._fieldsForExec(); + var _this = this; + + // don't pass in the conditions because we already merged them in + Query.base.findOne.call(_this, {}, function(err, doc) { + if (err) { + return callback(err); + } + if (!doc) { + return callback(null, null); + } + + if (!options.populate) { + return options.lean === true + ? callback(null, doc) + : completeOne(_this.model, doc, null, projection, _this, null, callback); + } + + var pop = helpers.preparePopulationOptionsMQ(_this, options); + pop.__noPromise = true; + _this.model.populate(doc, pop, function(err, doc) { + if (err) { + return callback(err); + } + + return options.lean === true + ? callback(null, doc) + : completeOne(_this.model, doc, null, projection, _this, pop, callback); + }); + }); +}; + +/** + * Declares the query a findOne operation. When executed, the first found document is passed to the callback. + * + * Passing a `callback` executes the query. The result of the query is a single document. + * + * ####Example + * + * var query = Kitten.where({ color: 'white' }); + * query.findOne(function (err, kitten) { + * if (err) return handleError(err); + * if (kitten) { + * // doc may be null if no document matched + * } + * }); + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Object} [projection] optional fields to return + * @param {Function} [callback] + * @return {Query} this + * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ + * @see Query.select #query_Query-select + * @api public + */ + +Query.prototype.findOne = function(conditions, projection, options, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = null; + projection = null; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + options = null; + projection = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } + + // make sure we don't send in the whole Document to merge() + conditions = utils.toObject(conditions); + + this.op = 'findOne'; + + if (options) { + this.setOptions(options); + } + + if (projection) { + this.select(projection); + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + prepareDiscriminatorCriteria(this); + + try { + this.cast(this.model); + this._castError = null; + } catch (err) { + this._castError = err; + } + + if (!callback) { + // already merged in the conditions, don't need to send them in. + return Query.base.findOne.call(this); + } + + this._findOne(callback); + + return this; +}; + +/** + * Thunk around count() + * + * @param {Function} [callback] + * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ + * @api private + */ + +Query.prototype._count = function(callback) { + try { + this.cast(this.model); + } catch (err) { + process.nextTick(function() { + callback(err); + }); + return this; + } + + var conds = this._conditions; + var options = this._optionsForExec(); + + this._collection.count(conds, options, utils.tick(callback)); +}; + +/** + * Specifying this query as a `count` query. + * + * Passing a `callback` executes the query. + * + * ####Example: + * + * var countQuery = model.where({ 'color': 'black' }).count(); + * + * query.count({ color: 'black' }).count(callback) + * + * query.count({ color: 'black' }, callback) + * + * query.where('color', 'black').count(function (err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ + * @api public + */ + +Query.prototype.count = function(conditions, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + this.op = 'count'; + if (!callback) { + return this; + } + + this._count(callback); + + return this; +}; + +/** + * Declares or executes a distict() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * distinct(field, conditions, callback) + * distinct(field, conditions) + * distinct(field, callback) + * distinct(field) + * distinct(callback) + * distinct() + * + * @param {String} [field] + * @param {Object|Query} [criteria] + * @param {Function} [callback] + * @return {Query} this + * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ + * @api public + */ + +Query.prototype.distinct = function(field, conditions, callback) { + if (!callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + } else if (typeof field === 'function') { + callback = field; + field = undefined; + conditions = undefined; + } + } + + conditions = utils.toObject(conditions); + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + try { + this.cast(this.model); + } catch (err) { + if (!callback) { + throw err; + } + callback(err); + return this; + } + + return Query.base.distinct.call(this, {}, field, callback); +}; + +/** + * Sets the sort order + * + * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + * + * If a string is passed, it must be a space delimited list of path names. The + * sort order of each path is ascending unless the path name is prefixed with `-` + * which will be treated as descending. + * + * ####Example + * + * // sort by "field" ascending and "test" descending + * query.sort({ field: 'asc', test: -1 }); + * + * // equivalent + * query.sort('field -test'); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/ + * @api public + */ + +Query.prototype.sort = function(arg) { + var nArg = {}; + + if (arguments.length > 1) { + throw new Error('sort() only takes 1 Argument'); + } + + if (Array.isArray(arg)) { + // time to deal with the terrible syntax + for (var i = 0; i < arg.length; i++) { + if (!Array.isArray(arg[i])) throw new Error('Invalid sort() argument.'); + nArg[arg[i][0]] = arg[i][1]; + } + } else { + nArg = arg; + } + + // workaround for gh-2374 when sort is called after count + // if previous operation is count, we ignore + if (this.op === 'count') { + delete this.op; + } + return Query.base.sort.call(this, nArg); +}; + +/** + * Declare and/or execute this query as a remove() operation. + * + * ####Example + * + * Model.remove({ artist: 'Anne Murray' }, callback) + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback, you must first call `remove()` and then execute it by using the `exec()` method. + * + * // not executed + * var query = Model.find().remove({ name: 'Anne Murray' }) + * + * // executed + * query.remove({ name: 'Anne Murray' }, callback) + * query.remove({ name: 'Anne Murray' }).remove(callback) + * + * // executed without a callback (unsafe write) + * query.exec() + * + * // summary + * query.remove(conds, fn); // executes + * query.remove(conds) + * query.remove(fn) // executes + * query.remove() + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/ + * @api public + */ + +Query.prototype.remove = function(cond, callback) { + if (typeof cond === 'function') { + callback = cond; + cond = null; + } + + var cb = typeof callback === 'function'; + + try { + this.cast(this.model); + } catch (err) { + if (cb) return process.nextTick(callback.bind(null, err)); + return this; + } + + return Query.base.remove.call(this, cond, callback); +}; + +/*! + * hydrates a document + * + * @param {Model} model + * @param {Document} doc + * @param {Object} res 3rd parameter to callback + * @param {Object} fields + * @param {Query} self + * @param {Array} [pop] array of paths used in population + * @param {Function} callback + */ + +function completeOne(model, doc, res, fields, self, pop, callback) { + var opts = pop ? + {populated: pop} + : undefined; + + var casted = helpers.createModel(model, doc, fields); + casted.init(doc, opts, function(err) { + if (err) { + return callback(err); + } + if (res) { + return callback(null, casted, res); + } + callback(null, casted); + }); +} + +/*! + * If the model is a discriminator type and not root, then add the key & value to the criteria. + */ + +function prepareDiscriminatorCriteria(query) { + if (!query || !query.model || !query.model.schema) { + return; + } + + var schema = query.model.schema; + + if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { + query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; + } +} + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. + * + * ####Available options + * + * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * } + * + * ####Examples + * + * query.findOneAndUpdate(conditions, update, options, callback) // executes + * query.findOneAndUpdate(conditions, update, options) // returns Query + * query.findOneAndUpdate(conditions, update, callback) // executes + * query.findOneAndUpdate(conditions, update) // returns Query + * query.findOneAndUpdate(update, callback) // returns Query + * query.findOneAndUpdate(update) // returns Query + * query.findOneAndUpdate(callback) // executes + * query.findOneAndUpdate() // returns Query + * + * @method findOneAndUpdate + * @memberOf Query + * @param {Object|Query} [query] + * @param {Object} [doc] + * @param {Object} [options] + * @param {Function} [callback] + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @return {Query} this + * @api public + */ + +Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) { + this.op = 'findOneAndUpdate'; + this._validate(); + + switch (arguments.length) { + case 3: + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 2: + if (typeof doc === 'function') { + callback = doc; + doc = criteria; + criteria = undefined; + } + options = undefined; + break; + case 1: + if (typeof criteria === 'function') { + callback = criteria; + criteria = options = doc = undefined; + } else { + doc = criteria; + criteria = options = undefined; + } + } + + if (mquery.canMerge(criteria)) { + this.merge(criteria); + } + + // apply doc + if (doc) { + this._mergeUpdate(doc); + } + + options && this.setOptions(options); + + if (!callback) { + return this; + } + + return this._findOneAndUpdate(callback); +}; + +/** + * Thunk around findOneAndUpdate() + * + * @param {Function} [callback] + * @api private + */ + +Query.prototype._findOneAndUpdate = function(callback) { + this._findAndModify('update', callback); + return this; +}; + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc, result) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * // result: [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * } + * + * ####Examples + * + * A.where().findOneAndRemove(conditions, options, callback) // executes + * A.where().findOneAndRemove(conditions, options) // return Query + * A.where().findOneAndRemove(conditions, callback) // executes + * A.where().findOneAndRemove(conditions) // returns Query + * A.where().findOneAndRemove(callback) // executes + * A.where().findOneAndRemove() // returns Query + * + * @method findOneAndRemove + * @memberOf Query + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Query.prototype.findOneAndRemove = function(conditions, options, callback) { + this.op = 'findOneAndRemove'; + this._validate(); + + switch (arguments.length) { + case 2: + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 1: + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + options = undefined; + } + break; + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + options && this.setOptions(options); + + if (!callback) { + return this; + } + + this._findOneAndRemove(callback); + + return this; +}; + +/** + * Thunk around findOneAndRemove() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._findOneAndRemove = function(callback) { + Query.base.findOneAndRemove.call(this, callback); +}; + +/** + * Override mquery.prototype._findAndModify to provide casting etc. + * + * @param {String} type - either "remove" or "update" + * @param {Function} callback + * @api private + */ + +Query.prototype._findAndModify = function(type, callback) { + if (typeof callback !== 'function') { + throw new Error('Expected callback in _findAndModify'); + } + + var model = this.model; + var schema = model.schema; + var _this = this; + var castedQuery; + var castedDoc; + var fields; + var opts; + var doValidate; + + castedQuery = castQuery(this); + if (castedQuery instanceof Error) { + return callback(castedQuery); + } + + opts = this._optionsForExec(model); + + if ('strict' in opts) { + this._mongooseOptions.strict = opts.strict; + } + + if (type === 'remove') { + opts.remove = true; + } else { + if (!('new' in opts)) { + opts.new = false; + } + if (!('upsert' in opts)) { + opts.upsert = false; + } + if (opts.upsert || opts['new']) { + opts.remove = false; + } + + castedDoc = castDoc(this, opts.overwrite); + if (!castedDoc) { + if (opts.upsert) { + // still need to do the upsert to empty doc + var doc = utils.clone(castedQuery); + delete doc._id; + castedDoc = {$set: doc}; + } else { + return this.findOne(callback); + } + } else if (castedDoc instanceof Error) { + return callback(castedDoc); + } else { + // In order to make MongoDB 2.6 happy (see + // https://jira.mongodb.org/browse/SERVER-12266 and related issues) + // if we have an actual update document but $set is empty, junk the $set. + if (castedDoc.$set && Object.keys(castedDoc.$set).length === 0) { + delete castedDoc.$set; + } + } + + doValidate = updateValidators(this, schema, castedDoc, opts); + } + + this._applyPaths(); + + var options = this._mongooseOptions; + + if (this._fields) { + fields = utils.clone(this._fields); + opts.fields = this._castFields(fields); + if (opts.fields instanceof Error) { + return callback(opts.fields); + } + } + + if (opts.sort) convertSortToArray(opts); + + var cb = function(err, doc, res) { + if (err) { + return callback(err); + } + + if (!doc || (utils.isObject(doc) && Object.keys(doc).length === 0)) { + return callback(null, null); + } + + if (!opts.passRawResult) { + res = null; + } + + if (!options.populate) { + return options.lean === true + ? callback(null, doc) + : completeOne(_this.model, doc, res, fields, _this, null, callback); + } + + var pop = helpers.preparePopulationOptionsMQ(_this, options); + pop.__noPromise = true; + _this.model.populate(doc, pop, function(err, doc) { + if (err) { + return callback(err); + } + + return options.lean === true + ? callback(null, doc) + : completeOne(_this.model, doc, res, fields, _this, pop, callback); + }); + }; + + if ((opts.runValidators || opts.setDefaultsOnInsert) && doValidate) { + doValidate(function(error) { + if (error) { + return callback(error); + } + _this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function(error, res) { + return cb(error, res ? res.value : res, res); + })); + }); + } else { + this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function(error, res) { + return cb(error, res ? res.value : res, res); + })); + } + + return this; +}; + +/** + * Override mquery.prototype._mergeUpdate to handle mongoose objects in + * updates. + * + * @param {Object} doc + * @api private + */ + +Query.prototype._mergeUpdate = function(doc) { + if (!this._update) this._update = {}; + if (doc instanceof Query) { + if (doc._update) { + utils.mergeClone(this._update, doc._update); + } + } else { + utils.mergeClone(this._update, doc); + } +}; + +/*! + * The mongodb driver 1.3.23 only supports the nested array sort + * syntax. We must convert it or sorting findAndModify will not work. + */ + +function convertSortToArray(opts) { + if (Array.isArray(opts.sort)) { + return; + } + if (!utils.isObject(opts.sort)) { + return; + } + + var sort = []; + + for (var key in opts.sort) { + if (utils.object.hasOwnProperty(opts.sort, key)) { + sort.push([key, opts.sort[key]]); + } + } + + opts.sort = sort; +} + +/** + * Internal thunk for .update() + * + * @param {Function} callback + * @see Model.update #model_Model.update + * @api private + */ +Query.prototype._execUpdate = function(callback) { + var schema = this.model.schema; + var doValidate; + var _this; + + var castedQuery = this._conditions; + var castedDoc = this._update; + var options = this.options; + + if (this._castError) { + callback(this._castError); + return this; + } + + if (this.options.runValidators || this.options.setDefaultsOnInsert) { + _this = this; + doValidate = updateValidators(this, schema, castedDoc, options); + doValidate(function(err) { + if (err) { + return callback(err); + } + + Query.base.update.call(_this, castedQuery, castedDoc, options, callback); + }); + return this; + } + + Query.base.update.call(this, castedQuery, castedDoc, options, callback); + return this; +}; + +/** + * Declare and/or execute this query as an update() operation. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * Model.where({ _id: id }).update({ title: 'words' }) + * + * // becomes + * + * Model.where({ _id: id }).update({ $set: { title: 'words' }}) + * + * ####Note + * + * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. + * + * var q = Model.where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).update(); // not executed + * + * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe + * + * // keys that are not $atomic ops become $set. + * // this executes the same command as the previous example. + * q.update({ name: 'bob' }).exec(); + * + * // overwriting with empty docs + * var q = Model.where({ _id: id }).setOptions({ overwrite: true }) + * q.update({ }, callback); // executes + * + * // multi update with overwrite to empty doc + * var q = Model.where({ _id: id }); + * q.setOptions({ multi: true, overwrite: true }) + * q.update({ }); + * q.update(callback); // executed + * + * // multi updates + * Model.where() + * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) + * + * // more multi updates + * Model.where() + * .setOptions({ multi: true }) + * .update({ $set: { arr: [] }}, callback) + * + * // single update by default + * Model.where({ email: 'address@example.com' }) + * .update({ $inc: { counter: 1 }}, callback) + * + * API summary + * + * update(criteria, doc, options, cb) // executes + * update(criteria, doc, options) + * update(criteria, doc, cb) // executes + * update(criteria, doc) + * update(doc, cb) // executes + * update(doc) + * update(cb) // executes + * update(true) // executes (unsafe write) + * update() + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @see Model.update #model_Model.update + * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ + * @api public + */ + +Query.prototype.update = function(conditions, doc, options, callback) { + if (typeof options === 'function') { + // .update(conditions, doc, callback) + callback = options; + options = null; + } else if (typeof doc === 'function') { + // .update(doc, callback); + callback = doc; + doc = conditions; + conditions = {}; + options = null; + } else if (typeof conditions === 'function') { + // .update(callback) + callback = conditions; + conditions = undefined; + doc = undefined; + options = undefined; + } else if (typeof conditions === 'object' && !doc && !options && !callback) { + // .update(doc) + doc = conditions; + conditions = undefined; + options = undefined; + callback = undefined; + } + + // make sure we don't send in the whole Document to merge() + conditions = utils.toObject(conditions); + + var oldCb = callback; + if (oldCb) { + if (typeof oldCb === 'function') { + callback = function(error, result) { + oldCb(error, result ? result.result : {ok: 0, n: 0, nModified: 0}); + }; + } else { + throw new Error('Invalid callback() argument.'); + } + } + + // strict is an option used in the update checking, make sure it gets set + if (options) { + if ('strict' in options) { + this._mongooseOptions.strict = options.strict; + } + } + + // if doc is undefined at this point, this means this function is being + // executed by exec(not always see below). Grab the update doc from here in + // order to validate + // This could also be somebody calling update() or update({}). Probably not a + // common use case, check for _update to make sure we don't do anything bad + if (!doc && this._update) { + doc = this._updateForExec(); + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + // validate the selector part of the query + var castedQuery = castQuery(this); + if (castedQuery instanceof Error) { + this._castError = castedQuery; + if (callback) { + callback(castedQuery); + return this; + } else if (!options || !options.dontThrowCastError) { + throw castedQuery; + } + } + + // validate the update part of the query + var castedDoc; + try { + var $options = {retainKeyOrder: true}; + if (options && options.minimize) { + $options.minimize = true; + } + castedDoc = this._castUpdate(utils.clone(doc, $options), + options && options.overwrite); + } catch (err) { + this._castError = castedQuery; + if (callback) { + callback(err); + return this; + } else if (!options || !options.dontThrowCastError) { + throw err; + } + } + + if (!castedDoc) { + // Make sure promises know that this is still an update, see gh-2796 + this.op = 'update'; + callback && callback(null); + return this; + } + + if (utils.isObject(options)) { + this.setOptions(options); + } + + if (!this._update) this._update = castedDoc; + + // Hooks + if (callback) { + return this._execUpdate(callback); + } + + return Query.base.update.call(this, castedQuery, castedDoc, options, callback); +}; + +/** + * Executes the query + * + * ####Examples: + * + * var promise = query.exec(); + * var promise = query.exec('update'); + * + * query.exec(callback); + * query.exec('find', callback); + * + * @param {String|Function} [operation] + * @param {Function} [callback] + * @return {Promise} + * @api public + */ + +Query.prototype.exec = function exec(op, callback) { + var Promise = PromiseProvider.get(); + var _this = this; + + if (typeof op === 'function') { + callback = op; + op = null; + } else if (typeof op === 'string') { + this.op = op; + } + + return new Promise.ES6(function(resolve, reject) { + if (!_this.op) { + callback && callback(null, undefined); + resolve(); + return; + } + + _this[_this.op].call(_this, function(error, res) { + if (error) { + callback && callback(error); + reject(error); + return; + } + callback && callback.apply(null, arguments); + resolve(res); + }); + }); +}; + +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @return {Promise} + * @api public + */ + +Query.prototype.then = function(resolve, reject) { + return this.exec().then(resolve, reject); +}; + +/** + * Finds the schema for `path`. This is different than + * calling `schema.path` as it also resolves paths with + * positional selectors (something.$.another.$.path). + * + * @param {String} path + * @api private + */ + +Query.prototype._getSchema = function _getSchema(path) { + return this.model._getSchema(path); +}; + +/*! + * These operators require casting docs + * to real Documents for Update operations. + */ + +var castOps = { + $push: 1, + $pushAll: 1, + $addToSet: 1, + $set: 1 +}; + +/*! + * These operators should be cast to numbers instead + * of their path schema type. + */ + +var numberOps = { + $pop: 1, + $unset: 1, + $inc: 1 +}; + +/** + * Casts obj for an update command. + * + * @param {Object} obj + * @return {Object} obj after casting its values + * @api private + */ + +Query.prototype._castUpdate = function _castUpdate(obj, overwrite) { + if (!obj) { + return undefined; + } + + var ops = Object.keys(obj); + var i = ops.length; + var ret = {}; + var hasKeys; + var val; + var hasDollarKey = false; + + while (i--) { + var op = ops[i]; + // if overwrite is set, don't do any of the special $set stuff + if (op[0] !== '$' && !overwrite) { + // fix up $set sugar + if (!ret.$set) { + if (obj.$set) { + ret.$set = obj.$set; + } else { + ret.$set = {}; + } + } + ret.$set[op] = obj[op]; + ops.splice(i, 1); + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if (op === '$set') { + if (!ret.$set) { + ret[op] = obj[op]; + } + } else { + ret[op] = obj[op]; + } + } + + // cast each value + i = ops.length; + + // if we get passed {} for the update, we still need to respect that when it + // is an overwrite scenario + if (overwrite) { + hasKeys = true; + } + + while (i--) { + op = ops[i]; + val = ret[op]; + hasDollarKey = hasDollarKey || op.charAt(0) === '$'; + if (val && + val.constructor.name === 'Object' && + (!overwrite || hasDollarKey)) { + hasKeys |= this._walkUpdatePath(val, op); + } else if (overwrite && ret.constructor.name === 'Object') { + // if we are just using overwrite, cast the query and then we will + // *always* return the value, even if it is an empty object. We need to + // set hasKeys above because we need to account for the case where the + // user passes {} and wants to clobber the whole document + // Also, _walkUpdatePath expects an operation, so give it $set since that + // is basically what we're doing + this._walkUpdatePath(ret, '$set'); + } else { + var msg = 'Invalid atomic update value for ' + op + '. ' + + 'Expected an object, received ' + typeof val; + throw new Error(msg); + } + } + + return hasKeys && ret; +}; + +/** + * Walk each path of obj and cast its values + * according to its schema. + * + * @param {Object} obj - part of a query + * @param {String} op - the atomic operator ($pull, $set, etc) + * @param {String} pref - path prefix (internal only) + * @return {Bool} true if this path has keys to update + * @api private + */ + +Query.prototype._walkUpdatePath = function _walkUpdatePath(obj, op, pref) { + var prefix = pref ? pref + '.' : '', + keys = Object.keys(obj), + i = keys.length, + hasKeys = false, + schema, + key, + val; + + var strict = 'strict' in this._mongooseOptions + ? this._mongooseOptions.strict + : this.model.schema.options.strict; + + while (i--) { + key = keys[i]; + val = obj[key]; + + if (val && val.constructor.name === 'Object') { + // watch for embedded doc schemas + schema = this._getSchema(prefix + key); + if (schema && schema.caster && op in castOps) { + // embedded doc schema + hasKeys = true; + + if ('$each' in val) { + obj[key] = { + $each: this._castUpdateVal(schema, val.$each, op) + }; + + if (val.$slice != null) { + obj[key].$slice = val.$slice | 0; + } + + if (val.$sort) { + obj[key].$sort = val.$sort; + } + + if (!!val.$position || val.$position === 0) { + obj[key].$position = val.$position; + } + } else { + obj[key] = this._castUpdateVal(schema, val, op); + } + } else if (op === '$currentDate') { + // $currentDate can take an object + obj[key] = this._castUpdateVal(schema, val, op); + hasKeys = true; + } else if (op === '$set' && schema) { + obj[key] = this._castUpdateVal(schema, val, op); + hasKeys = true; + } else { + var pathToCheck = (prefix + key); + var v = this.model.schema._getPathType(pathToCheck); + if (v === 'undefined') { + if (strict === 'throw') { + throw new StrictModeError(pathToCheck); + } else if (strict) { + delete obj[key]; + continue; + } + } + + // gh-2314 + // we should be able to set a schema-less field + // to an empty object literal + hasKeys |= this._walkUpdatePath(val, op, prefix + key) || + (utils.isObject(val) && Object.keys(val).length === 0); + } + } else { + schema = (key === '$each' || key === '$or' || key === '$and') + ? this._getSchema(pref) + : this._getSchema(prefix + key); + + var skip = strict && + !schema && + !/real|nested/.test(this.model.schema.pathType(prefix + key)); + + if (skip) { + if (strict === 'throw') { + throw new StrictModeError(prefix + key); + } else { + delete obj[key]; + } + } else { + // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking + // improving this. + if (op === '$rename') { + hasKeys = true; + return; + } + + hasKeys = true; + obj[key] = this._castUpdateVal(schema, val, op, key); + } + } + } + return hasKeys; +}; + +/** + * Casts `val` according to `schema` and atomic `op`. + * + * @param {Schema} schema + * @param {Object} val + * @param {String} op - the atomic operator ($pull, $set, etc) + * @param {String} [$conditional] + * @api private + */ + +Query.prototype._castUpdateVal = function _castUpdateVal(schema, val, op, $conditional) { + if (!schema) { + // non-existing schema path + return op in numberOps + ? Number(val) + : val; + } + + var cond = schema.caster && op in castOps && + (utils.isObject(val) || Array.isArray(val)); + if (cond) { + // Cast values for ops that add data to MongoDB. + // Ensures embedded documents get ObjectIds etc. + var tmp = schema.cast(val); + if (Array.isArray(val)) { + val = tmp; + } else if (schema.caster.$isSingleNested) { + val = tmp; + } else { + val = tmp[0]; + } + } + + if (op in numberOps) { + return Number(val); + } + if (op === '$currentDate') { + if (typeof val === 'object') { + return {$type: val.$type}; + } + return Boolean(val); + } + if (/^\$/.test($conditional)) { + return schema.castForQuery($conditional, val); + } + + return schema.castForQuery(val); +}; + +/*! + * castQuery + * @api private + */ + +function castQuery(query) { + try { + return query.cast(query.model); + } catch (err) { + return err; + } +} + +/*! + * castDoc + * @api private + */ + +function castDoc(query, overwrite) { + try { + return query._castUpdate(query._update, overwrite); + } catch (err) { + return err; + } +} + +/** + * Specifies paths which should be populated with other documents. + * + * ####Example: + * + * Kitten.findOne().populate('owner').exec(function (err, kitten) { + * console.log(kitten.owner.name) // Max + * }) + * + * Kitten.find().populate({ + * path: 'owner' + * , select: 'name' + * , match: { color: 'black' } + * , options: { sort: { name: -1 }} + * }).exec(function (err, kittens) { + * console.log(kittens[0].owner.name) // Zoopa + * }) + * + * // alternatively + * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) { + * console.log(kittens[0].owner.name) // Zoopa + * }) + * + * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback. + * + * @param {Object|String} path either the path to populate or an object specifying all parameters + * @param {Object|String} [select] Field selection for the population query + * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field. + * @param {Object} [match] Conditions for the population query + * @param {Object} [options] Options for the population query (sort, etc) + * @see population ./populate.html + * @see Query#select #query_Query-select + * @see Model.populate #model_Model.populate + * @return {Query} this + * @api public + */ + +Query.prototype.populate = function() { + var res = utils.populate.apply(null, arguments); + var opts = this._mongooseOptions; + + if (!utils.isObject(opts.populate)) { + opts.populate = {}; + } + + for (var i = 0; i < res.length; ++i) { + opts.populate[res[i].path] = res[i]; + } + + return this; +}; + +/** + * Casts this query to the schema of `model` + * + * ####Note + * + * If `obj` is present, it is cast instead of this query. + * + * @param {Model} model + * @param {Object} [obj] + * @return {Object} + * @api public + */ + +Query.prototype.cast = function(model, obj) { + obj || (obj = this._conditions); + + return cast(model.schema, obj); +}; + +/** + * Casts selected field arguments for field selection with mongo 2.2 + * + * query.select({ ids: { $elemMatch: { $in: [hexString] }}) + * + * @param {Object} fields + * @see https://github.com/Automattic/mongoose/issues/1091 + * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ + * @api private + */ + +Query.prototype._castFields = function _castFields(fields) { + var selected, + elemMatchKeys, + keys, + key, + out, + i; + + if (fields) { + keys = Object.keys(fields); + elemMatchKeys = []; + i = keys.length; + + // collect $elemMatch args + while (i--) { + key = keys[i]; + if (fields[key].$elemMatch) { + selected || (selected = {}); + selected[key] = fields[key]; + elemMatchKeys.push(key); + } + } + } + + if (selected) { + // they passed $elemMatch, cast em + try { + out = this.cast(this.model, selected); + } catch (err) { + return err; + } + + // apply the casted field args + i = elemMatchKeys.length; + while (i--) { + key = elemMatchKeys[i]; + fields[key] = out[key]; + } + } + + return fields; +}; + +/** + * Applies schematype selected options to this query. + * @api private + */ + +Query.prototype._applyPaths = function applyPaths() { + // determine if query is selecting or excluding fields + + var fields = this._fields, + exclude, + keys, + ki; + + if (fields) { + keys = Object.keys(fields); + ki = keys.length; + + while (ki--) { + if (keys[ki][0] === '+') continue; + exclude = fields[keys[ki]] === 0; + break; + } + } + + // if selecting, apply default schematype select:true fields + // if excluding, apply schematype select:false fields + + var selected = [], + excluded = [], + seen = []; + + var analyzePath = function(path, type) { + if (typeof type.selected !== 'boolean') return; + + var plusPath = '+' + path; + if (fields && plusPath in fields) { + // forced inclusion + delete fields[plusPath]; + + // if there are other fields being included, add this one + // if no other included fields, leave this out (implied inclusion) + if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) { + fields[path] = 1; + } + + return; + } + + // check for parent exclusions + var root = path.split('.')[0]; + if (~excluded.indexOf(root)) return; + + (type.selected ? selected : excluded).push(path); + }; + + var analyzeSchema = function(schema, prefix) { + prefix || (prefix = ''); + + // avoid recursion + if (~seen.indexOf(schema)) return; + seen.push(schema); + + schema.eachPath(function(path, type) { + if (prefix) path = prefix + '.' + path; + + analyzePath(path, type); + + // array of subdocs? + if (type.schema) { + analyzeSchema(type.schema, path); + } + }); + }; + + analyzeSchema(this.model.schema); + + switch (exclude) { + case true: + excluded.length && this.select('-' + excluded.join(' -')); + break; + case false: + if (this.model.schema && this.model.schema.paths['_id'] && + this.model.schema.paths['_id'].options && this.model.schema.paths['_id'].options.select === false) { + selected.push('-_id'); + } + selected.length && this.select(selected.join(' ')); + break; + case undefined: + // user didn't specify fields, implies returning all fields. + // only need to apply excluded fields + excluded.length && this.select('-' + excluded.join(' -')); + break; + } + seen = excluded = selected = keys = fields = null; +}; + +/** + * Returns a Node.js 0.8 style [read stream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface. + * + * ####Example + * + * // follows the nodejs 0.8 stream api + * Thing.find({ name: /^hello/ }).stream().pipe(res) + * + * // manual streaming + * var stream = Thing.find({ name: /^hello/ }).stream(); + * + * stream.on('data', function (doc) { + * // do something with the mongoose document + * }).on('error', function (err) { + * // handle the error + * }).on('close', function () { + * // the stream is closed + * }); + * + * ####Valid options + * + * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`. + * + * ####Example + * + * // JSON.stringify all documents before emitting + * var stream = Thing.find().stream({ transform: JSON.stringify }); + * stream.pipe(writeStream); + * + * @return {QueryStream} + * @param {Object} [options] + * @see QueryStream + * @api public + */ + +Query.prototype.stream = function stream(opts) { + this._applyPaths(); + this._fields = this._castFields(this._fields); + return new QueryStream(this, opts); +}; + +// the rest of these are basically to support older Mongoose syntax with mquery + +/** + * _DEPRECATED_ Alias of `maxScan` + * + * @deprecated + * @see maxScan #query_Query-maxScan + * @method maxscan + * @memberOf Query + */ + +Query.prototype.maxscan = Query.base.maxScan; + +/** + * Sets the tailable option (for use with capped collections). + * + * ####Example + * + * query.tailable() // true + * query.tailable(true) + * query.tailable(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Boolean} bool defaults to true + * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/ + * @api public + */ + +Query.prototype.tailable = function(val, opts) { + // we need to support the tailable({ awaitdata : true }) as well as the + // tailable(true, {awaitdata :true}) syntax that mquery does not support + if (val && val.constructor.name === 'Object') { + opts = val; + val = true; + } + + if (val === undefined) { + val = true; + } + + if (opts && typeof opts === 'object') { + for (var key in opts) { + if (key === 'awaitdata') { + // For backwards compatibility + this.options[key] = !!opts[key]; + } else { + this.options[key] = opts[key]; + } + } + } + + return Query.base.tailable.call(this, val); +}; + +/** + * Declares an intersects query for `geometry()`. + * + * ####Example + * + * query.where('path').intersects().geometry({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * query.where('path').intersects({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * ####NOTE: + * + * **MUST** be used after `where()`. + * + * ####NOTE: + * + * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). + * + * @method intersects + * @memberOf Query + * @param {Object} [arg] + * @return {Query} this + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/ + * @api public + */ + +/** + * Specifies a `$geometry` condition + * + * ####Example + * + * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] + * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + * + * // or + * var polyB = [[ 0, 0 ], [ 1, 1 ]] + * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + * + * // or + * var polyC = [ 0, 0 ] + * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + * + * // or + * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + * + * The argument is assigned to the most recent path passed to `where()`. + * + * ####NOTE: + * + * `geometry()` **must** come after either `intersects()` or `within()`. + * + * The `object` argument must contain `type` and `coordinates` properties. + * - type {String} + * - coordinates {Array} + * + * @method geometry + * @memberOf Query + * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. + * @return {Query} this + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/** + * Specifies a `$near` or `$nearSphere` condition + * + * These operators return documents sorted by distance. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10] }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); + * query.near('loc', { center: [10, 10], maxDistance: 5 }); + * + * @method near + * @memberOf Query + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see $near http://docs.mongodb.org/manual/reference/operator/near/ + * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/*! + * Overwriting mquery is needed to support a couple different near() forms found in older + * versions of mongoose + * near([1,1]) + * near(1,1) + * near(field, [1,2]) + * near(field, 1, 2) + * In addition to all of the normal forms supported by mquery + */ + +Query.prototype.near = function() { + var params = []; + var sphere = this._mongooseOptions.nearSphere; + + // TODO refactor + + if (arguments.length === 1) { + if (Array.isArray(arguments[0])) { + params.push({center: arguments[0], spherical: sphere}); + } else if (typeof arguments[0] === 'string') { + // just passing a path + params.push(arguments[0]); + } else if (utils.isObject(arguments[0])) { + if (typeof arguments[0].spherical !== 'boolean') { + arguments[0].spherical = sphere; + } + params.push(arguments[0]); + } else { + throw new TypeError('invalid argument'); + } + } else if (arguments.length === 2) { + if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') { + params.push({center: [arguments[0], arguments[1]], spherical: sphere}); + } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) { + params.push(arguments[0]); + params.push({center: arguments[1], spherical: sphere}); + } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) { + params.push(arguments[0]); + if (typeof arguments[1].spherical !== 'boolean') { + arguments[1].spherical = sphere; + } + params.push(arguments[1]); + } else { + throw new TypeError('invalid argument'); + } + } else if (arguments.length === 3) { + if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number' + && typeof arguments[2] === 'number') { + params.push(arguments[0]); + params.push({center: [arguments[1], arguments[2]], spherical: sphere}); + } else { + throw new TypeError('invalid argument'); + } + } else { + throw new TypeError('invalid argument'); + } + + return Query.base.near.apply(this, params); +}; + +/** + * _DEPRECATED_ Specifies a `$nearSphere` condition + * + * ####Example + * + * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); + * + * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10], spherical: true }); + * + * @deprecated + * @see near() #query_Query-near + * @see $near http://docs.mongodb.org/manual/reference/operator/near/ + * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + */ + +Query.prototype.nearSphere = function() { + this._mongooseOptions.nearSphere = true; + this.near.apply(this, arguments); + return this; +}; + +/** + * Specifies a $polygon condition + * + * ####Example + * + * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) + * query.polygon('loc', [10,20], [13, 25], [7,15]) + * + * @method polygon + * @memberOf Query + * @param {String|Array} [path] + * @param {Array|Object} [coordinatePairs...] + * @return {Query} this + * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/** + * Specifies a $box condition + * + * ####Example + * + * var lowerLeft = [40.73083, -73.99756] + * var upperRight= [40.741404, -73.988135] + * + * query.where('loc').within().box(lowerLeft, upperRight) + * query.box({ ll : lowerLeft, ur : upperRight }) + * + * @method box + * @memberOf Query + * @see $box http://docs.mongodb.org/manual/reference/operator/box/ + * @see within() Query#within #query_Query-within + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @param {Object} val + * @param [Array] Upper Right Coords + * @return {Query} this + * @api public + */ + +/*! + * this is needed to support the mongoose syntax of: + * box(field, { ll : [x,y], ur : [x2,y2] }) + * box({ ll : [x,y], ur : [x2,y2] }) + */ + +Query.prototype.box = function(ll, ur) { + if (!Array.isArray(ll) && utils.isObject(ll)) { + ur = ll.ur; + ll = ll.ll; + } + return Query.base.box.call(this, ll, ur); +}; + +/** + * Specifies a $center or $centerSphere condition. + * + * ####Example + * + * var area = { center: [50, 50], radius: 10, unique: true } + * query.where('loc').within().circle(area) + * // alternatively + * query.circle('loc', area); + * + * // spherical calculations + * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } + * query.where('loc').within().circle(area) + * // alternatively + * query.circle('loc', area); + * + * New in 3.7.0 + * + * @method circle + * @memberOf Query + * @param {String} [path] + * @param {Object} area + * @return {Query} this + * @see $center http://docs.mongodb.org/manual/reference/operator/center/ + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/within/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/** + * _DEPRECATED_ Alias for [circle](#query_Query-circle) + * + * **Deprecated.** Use [circle](#query_Query-circle) instead. + * + * @deprecated + * @method center + * @memberOf Query + * @api public + */ + +Query.prototype.center = Query.base.circle; + +/** + * _DEPRECATED_ Specifies a $centerSphere condition + * + * **Deprecated.** Use [circle](#query_Query-circle) instead. + * + * ####Example + * + * var area = { center: [50, 50], radius: 10 }; + * query.where('loc').within().centerSphere(area); + * + * @deprecated + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @api public + */ + +Query.prototype.centerSphere = function() { + if (arguments[0] && arguments[0].constructor.name === 'Object') { + arguments[0].spherical = true; + } + + if (arguments[1] && arguments[1].constructor.name === 'Object') { + arguments[1].spherical = true; + } + + Query.base.circle.apply(this, arguments); +}; + +/** + * Determines if field selection has been made. + * + * @method selected + * @memberOf Query + * @return {Boolean} + * @api public + */ + +/** + * Executes this query and returns a promise + * + * @method then + * @memberOf Query + * @return {Promise} + * @api public + */ + +/** + * Determines if inclusive field selection has been made. + * + * query.selectedInclusively() // false + * query.select('name') + * query.selectedInclusively() // true + * + * @method selectedInclusively + * @memberOf Query + * @return {Boolean} + * @api public + */ + +/** + * Determines if exclusive field selection has been made. + * + * query.selectedExclusively() // false + * query.select('-name') + * query.selectedExclusively() // true + * query.selectedInclusively() // false + * + * @method selectedExclusively + * @memberOf Query + * @return {Boolean} + * @api public + */ + +/*! + * Export + */ + +module.exports = Query; diff --git a/5-2/service/node_modules/mongoose/lib/queryhelpers.js b/5-2/service/node_modules/mongoose/lib/queryhelpers.js new file mode 100644 index 0000000..3e0b82d --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/queryhelpers.js @@ -0,0 +1,78 @@ + +/*! + * Module dependencies + */ + +var utils = require('./utils'); + +/*! + * Prepare a set of path options for query population. + * + * @param {Query} query + * @param {Object} options + * @return {Array} + */ + +exports.preparePopulationOptions = function preparePopulationOptions(query, options) { + var pop = utils.object.vals(query.options.populate); + + // lean options should trickle through all queries + if (options.lean) pop.forEach(makeLean); + + return pop; +}; + +/*! + * Prepare a set of path options for query population. This is the MongooseQuery + * version + * + * @param {Query} query + * @param {Object} options + * @return {Array} + */ + +exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) { + var pop = utils.object.vals(query._mongooseOptions.populate); + + // lean options should trickle through all queries + if (options.lean) pop.forEach(makeLean); + + return pop; +}; + +/*! + * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise, + * it returns an instance of the given model. + * + * @param {Model} model + * @param {Object} doc + * @param {Object} fields + * + * @return {Model} + */ +exports.createModel = function createModel(model, doc, fields) { + var discriminatorMapping = model.schema + ? model.schema.discriminatorMapping + : null; + + var key = discriminatorMapping && discriminatorMapping.isRoot + ? discriminatorMapping.key + : null; + + if (key && doc[key] && model.discriminators && model.discriminators[doc[key]]) { + return new model.discriminators[doc[key]](undefined, fields, true); + } + + return new model(undefined, fields, true); +}; + +/*! + * Set each path query option to lean + * + * @param {Object} option + */ + +function makeLean(option) { + option.options || (option.options = {}); + option.options.lean = true; +} diff --git a/5-2/service/node_modules/mongoose/lib/querystream.js b/5-2/service/node_modules/mongoose/lib/querystream.js new file mode 100644 index 0000000..25bcb9e --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/querystream.js @@ -0,0 +1,367 @@ +/* eslint no-empty: 1 */ + +/*! + * Module dependencies. + */ + +var Stream = require('stream').Stream; +var utils = require('./utils'); +var helpers = require('./queryhelpers'); +var K = function(k) { + return k; +}; + +/** + * Provides a Node.js 0.8 style [ReadStream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface for Queries. + * + * var stream = Model.find().stream(); + * + * stream.on('data', function (doc) { + * // do something with the mongoose document + * }).on('error', function (err) { + * // handle the error + * }).on('close', function () { + * // the stream is closed + * }); + * + * + * The stream interface allows us to simply "plug-in" to other _Node.js 0.8_ style write streams. + * + * Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream); + * + * ####Valid options + * + * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`. + * + * ####Example + * + * // JSON.stringify all documents before emitting + * var stream = Thing.find().stream({ transform: JSON.stringify }); + * stream.pipe(writeStream); + * + * _NOTE: plugging into an HTTP response will *not* work out of the box. Those streams expect only strings or buffers to be emitted, so first formatting our documents as strings/buffers is necessary._ + * + * _NOTE: these streams are Node.js 0.8 style read streams which differ from Node.js 0.10 style. Node.js 0.10 streams are not well tested yet and are not guaranteed to work._ + * + * @param {Query} query + * @param {Object} [options] + * @inherits NodeJS Stream http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream + * @event `data`: emits a single Mongoose document + * @event `error`: emits when an error occurs during streaming. This will emit _before_ the `close` event. + * @event `close`: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually `destroy`ed. After this event, no more events are emitted. + * @api public + */ + +function QueryStream(query, options) { + Stream.call(this); + + this.query = query; + this.readable = true; + this.paused = false; + this._cursor = null; + this._destroyed = null; + this._fields = null; + this._buffer = null; + this._inline = T_INIT; + this._running = false; + this._transform = options && typeof options.transform === 'function' + ? options.transform + : K; + + // give time to hook up events + var _this = this; + process.nextTick(function() { + _this._init(); + }); +} + +/*! + * Inherit from Stream + */ + +QueryStream.prototype.__proto__ = Stream.prototype; + +/** + * Flag stating whether or not this stream is readable. + * + * @property readable + * @api public + */ + +QueryStream.prototype.readable; + +/** + * Flag stating whether or not this stream is paused. + * + * @property paused + * @api public + */ + +QueryStream.prototype.paused; + +// trampoline flags +var T_INIT = 0; +var T_IDLE = 1; +var T_CONT = 2; + +/** + * Initializes the query. + * + * @api private + */ + +QueryStream.prototype._init = function() { + if (this._destroyed) { + return; + } + + var query = this.query, + model = query.model, + options = query._optionsForExec(model), + _this = this; + + try { + query.cast(model); + } catch (err) { + return _this.destroy(err); + } + + _this._fields = utils.clone(query._fields); + options.fields = query._castFields(_this._fields); + + model.collection.find(query._conditions, options, function(err, cursor) { + if (err) { + return _this.destroy(err); + } + _this._cursor = cursor; + _this._next(); + }); +}; + +/** + * Trampoline for pulling the next doc from cursor. + * + * @see QueryStream#__next #querystream_QueryStream-__next + * @api private + */ + +QueryStream.prototype._next = function _next() { + if (this.paused || this._destroyed) { + this._running = false; + return this._running; + } + + this._running = true; + + if (this._buffer && this._buffer.length) { + var arg; + while (!this.paused && !this._destroyed && (arg = this._buffer.shift())) { // eslint-disable-line no-cond-assign + this._onNextObject.apply(this, arg); + } + } + + // avoid stack overflows with large result sets. + // trampoline instead of recursion. + while (this.__next()) { + } +}; + +/** + * Pulls the next doc from the cursor. + * + * @see QueryStream#_next #querystream_QueryStream-_next + * @api private + */ + +QueryStream.prototype.__next = function() { + if (this.paused || this._destroyed) { + this._running = false; + return this._running; + } + + var _this = this; + _this._inline = T_INIT; + + _this._cursor.nextObject(function cursorcb(err, doc) { + _this._onNextObject(err, doc); + }); + + // if onNextObject() was already called in this tick + // return ourselves to the trampoline. + if (T_CONT === this._inline) { + return true; + } + // onNextObject() hasn't fired yet. tell onNextObject + // that its ok to call _next b/c we are not within + // the trampoline anymore. + this._inline = T_IDLE; +}; + +/** + * Transforms raw `doc`s returned from the cursor into a model instance. + * + * @param {Error|null} err + * @param {Object} doc + * @api private + */ + +QueryStream.prototype._onNextObject = function _onNextObject(err, doc) { + if (this._destroyed) { + return; + } + + if (this.paused) { + this._buffer || (this._buffer = []); + this._buffer.push([err, doc]); + this._running = false; + return this._running; + } + + if (err) { + return this.destroy(err); + } + + // when doc is null we hit the end of the cursor + if (!doc) { + this.emit('end'); + return this.destroy(); + } + + var opts = this.query._mongooseOptions; + + if (!opts.populate) { + return opts.lean === true ? + emit(this, doc) : + createAndEmit(this, null, doc); + } + + var _this = this; + var pop = helpers.preparePopulationOptionsMQ(_this.query, _this.query._mongooseOptions); + + // Hack to work around gh-3108 + pop.forEach(function(option) { + delete option.model; + }); + + pop.__noPromise = true; + _this.query.model.populate(doc, pop, function(err, doc) { + if (err) { + return _this.destroy(err); + } + return opts.lean === true ? + emit(_this, doc) : + createAndEmit(_this, pop, doc); + }); +}; + +function createAndEmit(self, populatedIds, doc) { + var instance = helpers.createModel(self.query.model, doc, self._fields); + var opts = populatedIds ? + {populated: populatedIds} : + undefined; + + instance.init(doc, opts, function(err) { + if (err) { + return self.destroy(err); + } + emit(self, instance); + }); +} + +/*! + * Emit a data event and manage the trampoline state + */ + +function emit(self, doc) { + self.emit('data', self._transform(doc)); + + // trampoline management + if (T_IDLE === self._inline) { + // no longer in trampoline. restart it. + self._next(); + } else { + // in a trampoline. tell __next that its + // ok to continue jumping. + self._inline = T_CONT; + } +} + +/** + * Pauses this stream. + * + * @api public + */ + +QueryStream.prototype.pause = function() { + this.paused = true; +}; + +/** + * Resumes this stream. + * + * @api public + */ + +QueryStream.prototype.resume = function() { + this.paused = false; + + if (!this._cursor) { + // cannot start if not initialized + return; + } + + // are we within the trampoline? + if (T_INIT === this._inline) { + return; + } + + if (!this._running) { + // outside QueryStream control, need manual restart + return this._next(); + } +}; + +/** + * Destroys the stream, closing the underlying cursor. No more events will be emitted. + * + * @param {Error} [err] + * @api public + */ + +QueryStream.prototype.destroy = function(err) { + if (this._destroyed) { + return; + } + this._destroyed = true; + this._running = false; + this.readable = false; + + if (this._cursor) { + this._cursor.close(); + } + + if (err) { + this.emit('error', err); + } + + this.emit('close'); +}; + +/** + * Pipes this query stream into another stream. This method is inherited from NodeJS Streams. + * + * ####Example: + * + * query.stream().pipe(writeStream [, options]) + * + * @method pipe + * @memberOf QueryStream + * @see NodeJS http://nodejs.org/api/stream.html + * @api public + */ + +/*! + * Module exports + */ + +module.exports = exports = QueryStream; diff --git a/5-2/service/node_modules/mongoose/lib/schema.js b/5-2/service/node_modules/mongoose/lib/schema.js new file mode 100644 index 0000000..06b2d7a --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema.js @@ -0,0 +1,1374 @@ +/*! + * Module dependencies. + */ + +var readPref = require('./drivers').ReadPreference; +var EventEmitter = require('events').EventEmitter; +var VirtualType = require('./virtualtype'); +var utils = require('./utils'); +var MongooseTypes; +var Kareem = require('kareem'); +var async = require('async'); + +var IS_QUERY_HOOK = { + count: true, + find: true, + findOne: true, + findOneAndUpdate: true, + findOneAndRemove: true, + update: true +}; + +/** + * Schema constructor. + * + * ####Example: + * + * var child = new Schema({ name: String }); + * var schema = new Schema({ name: String, age: Number, children: [child] }); + * var Tree = mongoose.model('Tree', schema); + * + * // setting schema options + * new Schema({ name: String }, { _id: false, autoIndex: false }) + * + * ####Options: + * + * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option) + * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true + * - [capped](/docs/guide.html#capped): bool - defaults to false + * - [collection](/docs/guide.html#collection): string - no default + * - [emitIndexErrors](/docs/guide.html#emitIndexErrors): bool - defaults to false. + * - [id](/docs/guide.html#id): bool - defaults to true + * - [_id](/docs/guide.html#_id): bool - defaults to true + * - `minimize`: bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true + * - [read](/docs/guide.html#read): string + * - [safe](/docs/guide.html#safe): bool - defaults to true. + * - [shardKey](/docs/guide.html#shardKey): bool - defaults to `null` + * - [strict](/docs/guide.html#strict): bool - defaults to true + * - [toJSON](/docs/guide.html#toJSON) - object - no default + * - [toObject](/docs/guide.html#toObject) - object - no default + * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type' + * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` + * - [versionKey](/docs/guide.html#versionKey): string - defaults to "__v" + * + * ####Note: + * + * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ + * + * @param {Object} definition + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted after the schema is compiled into a `Model`. + * @api public + */ + +function Schema(obj, options) { + if (!(this instanceof Schema)) { + return new Schema(obj, options); + } + + this.paths = {}; + this.subpaths = {}; + this.virtuals = {}; + this.singleNestedPaths = {}; + this.nested = {}; + this.inherits = {}; + this.callQueue = []; + this._indexes = []; + this.methods = {}; + this.statics = {}; + this.tree = {}; + this._requiredpaths = undefined; + this.discriminatorMapping = undefined; + this._indexedpaths = undefined; + + this.s = { + hooks: new Kareem(), + queryHooks: IS_QUERY_HOOK + }; + + this.options = this.defaultOptions(options); + + // build paths + if (obj) { + this.add(obj); + } + + // check if _id's value is a subdocument (gh-2276) + var _idSubDoc = obj && obj._id && utils.isObject(obj._id); + + // ensure the documents get an auto _id unless disabled + var auto_id = !this.paths['_id'] && + (!this.options.noId && this.options._id) && !_idSubDoc; + + if (auto_id) { + obj = {_id: {auto: true}}; + obj._id[this.options.typeKey] = Schema.ObjectId; + this.add(obj); + } + + // ensure the documents receive an id getter unless disabled + var autoid = !this.paths['id'] && + (!this.options.noVirtualId && this.options.id); + if (autoid) { + this.virtual('id').get(idGetter); + } + + for (var i = 0; i < this._defaultMiddleware.length; ++i) { + var m = this._defaultMiddleware[i]; + this[m.kind](m.hook, !!m.isAsync, m.fn); + } + + // adds updatedAt and createdAt timestamps to documents if enabled + var timestamps = this.options.timestamps; + if (timestamps) { + var createdAt = timestamps.createdAt || 'createdAt', + updatedAt = timestamps.updatedAt || 'updatedAt', + schemaAdditions = {}; + + schemaAdditions[updatedAt] = Date; + + if (!this.paths[createdAt]) { + schemaAdditions[createdAt] = Date; + } + + this.add(schemaAdditions); + + this.pre('save', function(next) { + var defaultTimestamp = new Date(); + + if (!this[createdAt]) { + this[createdAt] = auto_id ? this._id.getTimestamp() : defaultTimestamp; + } + + this[updatedAt] = this.isNew ? this[createdAt] : defaultTimestamp; + + next(); + }); + + var genUpdates = function() { + var now = new Date(); + var updates = {$set: {}, $setOnInsert: {}}; + updates.$set[updatedAt] = now; + updates.$setOnInsert[createdAt] = now; + + return updates; + }; + + this.pre('findOneAndUpdate', function(next) { + this.findOneAndUpdate({}, genUpdates()); + next(); + }); + + this.pre('update', function(next) { + this.update({}, genUpdates()); + next(); + }); + } +} + +/*! + * Returns this documents _id cast to a string. + */ + +function idGetter() { + if (this.$__._id) { + return this.$__._id; + } + + this.$__._id = this._id == null + ? null + : String(this._id); + return this.$__._id; +} + +/*! + * Inherit from EventEmitter. + */ +Schema.prototype = Object.create(EventEmitter.prototype); +Schema.prototype.constructor = Schema; +Schema.prototype.instanceOfSchema = true; + +/** + * Default middleware attached to a schema. Cannot be changed. + * + * This field is used to make sure discriminators don't get multiple copies of + * built-in middleware. Declared as a constant because changing this at runtime + * may lead to instability with Model.prototype.discriminator(). + * + * @api private + * @property _defaultMiddleware + */ +Object.defineProperty(Schema.prototype, '_defaultMiddleware', { + configurable: false, + enumerable: false, + writable: false, + value: [{ + kind: 'pre', + hook: 'save', + fn: function(next, options) { + // Nested docs have their own presave + if (this.ownerDocument) { + return next(); + } + + var hasValidateBeforeSaveOption = options && + (typeof options === 'object') && + ('validateBeforeSave' in options); + + var shouldValidate; + if (hasValidateBeforeSaveOption) { + shouldValidate = !!options.validateBeforeSave; + } else { + shouldValidate = this.schema.options.validateBeforeSave; + } + + // Validate + if (shouldValidate) { + // HACK: use $__original_validate to avoid promises so bluebird doesn't + // complain + if (this.$__original_validate) { + this.$__original_validate({__noPromise: true}, function(error) { + next(error); + }); + } else { + this.validate({__noPromise: true}, function(error) { + next(error); + }); + } + } else { + next(); + } + } + }, { + kind: 'pre', + hook: 'save', + isAsync: true, + fn: function(next, done) { + var subdocs = this.$__getAllSubdocs(); + + if (!subdocs.length || this.$__preSavingFromParent) { + done(); + next(); + return; + } + + async.each(subdocs, function(subdoc, cb) { + subdoc.$__preSavingFromParent = true; + subdoc.save(function(err) { + cb(err); + }); + }, function(error) { + for (var i = 0; i < subdocs.length; ++i) { + delete subdocs[i].$__preSavingFromParent; + } + if (error) { + done(error); + return; + } + next(); + done(); + }); + } + }] +}); + +/** + * Schema as flat paths + * + * ####Example: + * { + * '_id' : SchemaType, + * , 'nested.key' : SchemaType, + * } + * + * @api private + * @property paths + */ + +Schema.prototype.paths; + +/** + * Schema as a tree + * + * ####Example: + * { + * '_id' : ObjectId + * , 'nested' : { + * 'key' : String + * } + * } + * + * @api private + * @property tree + */ + +Schema.prototype.tree; + +/** + * Returns default options for this schema, merged with `options`. + * + * @param {Object} options + * @return {Object} + * @api private + */ + +Schema.prototype.defaultOptions = function(options) { + if (options && options.safe === false) { + options.safe = {w: 0}; + } + + if (options && options.safe && options.safe.w === 0) { + // if you turn off safe writes, then versioning goes off as well + options.versionKey = false; + } + + options = utils.options({ + strict: true, + bufferCommands: true, + capped: false, // { size, max, autoIndexId } + versionKey: '__v', + discriminatorKey: '__t', + minimize: true, + autoIndex: null, + shardKey: null, + read: null, + validateBeforeSave: true, + // the following are only applied at construction time + noId: false, // deprecated, use { _id: false } + _id: true, + noVirtualId: false, // deprecated, use { id: false } + id: true, + typeKey: 'type' + }, options); + + if (options.read) { + options.read = readPref(options.read); + } + + return options; +}; + +/** + * Adds key path / schema type pairs to this schema. + * + * ####Example: + * + * var ToySchema = new Schema; + * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); + * + * @param {Object} obj + * @param {String} prefix + * @api public + */ + +Schema.prototype.add = function add(obj, prefix) { + prefix = prefix || ''; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + + if (obj[key] == null) { + throw new TypeError('Invalid value for schema path `' + prefix + key + '`'); + } + + if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) { + throw new TypeError('Invalid value for schema Array path `' + prefix + key + '`'); + } + + if (utils.isObject(obj[key]) && + (!obj[key].constructor || utils.getFunctionName(obj[key].constructor) === 'Object') && + (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type))) { + if (Object.keys(obj[key]).length) { + // nested object { last: { name: String }} + this.nested[prefix + key] = true; + this.add(obj[key], prefix + key + '.'); + } else { + this.path(prefix + key, obj[key]); // mixed type + } + } else { + this.path(prefix + key, obj[key]); + } + } +}; + +/** + * Reserved document keys. + * + * Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error. + * + * on, emit, _events, db, get, set, init, isNew, errors, schema, options, modelName, collection, _pres, _posts, toObject + * + * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. + * + * var schema = new Schema(..); + * schema.methods.init = function () {} // potentially breaking + */ + +Schema.reserved = Object.create(null); +var reserved = Schema.reserved; +// EventEmitter +reserved.emit = +reserved.on = +reserved.once = +reserved.listeners = +reserved.removeListener = +// document properties and functions +reserved.collection = +reserved.db = +reserved.errors = +reserved.init = +reserved.isModified = +reserved.isNew = +reserved.get = +reserved.modelName = +reserved.save = +reserved.schema = +reserved.set = +reserved.toObject = +reserved.validate = +// hooks.js +reserved._pres = reserved._posts = 1; + +/** + * Document keys to print warnings for + */ + +var warnings = {}; +warnings.increment = '`increment` should not be used as a schema path name ' + + 'unless you have disabled versioning.'; + +/** + * Gets/sets schema paths. + * + * Sets a path (if arity 2) + * Gets a path (if arity 1) + * + * ####Example + * + * schema.path('name') // returns a SchemaType + * schema.path('name', Number) // changes the schemaType of `name` to Number + * + * @param {String} path + * @param {Object} constructor + * @api public + */ + +Schema.prototype.path = function(path, obj) { + if (obj === undefined) { + if (this.paths[path]) { + return this.paths[path]; + } + if (this.subpaths[path]) { + return this.subpaths[path]; + } + if (this.singleNestedPaths[path]) { + return this.singleNestedPaths[path]; + } + + // subpaths? + return /\.\d+\.?.*$/.test(path) + ? getPositionalPath(this, path) + : undefined; + } + + // some path names conflict with document methods + if (reserved[path]) { + throw new Error('`' + path + '` may not be used as a schema pathname'); + } + + if (warnings[path]) { + console.log('WARN: ' + warnings[path]); + } + + // update the tree + var subpaths = path.split(/\./), + last = subpaths.pop(), + branch = this.tree; + + subpaths.forEach(function(sub, i) { + if (!branch[sub]) { + branch[sub] = {}; + } + if (typeof branch[sub] !== 'object') { + var msg = 'Cannot set nested path `' + path + '`. ' + + 'Parent path `' + + subpaths.slice(0, i).concat([sub]).join('.') + + '` already set to type ' + branch[sub].name + + '.'; + throw new Error(msg); + } + branch = branch[sub]; + }); + + branch[last] = utils.clone(obj); + + this.paths[path] = Schema.interpretAsType(path, obj, this.options); + if (this.paths[path].$isSingleNested) { + for (var key in this.paths[path].schema.paths) { + this.singleNestedPaths[path + '.' + key] = + this.paths[path].schema.paths[key]; + } + for (key in this.paths[path].schema.singleNestedPaths) { + this.singleNestedPaths[path + '.' + key] = + this.paths[path].schema.singleNestedPaths[key]; + } + } + return this; +}; + +/** + * Converts type arguments into Mongoose Types. + * + * @param {String} path + * @param {Object} obj constructor + * @api private + */ + +Schema.interpretAsType = function(path, obj, options) { + if (obj.constructor) { + var constructorName = utils.getFunctionName(obj.constructor); + if (constructorName !== 'Object') { + var oldObj = obj; + obj = {}; + obj[options.typeKey] = oldObj; + } + } + + // Get the type making sure to allow keys named "type" + // and default to mixed if not specified. + // { type: { type: String, default: 'freshcut' } } + var type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type) + ? obj[options.typeKey] + : {}; + + if (utils.getFunctionName(type.constructor) === 'Object' || type === 'mixed') { + return new MongooseTypes.Mixed(path, obj); + } + + if (Array.isArray(type) || Array === type || type === 'array') { + // if it was specified through { type } look for `cast` + var cast = (Array === type || type === 'array') + ? obj.cast + : type[0]; + + if (cast && cast.instanceOfSchema) { + return new MongooseTypes.DocumentArray(path, cast, obj); + } + + if (typeof cast === 'string') { + cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; + } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type)) + && utils.getFunctionName(cast.constructor) === 'Object' + && Object.keys(cast).length) { + // The `minimize` and `typeKey` options propagate to child schemas + // declared inline, like `{ arr: [{ val: { $type: String } }] }`. + // See gh-3560 + var childSchemaOptions = {minimize: options.minimize}; + if (options.typeKey) { + childSchemaOptions.typeKey = options.typeKey; + } + var childSchema = new Schema(cast, childSchemaOptions); + return new MongooseTypes.DocumentArray(path, childSchema, obj); + } + + return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj); + } + + if (type && type.instanceOfSchema) { + return new MongooseTypes.Embedded(type, path, obj); + } + + var name; + if (Buffer.isBuffer(type)) { + name = 'Buffer'; + } else { + name = typeof type === 'string' + ? type + // If not string, `type` is a function. Outside of IE, function.name + // gives you the function name. In IE, you need to compute it + : type.schemaName || utils.getFunctionName(type); + } + + if (name) { + name = name.charAt(0).toUpperCase() + name.substring(1); + } + + if (undefined == MongooseTypes[name]) { + throw new TypeError('Undefined type `' + name + '` at `' + path + + '`\n Did you try nesting Schemas? ' + + 'You can only nest using refs or arrays.'); + } + + return new MongooseTypes[name](path, obj); +}; + +/** + * Iterates the schemas paths similar to Array#forEach. + * + * The callback is passed the pathname and schemaType as arguments on each iteration. + * + * @param {Function} fn callback function + * @return {Schema} this + * @api public + */ + +Schema.prototype.eachPath = function(fn) { + var keys = Object.keys(this.paths), + len = keys.length; + + for (var i = 0; i < len; ++i) { + fn(keys[i], this.paths[keys[i]]); + } + + return this; +}; + +/** + * Returns an Array of path strings that are required by this schema. + * + * @api public + * @param {Boolean} invalidate refresh the cache + * @return {Array} + */ + +Schema.prototype.requiredPaths = function requiredPaths(invalidate) { + if (this._requiredpaths && !invalidate) { + return this._requiredpaths; + } + + var paths = Object.keys(this.paths), + i = paths.length, + ret = []; + + while (i--) { + var path = paths[i]; + if (this.paths[path].isRequired) { + ret.push(path); + } + } + this._requiredpaths = ret; + return this._requiredpaths; +}; + +/** + * Returns indexes from fields and schema-level indexes (cached). + * + * @api private + * @return {Array} + */ + +Schema.prototype.indexedPaths = function indexedPaths() { + if (this._indexedpaths) { + return this._indexedpaths; + } + this._indexedpaths = this.indexes(); + return this._indexedpaths; +}; + +/** + * Returns the pathType of `path` for this schema. + * + * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. + * + * @param {String} path + * @return {String} + * @api public + */ + +Schema.prototype.pathType = function(path) { + if (path in this.paths) { + return 'real'; + } + if (path in this.virtuals) { + return 'virtual'; + } + if (path in this.nested) { + return 'nested'; + } + if (path in this.subpaths) { + return 'real'; + } + if (path in this.singleNestedPaths) { + return 'real'; + } + + if (/\.\d+\.|\.\d+$/.test(path)) { + return getPositionalPathType(this, path); + } + return 'adhocOrUndefined'; +}; + +/** + * Returns true iff this path is a child of a mixed schema. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Schema.prototype.hasMixedParent = function(path) { + var subpaths = path.split(/\./g); + path = ''; + for (var i = 0; i < subpaths.length; ++i) { + path = i > 0 ? path + '.' + subpaths[i] : subpaths[i]; + if (path in this.paths && + this.paths[path] instanceof MongooseTypes.Mixed) { + return true; + } + } + + return false; +}; + +/*! + * ignore + */ + +function getPositionalPathType(self, path) { + var subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); + if (subpaths.length < 2) { + return self.paths[subpaths[0]]; + } + + var val = self.path(subpaths[0]); + var isNested = false; + if (!val) { + return val; + } + + var last = subpaths.length - 1, + subpath, + i = 1; + + for (; i < subpaths.length; ++i) { + isNested = false; + subpath = subpaths[i]; + + if (i === last && val && !val.schema && !/\D/.test(subpath)) { + if (val instanceof MongooseTypes.Array) { + // StringSchema, NumberSchema, etc + val = val.caster; + } else { + val = undefined; + } + break; + } + + // ignore if its just a position segment: path.0.subpath + if (!/\D/.test(subpath)) { + continue; + } + + if (!(val && val.schema)) { + val = undefined; + break; + } + + var type = val.schema.pathType(subpath); + isNested = (type === 'nested'); + val = val.schema.path(subpath); + } + + self.subpaths[path] = val; + if (val) { + return 'real'; + } + if (isNested) { + return 'nested'; + } + return 'adhocOrUndefined'; +} + + +/*! + * ignore + */ + +function getPositionalPath(self, path) { + getPositionalPathType(self, path); + return self.subpaths[path]; +} + +/** + * Adds a method call to the queue. + * + * @param {String} name name of the document method to call later + * @param {Array} args arguments to pass to the method + * @api public + */ + +Schema.prototype.queue = function(name, args) { + this.callQueue.push([name, args]); + return this; +}; + +/** + * Defines a pre hook for the document. + * + * ####Example + * + * var toySchema = new Schema(..); + * + * toySchema.pre('save', function (next) { + * if (!this.created) this.created = new Date; + * next(); + * }) + * + * toySchema.pre('validate', function (next) { + * if (this.name !== 'Woody') this.name = 'Woody'; + * next(); + * }) + * + * @param {String} method + * @param {Function} callback + * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 + * @api public + */ + +Schema.prototype.pre = function() { + var name = arguments[0]; + if (IS_QUERY_HOOK[name]) { + this.s.hooks.pre.apply(this.s.hooks, arguments); + return this; + } + return this.queue('pre', arguments); +}; + +/** + * Defines a post hook for the document + * + * Post hooks fire `on` the event emitted from document instances of Models compiled from this schema. + * + * var schema = new Schema(..); + * schema.post('save', function (doc) { + * console.log('this fired after a document was saved'); + * }); + * + * var Model = mongoose.model('Model', schema); + * + * var m = new Model(..); + * m.save(function (err) { + * console.log('this fires after the `post` hook'); + * }); + * + * @param {String} method name of the method to hook + * @param {Function} fn callback + * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 + * @api public + */ + +Schema.prototype.post = function(method, fn) { + if (IS_QUERY_HOOK[method]) { + this.s.hooks.post.apply(this.s.hooks, arguments); + return this; + } + // assuming that all callbacks with arity < 2 are synchronous post hooks + if (fn.length < 2) { + return this.queue('on', [arguments[0], function(doc) { + return fn.call(doc, doc); + }]); + } + + return this.queue('post', [arguments[0], function(next) { + // wrap original function so that the callback goes last, + // for compatibility with old code that is using synchronous post hooks + var _this = this; + var args = Array.prototype.slice.call(arguments, 1); + fn.call(this, this, function(err) { + return next.apply(_this, [err].concat(args)); + }); + }]); +}; + +/** + * Registers a plugin for this schema. + * + * @param {Function} plugin callback + * @param {Object} [opts] + * @see plugins + * @api public + */ + +Schema.prototype.plugin = function(fn, opts) { + fn(this, opts); + return this; +}; + +/** + * Adds an instance method to documents constructed from Models compiled from this schema. + * + * ####Example + * + * var schema = kittySchema = new Schema(..); + * + * schema.method('meow', function () { + * console.log('meeeeeoooooooooooow'); + * }) + * + * var Kitty = mongoose.model('Kitty', schema); + * + * var fizz = new Kitty; + * fizz.meow(); // meeeeeooooooooooooow + * + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. + * + * schema.method({ + * purr: function () {} + * , scratch: function () {} + * }); + * + * // later + * fizz.purr(); + * fizz.scratch(); + * + * @param {String|Object} method name + * @param {Function} [fn] + * @api public + */ + +Schema.prototype.method = function(name, fn) { + if (typeof name !== 'string') { + for (var i in name) { + this.methods[i] = name[i]; + } + } else { + this.methods[name] = fn; + } + return this; +}; + +/** + * Adds static "class" methods to Models compiled from this schema. + * + * ####Example + * + * var schema = new Schema(..); + * schema.static('findByName', function (name, callback) { + * return this.find({ name: name }, callback); + * }); + * + * var Drink = mongoose.model('Drink', schema); + * Drink.findByName('sanpellegrino', function (err, drinks) { + * // + * }); + * + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. + * + * @param {String} name + * @param {Function} fn + * @api public + */ + +Schema.prototype.static = function(name, fn) { + if (typeof name !== 'string') { + for (var i in name) { + this.statics[i] = name[i]; + } + } else { + this.statics[name] = fn; + } + return this; +}; + +/** + * Defines an index (most likely compound) for this schema. + * + * ####Example + * + * schema.index({ first: 1, last: -1 }) + * + * @param {Object} fields + * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex) + * @param {String} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link. + * @api public + */ + +Schema.prototype.index = function(fields, options) { + options || (options = {}); + + if (options.expires) { + utils.expires(options); + } + + this._indexes.push([fields, options]); + return this; +}; + +/** + * Sets/gets a schema option. + * + * ####Example + * + * schema.set('strict'); // 'true' by default + * schema.set('strict', false); // Sets 'strict' to false + * schema.set('strict'); // 'false' + * + * @param {String} key option name + * @param {Object} [value] if not passed, the current option value is returned + * @see Schema ./ + * @api public + */ + +Schema.prototype.set = function(key, value, _tags) { + if (arguments.length === 1) { + return this.options[key]; + } + + switch (key) { + case 'read': + this.options[key] = readPref(value, _tags); + break; + case 'safe': + this.options[key] = value === false + ? {w: 0} + : value; + break; + default: + this.options[key] = value; + } + + return this; +}; + +/** + * Gets a schema option. + * + * @param {String} key option name + * @api public + */ + +Schema.prototype.get = function(key) { + return this.options[key]; +}; + +/** + * The allowed index types + * + * @static indexTypes + * @receiver Schema + * @api public + */ + +var indexTypes = '2d 2dsphere hashed text'.split(' '); + +Object.defineProperty(Schema, 'indexTypes', { + get: function() { + return indexTypes; + }, + set: function() { + throw new Error('Cannot overwrite Schema.indexTypes'); + } +}); + +/** + * Compiles indexes from fields and schema-level indexes + * + * @api public + */ + +Schema.prototype.indexes = function() { + 'use strict'; + + var indexes = []; + var seenPrefix = {}; + + var collectIndexes = function(schema, prefix) { + if (seenPrefix[prefix]) { + return; + } + seenPrefix[prefix] = true; + + prefix = prefix || ''; + var key, path, index, field, isObject, options, type; + var keys = Object.keys(schema.paths); + + for (var i = 0; i < keys.length; ++i) { + key = keys[i]; + path = schema.paths[key]; + + if ((path instanceof MongooseTypes.DocumentArray) || path.$isSingleNested) { + collectIndexes(path.schema, key + '.'); + } else { + index = path._index; + + if (index !== false && index !== null && index !== undefined) { + field = {}; + isObject = utils.isObject(index); + options = isObject ? index : {}; + type = typeof index === 'string' ? index : + isObject ? index.type : + false; + + if (type && ~Schema.indexTypes.indexOf(type)) { + field[prefix + key] = type; + } else if (options.text) { + field[prefix + key] = 'text'; + delete options.text; + } else { + field[prefix + key] = 1; + } + + delete options.type; + if (!('background' in options)) { + options.background = true; + } + + indexes.push([field, options]); + } + } + } + + if (prefix) { + fixSubIndexPaths(schema, prefix); + } else { + schema._indexes.forEach(function(index) { + if (!('background' in index[1])) { + index[1].background = true; + } + }); + indexes = indexes.concat(schema._indexes); + } + }; + + collectIndexes(this); + return indexes; + + /*! + * Checks for indexes added to subdocs using Schema.index(). + * These indexes need their paths prefixed properly. + * + * schema._indexes = [ [indexObj, options], [indexObj, options] ..] + */ + + function fixSubIndexPaths(schema, prefix) { + var subindexes = schema._indexes, + len = subindexes.length, + indexObj, + newindex, + klen, + keys, + key, + i = 0, + j; + + for (i = 0; i < len; ++i) { + indexObj = subindexes[i][0]; + keys = Object.keys(indexObj); + klen = keys.length; + newindex = {}; + + // use forward iteration, order matters + for (j = 0; j < klen; ++j) { + key = keys[j]; + newindex[prefix + key] = indexObj[key]; + } + + indexes.push([newindex, subindexes[i][1]]); + } + } +}; + +/** + * Creates a virtual type with the given name. + * + * @param {String} name + * @param {Object} [options] + * @return {VirtualType} + */ + +Schema.prototype.virtual = function(name, options) { + var virtuals = this.virtuals; + var parts = name.split('.'); + virtuals[name] = parts.reduce(function(mem, part, i) { + mem[part] || (mem[part] = (i === parts.length - 1) + ? new VirtualType(options, name) + : {}); + return mem[part]; + }, this.tree); + return virtuals[name]; +}; + +/** + * Returns the virtual type with the given `name`. + * + * @param {String} name + * @return {VirtualType} + */ + +Schema.prototype.virtualpath = function(name) { + return this.virtuals[name]; +}; + +/** + * Removes the given `path` (or [`paths`]). + * + * @param {String|Array} path + * + * @api public + */ +Schema.prototype.remove = function(path) { + if (typeof path === 'string') { + path = [path]; + } + if (Array.isArray(path)) { + path.forEach(function(name) { + if (this.path(name)) { + delete this.paths[name]; + } + }, this); + } +}; + +/*! + * ignore + */ + +Schema.prototype._getSchema = function(path) { + var _this = this; + var pathschema = _this.path(path); + + if (pathschema) { + return pathschema; + } + + function search(parts, schema) { + var p = parts.length + 1, + foundschema, + trypath; + + while (p--) { + trypath = parts.slice(0, p).join('.'); + foundschema = schema.path(trypath); + if (foundschema) { + if (foundschema.caster) { + // array of Mixed? + if (foundschema.caster instanceof MongooseTypes.Mixed) { + return foundschema.caster; + } + + // Now that we found the array, we need to check if there + // are remaining document paths to look up for casting. + // Also we need to handle array.$.path since schema.path + // doesn't work for that. + // If there is no foundschema.schema we are dealing with + // a path like array.$ + if (p !== parts.length && foundschema.schema) { + if (parts[p] === '$') { + // comments.$.comments.$.title + return search(parts.slice(p + 1), foundschema.schema); + } + // this is the last path of the selector + return search(parts.slice(p), foundschema.schema); + } + } + return foundschema; + } + } + } + + // look for arrays + return search(path.split('.'), _this); +}; + +/*! + * ignore + */ + +Schema.prototype._getPathType = function(path) { + var _this = this; + var pathschema = _this.path(path); + + if (pathschema) { + return 'real'; + } + + function search(parts, schema) { + var p = parts.length + 1, + foundschema, + trypath; + + while (p--) { + trypath = parts.slice(0, p).join('.'); + foundschema = schema.path(trypath); + if (foundschema) { + if (foundschema.caster) { + // array of Mixed? + if (foundschema.caster instanceof MongooseTypes.Mixed) { + return 'mixed'; + } + + // Now that we found the array, we need to check if there + // are remaining document paths to look up for casting. + // Also we need to handle array.$.path since schema.path + // doesn't work for that. + // If there is no foundschema.schema we are dealing with + // a path like array.$ + if (p !== parts.length && foundschema.schema) { + if (parts[p] === '$') { + if (p === parts.length - 1) { + return 'nested'; + } + // comments.$.comments.$.title + return search(parts.slice(p + 1), foundschema.schema); + } + // this is the last path of the selector + return search(parts.slice(p), foundschema.schema); + } + return foundschema.$isSingleNested ? 'nested' : 'array'; + } + return 'real'; + } else if (p === parts.length && schema.nested[trypath]) { + return 'nested'; + } + } + return 'undefined'; + } + + // look for arrays + return search(path.split('.'), _this); +}; + + +/*! + * Module exports. + */ + +module.exports = exports = Schema; + +// require down here because of reference issues + +/** + * The various built-in Mongoose Schema Types. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var ObjectId = mongoose.Schema.Types.ObjectId; + * + * ####Types: + * + * - [String](#schema-string-js) + * - [Number](#schema-number-js) + * - [Boolean](#schema-boolean-js) | Bool + * - [Array](#schema-array-js) + * - [Buffer](#schema-buffer-js) + * - [Date](#schema-date-js) + * - [ObjectId](#schema-objectid-js) | Oid + * - [Mixed](#schema-mixed-js) + * + * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. + * + * var Mixed = mongoose.Schema.Types.Mixed; + * new mongoose.Schema({ _user: Mixed }) + * + * @api public + */ + +Schema.Types = MongooseTypes = require('./schema/index'); + +/*! + * ignore + */ + +exports.ObjectId = MongooseTypes.ObjectId; diff --git a/5-2/service/node_modules/mongoose/lib/schema/array.js b/5-2/service/node_modules/mongoose/lib/schema/array.js new file mode 100644 index 0000000..7fec9e8 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/array.js @@ -0,0 +1,391 @@ +/*! + * Module dependencies. + */ + +var SchemaType = require('../schematype'), + CastError = SchemaType.CastError, + Types = { + Boolean: require('./boolean'), + Date: require('./date'), + Number: require('./number'), + String: require('./string'), + ObjectId: require('./objectid'), + Buffer: require('./buffer') + }, + MongooseArray = require('../types').Array, + EmbeddedDoc = require('../types').Embedded, + Mixed = require('./mixed'), + cast = require('../cast'), + utils = require('../utils'), + isMongooseObject = utils.isMongooseObject; + +/** + * Array SchemaType constructor + * + * @param {String} key + * @param {SchemaType} cast + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaArray(key, cast, options) { + if (cast) { + var castOptions = {}; + + if (utils.getFunctionName(cast.constructor) === 'Object') { + if (cast.type) { + // support { type: Woot } + castOptions = utils.clone(cast); // do not alter user arguments + delete castOptions.type; + cast = cast.type; + } else { + cast = Mixed; + } + } + + // support { type: 'String' } + var name = typeof cast === 'string' + ? cast + : utils.getFunctionName(cast); + + var caster = name in Types + ? Types[name] + : cast; + + this.casterConstructor = caster; + this.caster = new caster(null, castOptions); + if (!(this.caster instanceof EmbeddedDoc)) { + this.caster.path = key; + } + } + + SchemaType.call(this, key, options, 'Array'); + + var _this = this, + defaultArr, + fn; + + if (this.defaultValue) { + defaultArr = this.defaultValue; + fn = typeof defaultArr === 'function'; + } + + this.default(function() { + var arr = fn ? defaultArr() : defaultArr || []; + return new MongooseArray(arr, _this.path, this); + }); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaArray.schemaName = 'Array'; + +/*! + * Inherits from SchemaType. + */ +SchemaArray.prototype = Object.create(SchemaType.prototype); +SchemaArray.prototype.constructor = SchemaArray; + +/** + * Check required + * + * @param {Array} value + * @api private + */ + +SchemaArray.prototype.checkRequired = function(value) { + return !!(value && value.length); +}; + +/** + * Overrides the getters application for the population special-case + * + * @param {Object} value + * @param {Object} scope + * @api private + */ + +SchemaArray.prototype.applyGetters = function(value, scope) { + if (this.caster.options && this.caster.options.ref) { + // means the object id was populated + return value; + } + + return SchemaType.prototype.applyGetters.call(this, value, scope); +}; + +/** + * Casts values for set(). + * + * @param {Object} value + * @param {Document} doc document that triggers the casting + * @param {Boolean} init whether this is an initialization cast + * @api private + */ + +SchemaArray.prototype.cast = function(value, doc, init) { + if (Array.isArray(value)) { + if (!value.length && doc) { + var indexes = doc.schema.indexedPaths(); + + for (var i = 0, l = indexes.length; i < l; ++i) { + var pathIndex = indexes[i][0][this.path]; + if (pathIndex === '2dsphere' || pathIndex === '2d') { + return; + } + } + } + + if (!(value && value.isMongooseArray)) { + value = new MongooseArray(value, this.path, doc); + } + + if (this.caster) { + try { + for (i = 0, l = value.length; i < l; i++) { + value[i] = this.caster.cast(value[i], doc, init); + } + } catch (e) { + // rethrow + throw new CastError(e.type, value, this.path); + } + } + + return value; + } + // gh-2442: if we're loading this from the db and its not an array, mark + // the whole array as modified. + if (!!doc && !!init) { + doc.markModified(this.path); + } + return this.cast([value], doc, init); +}; + +/** + * Casts values for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaArray.prototype.castForQuery = function($conditional, value) { + var handler, + val; + + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Array.'); + } + + val = handler.call(this, value); + } else { + val = $conditional; + var proto = this.casterConstructor.prototype; + var method = proto.castForQuery || proto.cast; + var caster = this.caster; + + if (Array.isArray(val)) { + val = val.map(function(v) { + if (utils.isObject(v) && v.$elemMatch) { + return v; + } + if (method) { + v = method.call(caster, v); + } + return isMongooseObject(v) ? + v.toObject({virtuals: false}) : + v; + }); + } else if (method) { + val = method.call(caster, val); + } + } + + return val && isMongooseObject(val) ? + val.toObject({virtuals: false}) : + val; +}; + +/*! + * @ignore + * + * $atomic cast helpers + */ + +function castToNumber(val) { + return Types.Number.prototype.cast.call(this, val); +} + +function castArraysOfNumbers(arr, self) { + arr.forEach(function(v, i) { + if (Array.isArray(v)) { + castArraysOfNumbers(v, self); + } else { + arr[i] = castToNumber.call(self, v); + } + }); +} + +function cast$near(val) { + if (Array.isArray(val)) { + castArraysOfNumbers(val, this); + return val; + } + + if (val && val.$geometry) { + return cast$geometry(val, this); + } + + return SchemaArray.prototype.castForQuery.call(this, val); +} + +function cast$geometry(val, self) { + switch (val.$geometry.type) { + case 'Polygon': + case 'LineString': + case 'Point': + castArraysOfNumbers(val.$geometry.coordinates, self); + break; + default: + // ignore unknowns + break; + } + + if (val.$maxDistance) { + val.$maxDistance = castToNumber.call(self, val.$maxDistance); + } + + return val; +} + +function cast$within(val) { + var _this = this; + + if (val.$maxDistance) { + val.$maxDistance = castToNumber.call(_this, val.$maxDistance); + } + + if (val.$box || val.$polygon) { + var type = val.$box ? '$box' : '$polygon'; + val[type].forEach(function(arr) { + if (!Array.isArray(arr)) { + var msg = 'Invalid $within $box argument. ' + + 'Expected an array, received ' + arr; + throw new TypeError(msg); + } + arr.forEach(function(v, i) { + arr[i] = castToNumber.call(this, v); + }); + }); + } else if (val.$center || val.$centerSphere) { + type = val.$center ? '$center' : '$centerSphere'; + val[type].forEach(function(item, i) { + if (Array.isArray(item)) { + item.forEach(function(v, j) { + item[j] = castToNumber.call(this, v); + }); + } else { + val[type][i] = castToNumber.call(this, item); + } + }); + } else if (val.$geometry) { + cast$geometry(val, this); + } + + return val; +} + +function cast$all(val) { + if (!Array.isArray(val)) { + val = [val]; + } + + val = val.map(function(v) { + if (utils.isObject(v)) { + var o = {}; + o[this.path] = v; + return cast(this.casterConstructor.schema, o)[this.path]; + } + return v; + }, this); + + return this.castForQuery(val); +} + +function cast$elemMatch(val) { + var keys = Object.keys(val); + var numKeys = keys.length; + var key; + var value; + for (var i = 0; i < numKeys; ++i) { + key = keys[i]; + value = val[key]; + if (key.indexOf('$') === 0 && value) { + val[key] = this.castForQuery(key, value); + } + } + + return cast(this.casterConstructor.schema, val); +} + +function cast$geoIntersects(val) { + var geo = val.$geometry; + if (!geo) { + return; + } + + cast$geometry(val, this); + return val; +} + +var handle = SchemaArray.prototype.$conditionalHandlers = {}; + +handle.$all = cast$all; +handle.$options = String; +handle.$elemMatch = cast$elemMatch; +handle.$geoIntersects = cast$geoIntersects; +handle.$or = handle.$and = function(val) { + if (!Array.isArray(val)) { + throw new TypeError('conditional $or/$and require array'); + } + + var ret = []; + for (var i = 0; i < val.length; ++i) { + ret.push(cast(this.casterConstructor.schema, val[i])); + } + + return ret; +}; + +handle.$near = +handle.$nearSphere = cast$near; + +handle.$within = +handle.$geoWithin = cast$within; + +handle.$size = +handle.$maxDistance = castToNumber; + +handle.$eq = +handle.$gt = +handle.$gte = +handle.$in = +handle.$lt = +handle.$lte = +handle.$ne = +handle.$nin = +handle.$regex = SchemaArray.prototype.castForQuery; + +/*! + * Module exports. + */ + +module.exports = SchemaArray; diff --git a/5-2/service/node_modules/mongoose/lib/schema/boolean.js b/5-2/service/node_modules/mongoose/lib/schema/boolean.js new file mode 100644 index 0000000..6ca03ec --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/boolean.js @@ -0,0 +1,99 @@ +/*! + * Module dependencies. + */ + +var utils = require('../utils'); + +var SchemaType = require('../schematype'); + +/** + * Boolean SchemaType constructor. + * + * @param {String} path + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaBoolean(path, options) { + SchemaType.call(this, path, options, 'Boolean'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaBoolean.schemaName = 'Boolean'; + +/*! + * Inherits from SchemaType. + */ +SchemaBoolean.prototype = Object.create(SchemaType.prototype); +SchemaBoolean.prototype.constructor = SchemaBoolean; + +/** + * Required validator + * + * @api private + */ + +SchemaBoolean.prototype.checkRequired = function(value) { + return value === true || value === false; +}; + +/** + * Casts to boolean + * + * @param {Object} value + * @api private + */ + +SchemaBoolean.prototype.cast = function(value) { + if (value === null) { + return value; + } + if (value === '0') { + return false; + } + if (value === 'true') { + return true; + } + if (value === 'false') { + return false; + } + return !!value; +}; + +SchemaBoolean.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, {}); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} val + * @api private + */ + +SchemaBoolean.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = SchemaBoolean.$conditionalHandlers[$conditional]; + + if (handler) { + return handler.call(this, val); + } + + return this.cast(val); + } + + return this.cast($conditional); +}; + +/*! + * Module exports. + */ + +module.exports = SchemaBoolean; diff --git a/5-2/service/node_modules/mongoose/lib/schema/buffer.js b/5-2/service/node_modules/mongoose/lib/schema/buffer.js new file mode 100644 index 0000000..16432b4 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/buffer.js @@ -0,0 +1,183 @@ +/*! + * Module dependencies. + */ + +var handleBitwiseOperator = require('./operators/bitwise'); +var utils = require('../utils'); + +var MongooseBuffer = require('../types').Buffer; +var SchemaType = require('../schematype'); + +var Binary = MongooseBuffer.Binary; +var CastError = SchemaType.CastError; +var Document; + +/** + * Buffer SchemaType constructor + * + * @param {String} key + * @param {SchemaType} cast + * @inherits SchemaType + * @api public + */ + +function SchemaBuffer(key, options) { + SchemaType.call(this, key, options, 'Buffer'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaBuffer.schemaName = 'Buffer'; + +/*! + * Inherits from SchemaType. + */ +SchemaBuffer.prototype = Object.create(SchemaType.prototype); +SchemaBuffer.prototype.constructor = SchemaBuffer; + +/** + * Check required + * + * @api private + */ + +SchemaBuffer.prototype.checkRequired = function(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + return !!(value && value.length); +}; + +/** + * Casts contents + * + * @param {Object} value + * @param {Document} doc document that triggers the casting + * @param {Boolean} init + * @api private + */ + +SchemaBuffer.prototype.cast = function(value, doc, init) { + var ret; + if (SchemaType._isRef(this, value, doc, init)) { + // wait! we may need to cast this to a document + + if (value === null || value === undefined) { + return value; + } + + // lazy load + Document || (Document = require('./../document')); + + if (value instanceof Document) { + value.$__.wasPopulated = true; + return value; + } + + // setting a populated path + if (Buffer.isBuffer(value)) { + return value; + } else if (!utils.isObject(value)) { + throw new CastError('buffer', value, this.path); + } + + // Handle the case where user directly sets a populated + // path to a plain object; cast to the Model used in + // the population query. + var path = doc.$__fullPath(this.path); + var owner = doc.ownerDocument ? doc.ownerDocument() : doc; + var pop = owner.populated(path, true); + ret = new pop.options.model(value); + ret.$__.wasPopulated = true; + return ret; + } + + // documents + if (value && value._id) { + value = value._id; + } + + if (value && value.isMongooseBuffer) { + return value; + } + + if (Buffer.isBuffer(value)) { + if (!value || !value.isMongooseBuffer) { + value = new MongooseBuffer(value, [this.path, doc]); + } + + return value; + } else if (value instanceof Binary) { + ret = new MongooseBuffer(value.value(true), [this.path, doc]); + if (typeof value.sub_type !== 'number') { + throw new CastError('buffer', value, this.path); + } + ret._subtype = value.sub_type; + return ret; + } + + if (value === null) { + return value; + } + + var type = typeof value; + if (type === 'string' || type === 'number' || Array.isArray(value)) { + if (type === 'number') { + value = [value]; + } + ret = new MongooseBuffer(value, [this.path, doc]); + return ret; + } + + throw new CastError('buffer', value, this.path); +}; + +/*! + * ignore + */ +function handleSingle(val) { + return this.castForQuery(val); +} + +SchemaBuffer.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $bitsAllClear: handleBitwiseOperator, + $bitsAnyClear: handleBitwiseOperator, + $bitsAllSet: handleBitwiseOperator, + $bitsAnySet: handleBitwiseOperator, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaBuffer.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Buffer.'); + } + return handler.call(this, val); + } + val = $conditional; + return this.cast(val).toObject(); +}; + +/*! + * Module exports. + */ + +module.exports = SchemaBuffer; diff --git a/5-2/service/node_modules/mongoose/lib/schema/date.js b/5-2/service/node_modules/mongoose/lib/schema/date.js new file mode 100644 index 0000000..6794056 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/date.js @@ -0,0 +1,284 @@ +/*! + * Module requirements. + */ + +var errorMessages = require('../error').messages; +var utils = require('../utils'); + +var SchemaType = require('../schematype'); + +var CastError = SchemaType.CastError; + +/** + * Date SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaDate(key, options) { + SchemaType.call(this, key, options, 'Date'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaDate.schemaName = 'Date'; + +/*! + * Inherits from SchemaType. + */ +SchemaDate.prototype = Object.create(SchemaType.prototype); +SchemaDate.prototype.constructor = SchemaDate; + +/** + * Declares a TTL index (rounded to the nearest second) for _Date_ types only. + * + * This sets the `expireAfterSeconds` index option available in MongoDB >= 2.1.2. + * This index type is only compatible with Date types. + * + * ####Example: + * + * // expire in 24 hours + * new Schema({ createdAt: { type: Date, expires: 60*60*24 }}); + * + * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: + * + * ####Example: + * + * // expire in 24 hours + * new Schema({ createdAt: { type: Date, expires: '24h' }}); + * + * // expire in 1.5 hours + * new Schema({ createdAt: { type: Date, expires: '1.5h' }}); + * + * // expire in 7 days + * var schema = new Schema({ createdAt: Date }); + * schema.path('createdAt').expires('7d'); + * + * @param {Number|String} when + * @added 3.0.0 + * @return {SchemaType} this + * @api public + */ + +SchemaDate.prototype.expires = function(when) { + if (!this._index || this._index.constructor.name !== 'Object') { + this._index = {}; + } + + this._index.expires = when; + utils.expires(this._index); + return this; +}; + +/** + * Required validator for date + * + * @api private + */ + +SchemaDate.prototype.checkRequired = function(value) { + return value instanceof Date; +}; + +/** + * Sets a minimum date validator. + * + * ####Example: + * + * var s = new Schema({ d: { type: Date, min: Date('1970-01-01') }) + * var M = db.model('M', s) + * var m = new M({ d: Date('1969-12-31') }) + * m.save(function (err) { + * console.error(err) // validator error + * m.d = Date('2014-12-08'); + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MIN} token which will be replaced with the invalid value + * var min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; + * var schema = new Schema({ d: { type: Date, min: min }) + * var M = mongoose.model('M', schema); + * var s= new M({ d: Date('1969-12-31') }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01). + * }) + * + * @param {Date} value minimum date + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaDate.prototype.min = function(value, message) { + if (this.minValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minValidator; + }, this); + } + + if (value) { + var msg = message || errorMessages.Date.min; + msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString())); + var _this = this; + this.validators.push({ + validator: this.minValidator = function(val) { + var min = (value === Date.now ? value() : _this.cast(value)); + return val === null || val.valueOf() >= min.valueOf(); + }, + message: msg, + type: 'min', + min: value + }); + } + + return this; +}; + +/** + * Sets a maximum date validator. + * + * ####Example: + * + * var s = new Schema({ d: { type: Date, max: Date('2014-01-01') }) + * var M = db.model('M', s) + * var m = new M({ d: Date('2014-12-08') }) + * m.save(function (err) { + * console.error(err) // validator error + * m.d = Date('2013-12-31'); + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAX} token which will be replaced with the invalid value + * var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; + * var schema = new Schema({ d: { type: Date, max: max }) + * var M = mongoose.model('M', schema); + * var s= new M({ d: Date('2014-12-08') }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01). + * }) + * + * @param {Date} maximum date + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaDate.prototype.max = function(value, message) { + if (this.maxValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxValidator; + }, this); + } + + if (value) { + var msg = message || errorMessages.Date.max; + msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString())); + var _this = this; + this.validators.push({ + validator: this.maxValidator = function(val) { + var max = (value === Date.now ? value() : _this.cast(value)); + return val === null || val.valueOf() <= max.valueOf(); + }, + message: msg, + type: 'max', + max: value + }); + } + + return this; +}; + +/** + * Casts to date + * + * @param {Object} value to cast + * @api private + */ + +SchemaDate.prototype.cast = function(value) { + // If null or undefined + if (value === null || value === void 0 || value === '') { + return null; + } + + if (value instanceof Date) { + return value; + } + + var date; + + if (value instanceof Number || typeof value === 'number' + || String(value) == Number(value)) { + // support for timestamps + date = new Date(Number(value)); + } else if (value.valueOf) { + // support for moment.js + date = new Date(value.valueOf()); + } + + if (!isNaN(date.valueOf())) { + return date; + } + + throw new CastError('date', value, this.path); +}; + +/*! + * Date Query casting. + * + * @api private + */ + +function handleSingle(val) { + return this.cast(val); +} + +SchemaDate.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); + + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaDate.prototype.castForQuery = function($conditional, val) { + var handler; + + if (arguments.length !== 2) { + return this.cast($conditional); + } + + handler = this.$conditionalHandlers[$conditional]; + + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Date.'); + } + + return handler.call(this, val); +}; + +/*! + * Module exports. + */ + +module.exports = SchemaDate; diff --git a/5-2/service/node_modules/mongoose/lib/schema/documentarray.js b/5-2/service/node_modules/mongoose/lib/schema/documentarray.js new file mode 100644 index 0000000..e41f674 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/documentarray.js @@ -0,0 +1,290 @@ +/* eslint no-empty: 1 */ + +/*! + * Module dependencies. + */ + +var ArrayType = require('./array'); +var CastError = require('../error/cast'); +var MongooseDocumentArray = require('../types/documentarray'); +var SchemaType = require('../schematype'); +var Subdocument = require('../types/embedded'); + +/** + * SubdocsArray SchemaType constructor + * + * @param {String} key + * @param {Schema} schema + * @param {Object} options + * @inherits SchemaArray + * @api public + */ + +function DocumentArray(key, schema, options) { + // compile an embedded document for this schema + function EmbeddedDocument() { + Subdocument.apply(this, arguments); + } + + EmbeddedDocument.prototype = Object.create(Subdocument.prototype); + EmbeddedDocument.prototype.$__setSchema(schema); + EmbeddedDocument.schema = schema; + + // apply methods + for (var i in schema.methods) { + EmbeddedDocument.prototype[i] = schema.methods[i]; + } + + // apply statics + for (i in schema.statics) { + EmbeddedDocument[i] = schema.statics[i]; + } + + EmbeddedDocument.options = options; + + ArrayType.call(this, key, EmbeddedDocument, options); + + this.schema = schema; + var path = this.path; + var fn = this.defaultValue; + + this.default(function() { + var arr = fn.call(this); + if (!Array.isArray(arr)) { + arr = [arr]; + } + return new MongooseDocumentArray(arr, path, this); + }); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +DocumentArray.schemaName = 'DocumentArray'; + +/*! + * Inherits from ArrayType. + */ +DocumentArray.prototype = Object.create(ArrayType.prototype); +DocumentArray.prototype.constructor = DocumentArray; + +/** + * Performs local validations first, then validations on each embedded doc + * + * @api private + */ + +DocumentArray.prototype.doValidate = function(array, fn, scope, options) { + SchemaType.prototype.doValidate.call(this, array, function(err) { + if (err) { + return fn(err); + } + + var count = array && array.length; + var error; + + if (!count) { + return fn(); + } + if (options && options.updateValidator) { + return fn(); + } + + // handle sparse arrays, do not use array.forEach which does not + // iterate over sparse elements yet reports array.length including + // them :( + + function callback(err) { + if (err) { + error = err; + } + --count || fn(error); + } + + for (var i = 0, len = count; i < len; ++i) { + // sidestep sparse entries + var doc = array[i]; + if (!doc) { + --count || fn(error); + continue; + } + + // HACK: use $__original_validate to avoid promises so bluebird doesn't + // complain + if (doc.$__original_validate) { + doc.$__original_validate({__noPromise: true}, callback); + } else { + doc.validate({__noPromise: true}, callback); + } + } + }, scope); +}; + +/** + * Performs local validations first, then validations on each embedded doc. + * + * ####Note: + * + * This method ignores the asynchronous validators. + * + * @return {MongooseError|undefined} + * @api private + */ + +DocumentArray.prototype.doValidateSync = function(array, scope) { + var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); + if (schemaTypeError) { + return schemaTypeError; + } + + var count = array && array.length, + resultError = null; + + if (!count) { + return; + } + + // handle sparse arrays, do not use array.forEach which does not + // iterate over sparse elements yet reports array.length including + // them :( + + for (var i = 0, len = count; i < len; ++i) { + // only first error + if (resultError) { + break; + } + // sidestep sparse entries + var doc = array[i]; + if (!doc) { + continue; + } + + var subdocValidateError = doc.validateSync(); + + if (subdocValidateError) { + resultError = subdocValidateError; + } + } + + return resultError; +}; + +/** + * Casts contents + * + * @param {Object} value + * @param {Document} document that triggers the casting + * @api private + */ + +DocumentArray.prototype.cast = function(value, doc, init, prev, options) { + var selected, + subdoc, + i; + + if (!Array.isArray(value)) { + // gh-2442 mark whole array as modified if we're initializing a doc from + // the db and the path isn't an array in the document + if (!!doc && init) { + doc.markModified(this.path); + } + return this.cast([value], doc, init, prev); + } + + if (!(value && value.isMongooseDocumentArray) && + (!options || !options.skipDocumentArrayCast)) { + value = new MongooseDocumentArray(value, this.path, doc); + if (prev && prev._handlers) { + for (var key in prev._handlers) { + doc.removeListener(key, prev._handlers[key]); + } + } + } + + i = value.length; + + while (i--) { + if (!value[i]) { + continue; + } + // Check if the document has a different schema (re gh-3701) + if ((value[i] instanceof Subdocument) && + value[i].schema !== this.casterConstructor.schema) { + value[i] = value[i].toObject({virtuals: false}); + } + if (!(value[i] instanceof Subdocument) && value[i]) { + if (init) { + selected || (selected = scopePaths(this, doc.$__.selected, init)); + subdoc = new this.casterConstructor(null, value, true, selected, i); + value[i] = subdoc.init(value[i]); + } else { + try { + subdoc = prev.id(value[i]._id); + } catch (e) { + } + + if (prev && subdoc) { + // handle resetting doc with existing id but differing data + // doc.array = [{ doc: 'val' }] + subdoc.set(value[i]); + // if set() is hooked it will have no return value + // see gh-746 + value[i] = subdoc; + } else { + try { + subdoc = new this.casterConstructor(value[i], value, undefined, + undefined, i); + // if set() is hooked it will have no return value + // see gh-746 + value[i] = subdoc; + } catch (error) { + throw new CastError('embedded', value[i], value._path); + } + } + } + } + } + + return value; +}; + +/*! + * Scopes paths selected in a query to this array. + * Necessary for proper default application of subdocument values. + * + * @param {DocumentArray} array - the array to scope `fields` paths + * @param {Object|undefined} fields - the root fields selected in the query + * @param {Boolean|undefined} init - if we are being created part of a query result + */ + +function scopePaths(array, fields, init) { + if (!(init && fields)) { + return undefined; + } + + var path = array.path + '.', + keys = Object.keys(fields), + i = keys.length, + selected = {}, + hasKeys, + key; + + while (i--) { + key = keys[i]; + if (key.indexOf(path) === 0) { + hasKeys || (hasKeys = true); + selected[key.substring(path.length)] = fields[key]; + } + } + + return hasKeys && selected || undefined; +} + +/*! + * Module exports. + */ + +module.exports = DocumentArray; diff --git a/5-2/service/node_modules/mongoose/lib/schema/embedded.js b/5-2/service/node_modules/mongoose/lib/schema/embedded.js new file mode 100644 index 0000000..f0444f5 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/embedded.js @@ -0,0 +1,135 @@ +var SchemaType = require('../schematype'); +var Subdocument = require('../types/subdocument'); + +module.exports = Embedded; + +/** + * Sub-schema schematype constructor + * + * @param {Schema} schema + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function Embedded(schema, path, options) { + var _embedded = function(value, path, parent) { + var _this = this; + Subdocument.apply(this, arguments); + this.$parent = parent; + if (parent) { + parent.on('save', function() { + _this.emit('save', _this); + }); + } + }; + _embedded.prototype = Object.create(Subdocument.prototype); + _embedded.prototype.$__setSchema(schema); + _embedded.schema = schema; + _embedded.$isSingleNested = true; + _embedded.prototype.$basePath = path; + + // apply methods + for (var i in schema.methods) { + _embedded.prototype[i] = schema.methods[i]; + } + + // apply statics + for (i in schema.statics) { + _embedded[i] = schema.statics[i]; + } + + this.caster = _embedded; + this.schema = schema; + this.$isSingleNested = true; + SchemaType.call(this, path, options, 'Embedded'); +} + +Embedded.prototype = Object.create(SchemaType.prototype); + +/** + * Casts contents + * + * @param {Object} value + * @api private + */ + +Embedded.prototype.cast = function(val, doc, init) { + if (val && val.$isSingleNested) { + return val; + } + var subdoc = new this.caster(undefined, undefined, doc); + if (init) { + subdoc.init(val); + } else { + subdoc.set(val, undefined, true); + } + return subdoc; +}; + +/** + * Casts contents for query + * + * @param {string} [$conditional] optional query operator (like `$eq` or `$in`) + * @param {any} value + * @api private + */ + +Embedded.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional); + } + return handler.call(this, val); + } + val = $conditional; + return new this.caster(val).toObject({virtuals: false}); +}; + +/** + * Async validation on this single nested doc. + * + * @api private + */ + +Embedded.prototype.doValidate = function(value, fn) { + SchemaType.prototype.doValidate.call(this, value, function(error) { + if (error) { + return fn(error); + } + if (!value) { + return fn(null); + } + value.validate(fn, {__noPromise: true}); + }); +}; + +/** + * Synchronously validate this single nested doc + * + * @api private + */ + +Embedded.prototype.doValidateSync = function(value) { + var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value); + if (schemaTypeError) { + return schemaTypeError; + } + if (!value) { + return; + } + return value.validateSync(); +}; + +/** + * Required validator for single nested docs + * + * @api private + */ + +Embedded.prototype.checkRequired = function(value) { + return !!value && value.$isSingleNested; +}; diff --git a/5-2/service/node_modules/mongoose/lib/schema/index.js b/5-2/service/node_modules/mongoose/lib/schema/index.js new file mode 100644 index 0000000..f2935c1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/index.js @@ -0,0 +1,30 @@ + +/*! + * Module exports. + */ + +exports.String = require('./string'); + +exports.Number = require('./number'); + +exports.Boolean = require('./boolean'); + +exports.DocumentArray = require('./documentarray'); + +exports.Embedded = require('./embedded'); + +exports.Array = require('./array'); + +exports.Buffer = require('./buffer'); + +exports.Date = require('./date'); + +exports.ObjectId = require('./objectid'); + +exports.Mixed = require('./mixed'); + +// alias + +exports.Oid = exports.ObjectId; +exports.Object = exports.Mixed; +exports.Bool = exports.Boolean; diff --git a/5-2/service/node_modules/mongoose/lib/schema/mixed.js b/5-2/service/node_modules/mongoose/lib/schema/mixed.js new file mode 100644 index 0000000..c1b4cab --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/mixed.js @@ -0,0 +1,90 @@ +/*! + * Module dependencies. + */ + +var SchemaType = require('../schematype'); +var utils = require('../utils'); + +/** + * Mixed SchemaType constructor. + * + * @param {String} path + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function Mixed(path, options) { + if (options && options.default) { + var def = options.default; + if (Array.isArray(def) && def.length === 0) { + // make sure empty array defaults are handled + options.default = Array; + } else if (!options.shared && utils.isObject(def) && Object.keys(def).length === 0) { + // prevent odd "shared" objects between documents + options.default = function() { + return {}; + }; + } + } + + SchemaType.call(this, path, options, 'Mixed'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +Mixed.schemaName = 'Mixed'; + +/*! + * Inherits from SchemaType. + */ +Mixed.prototype = Object.create(SchemaType.prototype); +Mixed.prototype.constructor = Mixed; + +/** + * Required validator + * + * @api private + */ + +Mixed.prototype.checkRequired = function(val) { + return (val !== undefined) && (val !== null); +}; + +/** + * Casts `val` for Mixed. + * + * _this is a no-op_ + * + * @param {Object} value to cast + * @api private + */ + +Mixed.prototype.cast = function(val) { + return val; +}; + +/** + * Casts contents for queries. + * + * @param {String} $cond + * @param {any} [val] + * @api private + */ + +Mixed.prototype.castForQuery = function($cond, val) { + if (arguments.length === 2) { + return val; + } + return $cond; +}; + +/*! + * Module exports. + */ + +module.exports = Mixed; diff --git a/5-2/service/node_modules/mongoose/lib/schema/number.js b/5-2/service/node_modules/mongoose/lib/schema/number.js new file mode 100644 index 0000000..ff8f500 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/number.js @@ -0,0 +1,287 @@ +/*! + * Module requirements. + */ + +var SchemaType = require('../schematype'); +var CastError = SchemaType.CastError; +var handleBitwiseOperator = require('./operators/bitwise'); +var errorMessages = require('../error').messages; +var utils = require('../utils'); +var Document; + +/** + * Number SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaNumber(key, options) { + SchemaType.call(this, key, options, 'Number'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaNumber.schemaName = 'Number'; + +/*! + * Inherits from SchemaType. + */ +SchemaNumber.prototype = Object.create(SchemaType.prototype); +SchemaNumber.prototype.constructor = SchemaNumber; + +/** + * Required validator for number + * + * @api private + */ + +SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + return typeof value === 'number' || value instanceof Number; +}; + +/** + * Sets a minimum number validator. + * + * ####Example: + * + * var s = new Schema({ n: { type: Number, min: 10 }) + * var M = db.model('M', s) + * var m = new M({ n: 9 }) + * m.save(function (err) { + * console.error(err) // validator error + * m.n = 10; + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MIN} token which will be replaced with the invalid value + * var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; + * var schema = new Schema({ n: { type: Number, min: min }) + * var M = mongoose.model('Measurement', schema); + * var s= new M({ n: 4 }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). + * }) + * + * @param {Number} value minimum number + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaNumber.prototype.min = function(value, message) { + if (this.minValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minValidator; + }, this); + } + + if (value !== null && value !== undefined) { + var msg = message || errorMessages.Number.min; + msg = msg.replace(/{MIN}/, value); + this.validators.push({ + validator: this.minValidator = function(v) { + return v == null || v >= value; + }, + message: msg, + type: 'min', + min: value + }); + } + + return this; +}; + +/** + * Sets a maximum number validator. + * + * ####Example: + * + * var s = new Schema({ n: { type: Number, max: 10 }) + * var M = db.model('M', s) + * var m = new M({ n: 11 }) + * m.save(function (err) { + * console.error(err) // validator error + * m.n = 10; + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAX} token which will be replaced with the invalid value + * var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; + * var schema = new Schema({ n: { type: Number, max: max }) + * var M = mongoose.model('Measurement', schema); + * var s= new M({ n: 4 }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). + * }) + * + * @param {Number} maximum number + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaNumber.prototype.max = function(value, message) { + if (this.maxValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxValidator; + }, this); + } + + if (value !== null && value !== undefined) { + var msg = message || errorMessages.Number.max; + msg = msg.replace(/{MAX}/, value); + this.validators.push({ + validator: this.maxValidator = function(v) { + return v == null || v <= value; + }, + message: msg, + type: 'max', + max: value + }); + } + + return this; +}; + +/** + * Casts to number + * + * @param {Object} value value to cast + * @param {Document} doc document that triggers the casting + * @param {Boolean} init + * @api private + */ + +SchemaNumber.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + // wait! we may need to cast this to a document + + if (value === null || value === undefined) { + return value; + } + + // lazy load + Document || (Document = require('./../document')); + + if (value instanceof Document) { + value.$__.wasPopulated = true; + return value; + } + + // setting a populated path + if (typeof value === 'number') { + return value; + } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { + throw new CastError('number', value, this.path); + } + + // Handle the case where user directly sets a populated + // path to a plain object; cast to the Model used in + // the population query. + var path = doc.$__fullPath(this.path); + var owner = doc.ownerDocument ? doc.ownerDocument() : doc; + var pop = owner.populated(path, true); + var ret = new pop.options.model(value); + ret.$__.wasPopulated = true; + return ret; + } + + var val = value && value._id + ? value._id // documents + : value; + + if (!isNaN(val)) { + if (val === null) { + return val; + } + if (val === '') { + return null; + } + if (typeof val === 'string' || typeof val === 'boolean') { + val = Number(val); + } + if (val instanceof Number) { + return val; + } + if (typeof val === 'number') { + return val; + } + if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) { + return new Number(val); + } + } + + throw new CastError('number', value, this.path); +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.cast(val); +} + +function handleArray(val) { + var _this = this; + if (!Array.isArray(val)) { + return [this.cast(val)]; + } + return val.map(function(m) { + return _this.cast(m); + }); +} + +SchemaNumber.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $bitsAllClear: handleBitwiseOperator, + $bitsAnyClear: handleBitwiseOperator, + $bitsAllSet: handleBitwiseOperator, + $bitsAnySet: handleBitwiseOperator, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle, + $mod: handleArray + }); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaNumber.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Number.'); + } + return handler.call(this, val); + } + val = this.cast($conditional); + return val; +}; + +/*! + * Module exports. + */ + +module.exports = SchemaNumber; diff --git a/5-2/service/node_modules/mongoose/lib/schema/objectid.js b/5-2/service/node_modules/mongoose/lib/schema/objectid.js new file mode 100644 index 0000000..51bcb49 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/objectid.js @@ -0,0 +1,196 @@ +/* eslint no-empty: 1 */ + +/*! + * Module dependencies. + */ + +var SchemaType = require('../schematype'), + CastError = SchemaType.CastError, + oid = require('../types/objectid'), + utils = require('../utils'), + Document; + +/** + * ObjectId SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function ObjectId(key, options) { + SchemaType.call(this, key, options, 'ObjectID'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +ObjectId.schemaName = 'ObjectId'; + +/*! + * Inherits from SchemaType. + */ +ObjectId.prototype = Object.create(SchemaType.prototype); +ObjectId.prototype.constructor = ObjectId; + +/** + * Adds an auto-generated ObjectId default if turnOn is true. + * @param {Boolean} turnOn auto generated ObjectId defaults + * @api public + * @return {SchemaType} this + */ + +ObjectId.prototype.auto = function(turnOn) { + if (turnOn) { + this.default(defaultId); + this.set(resetId); + } + + return this; +}; + +/** + * Check required + * + * @api private + */ + +ObjectId.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + return value instanceof oid; +}; + +/** + * Casts to ObjectId + * + * @param {Object} value + * @param {Object} doc + * @param {Boolean} init whether this is an initialization cast + * @api private + */ + +ObjectId.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + // wait! we may need to cast this to a document + + if (value === null || value === undefined) { + return value; + } + + // lazy load + Document || (Document = require('./../document')); + + if (value instanceof Document) { + value.$__.wasPopulated = true; + return value; + } + + // setting a populated path + if (value instanceof oid) { + return value; + } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { + throw new CastError('ObjectId', value, this.path); + } + + // Handle the case where user directly sets a populated + // path to a plain object; cast to the Model used in + // the population query. + var path = doc.$__fullPath(this.path); + var owner = doc.ownerDocument ? doc.ownerDocument() : doc; + var pop = owner.populated(path, true); + var ret = new pop.options.model(value); + ret.$__.wasPopulated = true; + return ret; + } + + if (value === null || value === undefined) { + return value; + } + + if (value instanceof oid) { + return value; + } + + if (value._id) { + if (value._id instanceof oid) { + return value._id; + } + if (value._id.toString instanceof Function) { + try { + return oid.createFromHexString(value._id.toString()); + } catch (e) { + } + } + } + + if (value.toString instanceof Function) { + try { + return oid.createFromHexString(value.toString()); + } catch (err) { + throw new CastError('ObjectId', value, this.path); + } + } + + throw new CastError('ObjectId', value, this.path); +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.cast(val); +} + +ObjectId.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [val] + * @api private + */ + +ObjectId.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with ObjectId.'); + } + return handler.call(this, val); + } + return this.cast($conditional); +}; + +/*! + * ignore + */ + +function defaultId() { + return new oid(); +} + +function resetId(v) { + this.$__._id = null; + return v; +} + +/*! + * Module exports. + */ + +module.exports = ObjectId; diff --git a/5-2/service/node_modules/mongoose/lib/schema/operators/bitwise.js b/5-2/service/node_modules/mongoose/lib/schema/operators/bitwise.js new file mode 100644 index 0000000..c1fdd34 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/operators/bitwise.js @@ -0,0 +1,36 @@ +/*! + * Module requirements. + */ + +var CastError = require('../../error/cast'); + +/*! + * ignore + */ + +function handleBitwiseOperator(val) { + var _this = this; + if (Array.isArray(val)) { + return val.map(function(v) { + return _castNumber(_this.path, v); + }); + } else if (Buffer.isBuffer(val)) { + return val; + } + // Assume trying to cast to number + return _castNumber(_this.path, val); +} + +/*! + * ignore + */ + +function _castNumber(path, num) { + var v = Number(num); + if (isNaN(v)) { + throw new CastError('number', num, path); + } + return v; +} + +module.exports = handleBitwiseOperator; diff --git a/5-2/service/node_modules/mongoose/lib/schema/string.js b/5-2/service/node_modules/mongoose/lib/schema/string.js new file mode 100644 index 0000000..6213471 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schema/string.js @@ -0,0 +1,504 @@ +/*! + * Module dependencies. + */ + +var SchemaType = require('../schematype'); +var CastError = SchemaType.CastError; +var errorMessages = require('../error').messages; +var utils = require('../utils'); +var Document; + +/** + * String SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaString(key, options) { + this.enumValues = []; + this.regExp = null; + SchemaType.call(this, key, options, 'String'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaString.schemaName = 'String'; + +/*! + * Inherits from SchemaType. + */ +SchemaString.prototype = Object.create(SchemaType.prototype); +SchemaString.prototype.constructor = SchemaString; + +/** + * Adds an enum validator + * + * ####Example: + * + * var states = 'opening open closing closed'.split(' ') + * var s = new Schema({ state: { type: String, enum: states }}) + * var M = db.model('M', s) + * var m = new M({ state: 'invalid' }) + * m.save(function (err) { + * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. + * m.state = 'open' + * m.save(callback) // success + * }) + * + * // or with custom error messages + * var enu = { + * values: 'opening open closing closed'.split(' '), + * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' + * } + * var s = new Schema({ state: { type: String, enum: enu }) + * var M = db.model('M', s) + * var m = new M({ state: 'invalid' }) + * m.save(function (err) { + * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` + * m.state = 'open' + * m.save(callback) // success + * }) + * + * @param {String|Object} [args...] enumeration values + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.enum = function() { + if (this.enumValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.enumValidator; + }, this); + this.enumValidator = false; + } + + if (arguments[0] === void 0 || arguments[0] === false) { + return this; + } + + var values; + var errorMessage; + + if (utils.isObject(arguments[0])) { + values = arguments[0].values; + errorMessage = arguments[0].message; + } else { + values = arguments; + errorMessage = errorMessages.String.enum; + } + + for (var i = 0; i < values.length; i++) { + if (undefined !== values[i]) { + this.enumValues.push(this.cast(values[i])); + } + } + + var vals = this.enumValues; + this.enumValidator = function(v) { + return undefined === v || ~vals.indexOf(v); + }; + this.validators.push({ + validator: this.enumValidator, + message: errorMessage, + type: 'enum', + enumValues: vals + }); + + return this; +}; + +/** + * Adds a lowercase setter. + * + * ####Example: + * + * var s = new Schema({ email: { type: String, lowercase: true }}) + * var M = db.model('M', s); + * var m = new M({ email: 'SomeEmail@example.COM' }); + * console.log(m.email) // someemail@example.com + * + * @api public + * @return {SchemaType} this + */ + +SchemaString.prototype.lowercase = function() { + return this.set(function(v, self) { + if (typeof v !== 'string') { + v = self.cast(v); + } + if (v) { + return v.toLowerCase(); + } + return v; + }); +}; + +/** + * Adds an uppercase setter. + * + * ####Example: + * + * var s = new Schema({ caps: { type: String, uppercase: true }}) + * var M = db.model('M', s); + * var m = new M({ caps: 'an example' }); + * console.log(m.caps) // AN EXAMPLE + * + * @api public + * @return {SchemaType} this + */ + +SchemaString.prototype.uppercase = function() { + return this.set(function(v, self) { + if (typeof v !== 'string') { + v = self.cast(v); + } + if (v) { + return v.toUpperCase(); + } + return v; + }); +}; + +/** + * Adds a trim setter. + * + * The string value will be trimmed when set. + * + * ####Example: + * + * var s = new Schema({ name: { type: String, trim: true }}) + * var M = db.model('M', s) + * var string = ' some name ' + * console.log(string.length) // 11 + * var m = new M({ name: string }) + * console.log(m.name.length) // 9 + * + * @api public + * @return {SchemaType} this + */ + +SchemaString.prototype.trim = function() { + return this.set(function(v, self) { + if (typeof v !== 'string') { + v = self.cast(v); + } + if (v) { + return v.trim(); + } + return v; + }); +}; + +/** + * Sets a minimum length validator. + * + * ####Example: + * + * var schema = new Schema({ postalCode: { type: String, minlength: 5 }) + * var Address = db.model('Address', schema) + * var address = new Address({ postalCode: '9512' }) + * address.save(function (err) { + * console.error(err) // validator error + * address.postalCode = '95125'; + * address.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length + * var minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).']; + * var schema = new Schema({ postalCode: { type: String, minlength: minlength }) + * var Address = mongoose.model('Address', schema); + * var address = new Address({ postalCode: '9512' }); + * address.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5). + * }) + * + * @param {Number} value minimum string length + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.minlength = function(value, message) { + if (this.minlengthValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minlengthValidator; + }, this); + } + + if (value !== null && value !== undefined) { + var msg = message || errorMessages.String.minlength; + msg = msg.replace(/{MINLENGTH}/, value); + this.validators.push({ + validator: this.minlengthValidator = function(v) { + return v === null || v.length >= value; + }, + message: msg, + type: 'minlength', + minlength: value + }); + } + + return this; +}; + +/** + * Sets a maximum length validator. + * + * ####Example: + * + * var schema = new Schema({ postalCode: { type: String, maxlength: 9 }) + * var Address = db.model('Address', schema) + * var address = new Address({ postalCode: '9512512345' }) + * address.save(function (err) { + * console.error(err) // validator error + * address.postalCode = '95125'; + * address.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length + * var maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).']; + * var schema = new Schema({ postalCode: { type: String, maxlength: maxlength }) + * var Address = mongoose.model('Address', schema); + * var address = new Address({ postalCode: '9512512345' }); + * address.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9). + * }) + * + * @param {Number} value maximum string length + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.maxlength = function(value, message) { + if (this.maxlengthValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxlengthValidator; + }, this); + } + + if (value !== null && value !== undefined) { + var msg = message || errorMessages.String.maxlength; + msg = msg.replace(/{MAXLENGTH}/, value); + this.validators.push({ + validator: this.maxlengthValidator = function(v) { + return v === null || v.length <= value; + }, + message: msg, + type: 'maxlength', + maxlength: value + }); + } + + return this; +}; + +/** + * Sets a regexp validator. + * + * Any value that does not pass `regExp`.test(val) will fail validation. + * + * ####Example: + * + * var s = new Schema({ name: { type: String, match: /^a/ }}) + * var M = db.model('M', s) + * var m = new M({ name: 'I am invalid' }) + * m.validate(function (err) { + * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)." + * m.name = 'apples' + * m.validate(function (err) { + * assert.ok(err) // success + * }) + * }) + * + * // using a custom error message + * var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; + * var s = new Schema({ file: { type: String, match: match }}) + * var M = db.model('M', s); + * var m = new M({ file: 'invalid' }); + * m.validate(function (err) { + * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)" + * }) + * + * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also. + * + * var s = new Schema({ name: { type: String, match: /^a/, required: true }}) + * + * @param {RegExp} regExp regular expression to test against + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.match = function match(regExp, message) { + // yes, we allow multiple match validators + + var msg = message || errorMessages.String.match; + + var matchValidator = function(v) { + if (!regExp) { + return false; + } + + var ret = ((v != null && v !== '') + ? regExp.test(v) + : true); + return ret; + }; + + this.validators.push({ + validator: matchValidator, + message: msg, + type: 'regexp', + regexp: regExp + }); + return this; +}; + +/** + * Check required + * + * @param {String|null|undefined} value + * @api private + */ + +SchemaString.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + return (value instanceof String || typeof value === 'string') && value.length; +}; + +/** + * Casts to String + * + * @api private + */ + +SchemaString.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + // wait! we may need to cast this to a document + + if (value === null || value === undefined) { + return value; + } + + // lazy load + Document || (Document = require('./../document')); + + if (value instanceof Document) { + value.$__.wasPopulated = true; + return value; + } + + // setting a populated path + if (typeof value === 'string') { + return value; + } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { + throw new CastError('string', value, this.path); + } + + // Handle the case where user directly sets a populated + // path to a plain object; cast to the Model used in + // the population query. + var path = doc.$__fullPath(this.path); + var owner = doc.ownerDocument ? doc.ownerDocument() : doc; + var pop = owner.populated(path, true); + var ret = new pop.options.model(value); + ret.$__.wasPopulated = true; + return ret; + } + + // If null or undefined + if (value === null || value === undefined) { + return value; + } + + if (typeof value !== 'undefined') { + // handle documents being passed + if (value._id && typeof value._id === 'string') { + return value._id; + } + + // Re: gh-647 and gh-3030, we're ok with casting using `toString()` + // **unless** its the default Object.toString, because "[object Object]" + // doesn't really qualify as useful data + if (value.toString && value.toString !== Object.prototype.toString) { + return value.toString(); + } + } + + throw new CastError('string', value, this.path); +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.castForQuery(val); +} + +function handleArray(val) { + var _this = this; + if (!Array.isArray(val)) { + return [this.castForQuery(val)]; + } + return val.map(function(m) { + return _this.castForQuery(m); + }); +} + +SchemaString.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $all: handleArray, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle, + $options: handleSingle, + $regex: handleSingle + }); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [val] + * @api private + */ + +SchemaString.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with String.'); + } + return handler.call(this, val); + } + val = $conditional; + if (Object.prototype.toString.call(val) === '[object RegExp]') { + return val; + } + return this.cast(val); +}; + +/*! + * Module exports. + */ + +module.exports = SchemaString; diff --git a/5-2/service/node_modules/mongoose/lib/schematype.js b/5-2/service/node_modules/mongoose/lib/schematype.js new file mode 100644 index 0000000..bfab06b --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/schematype.js @@ -0,0 +1,887 @@ +/*! + * Module dependencies. + */ + +var utils = require('./utils'); +var error = require('./error'); +var errorMessages = error.messages; +var CastError = error.CastError; +var ValidatorError = error.ValidatorError; + +/** + * SchemaType constructor + * + * @param {String} path + * @param {Object} [options] + * @param {String} [instance] + * @api public + */ + +function SchemaType(path, options, instance) { + this.path = path; + this.instance = instance; + this.validators = []; + this.setters = []; + this.getters = []; + this.options = options; + this._index = null; + this.selected; + + for (var i in options) { + if (this[i] && typeof this[i] === 'function') { + // { unique: true, index: true } + if (i === 'index' && this._index) { + continue; + } + + var opts = Array.isArray(options[i]) + ? options[i] + : [options[i]]; + + this[i].apply(this, opts); + } + } +} + +/** + * Sets a default value for this SchemaType. + * + * ####Example: + * + * var schema = new Schema({ n: { type: Number, default: 10 }) + * var M = db.model('M', schema) + * var m = new M; + * console.log(m.n) // 10 + * + * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. + * + * ####Example: + * + * // values are cast: + * var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }}) + * var M = db.model('M', schema) + * var m = new M; + * console.log(m.aNumber) // 4.815162342 + * + * // default unique objects for Mixed types: + * var schema = new Schema({ mixed: Schema.Types.Mixed }); + * schema.path('mixed').default(function () { + * return {}; + * }); + * + * // if we don't use a function to return object literals for Mixed defaults, + * // each document will receive a reference to the same object literal creating + * // a "shared" object instance: + * var schema = new Schema({ mixed: Schema.Types.Mixed }); + * schema.path('mixed').default({}); + * var M = db.model('M', schema); + * var m1 = new M; + * m1.mixed.added = 1; + * console.log(m1.mixed); // { added: 1 } + * var m2 = new M; + * console.log(m2.mixed); // { added: 1 } + * + * @param {Function|any} val the default value + * @return {defaultValue} + * @api public + */ + +SchemaType.prototype.default = function(val) { + if (arguments.length === 1) { + this.defaultValue = typeof val === 'function' + ? val + : this.cast(val); + return this; + } else if (arguments.length > 1) { + this.defaultValue = utils.args(arguments); + } + return this.defaultValue; +}; + +/** + * Declares the index options for this schematype. + * + * ####Example: + * + * var s = new Schema({ name: { type: String, index: true }) + * var s = new Schema({ loc: { type: [Number], index: 'hashed' }) + * var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) + * var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) + * var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) + * Schema.path('my.path').index(true); + * Schema.path('my.date').index({ expires: 60 }); + * Schema.path('my.path').index({ unique: true, sparse: true }); + * + * ####NOTE: + * + * _Indexes are created in the background by default. Specify `background: false` to override._ + * + * [Direction doesn't matter for single key indexes](http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes) + * + * @param {Object|Boolean|String} options + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.index = function(options) { + this._index = options; + utils.expires(this._index); + return this; +}; + +/** + * Declares an unique index. + * + * ####Example: + * + * var s = new Schema({ name: { type: String, unique: true }}); + * Schema.path('name').index({ unique: true }); + * + * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ + * + * @param {Boolean} bool + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.unique = function(bool) { + if (this._index === null || this._index === undefined || + typeof this._index === 'boolean') { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = {type: this._index}; + } + + this._index.unique = bool; + return this; +}; + +/** + * Declares a full text index. + * + * ###Example: + * + * var s = new Schema({name : {type: String, text : true }) + * Schema.path('name').index({text : true}); + * @param bool + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.text = function(bool) { + if (this._index === null || this._index === undefined || + typeof this._index === 'boolean') { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = {type: this._index}; + } + + this._index.text = bool; + return this; +}; + +/** + * Declares a sparse index. + * + * ####Example: + * + * var s = new Schema({ name: { type: String, sparse: true }) + * Schema.path('name').index({ sparse: true }); + * + * @param {Boolean} bool + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.sparse = function(bool) { + if (this._index === null || this._index === undefined || + typeof this._index === 'boolean') { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = {type: this._index}; + } + + this._index.sparse = bool; + return this; +}; + +/** + * Adds a setter to this schematype. + * + * ####Example: + * + * function capitalize (val) { + * if (typeof val !== 'string') val = ''; + * return val.charAt(0).toUpperCase() + val.substring(1); + * } + * + * // defining within the schema + * var s = new Schema({ name: { type: String, set: capitalize }}) + * + * // or by retreiving its SchemaType + * var s = new Schema({ name: String }) + * s.path('name').set(capitalize) + * + * Setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key. + * + * Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. + * + * You can set up email lower case normalization easily via a Mongoose setter. + * + * function toLower (v) { + * return v.toLowerCase(); + * } + * + * var UserSchema = new Schema({ + * email: { type: String, set: toLower } + * }) + * + * var User = db.model('User', UserSchema) + * + * var user = new User({email: 'AVENUE@Q.COM'}) + * console.log(user.email); // 'avenue@q.com' + * + * // or + * var user = new User + * user.email = 'Avenue@Q.com' + * console.log(user.email) // 'avenue@q.com' + * + * As you can see above, setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key. + * + * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ + * + * new Schema({ email: { type: String, lowercase: true }}) + * + * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. + * + * function inspector (val, schematype) { + * if (schematype.options.required) { + * return schematype.path + ' is required'; + * } else { + * return val; + * } + * } + * + * var VirusSchema = new Schema({ + * name: { type: String, required: true, set: inspector }, + * taxonomy: { type: String, set: inspector } + * }) + * + * var Virus = db.model('Virus', VirusSchema); + * var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); + * + * console.log(v.name); // name is required + * console.log(v.taxonomy); // Parvovirinae + * + * @param {Function} fn + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.set = function(fn) { + if (typeof fn !== 'function') { + throw new TypeError('A setter must be a function.'); + } + this.setters.push(fn); + return this; +}; + +/** + * Adds a getter to this schematype. + * + * ####Example: + * + * function dob (val) { + * if (!val) return val; + * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); + * } + * + * // defining within the schema + * var s = new Schema({ born: { type: Date, get: dob }) + * + * // or by retreiving its SchemaType + * var s = new Schema({ born: Date }) + * s.path('born').get(dob) + * + * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. + * + * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: + * + * function obfuscate (cc) { + * return '****-****-****-' + cc.slice(cc.length-4, cc.length); + * } + * + * var AccountSchema = new Schema({ + * creditCardNumber: { type: String, get: obfuscate } + * }); + * + * var Account = db.model('Account', AccountSchema); + * + * Account.findById(id, function (err, found) { + * console.log(found.creditCardNumber); // '****-****-****-1234' + * }); + * + * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. + * + * function inspector (val, schematype) { + * if (schematype.options.required) { + * return schematype.path + ' is required'; + * } else { + * return schematype.path + ' is not'; + * } + * } + * + * var VirusSchema = new Schema({ + * name: { type: String, required: true, get: inspector }, + * taxonomy: { type: String, get: inspector } + * }) + * + * var Virus = db.model('Virus', VirusSchema); + * + * Virus.findById(id, function (err, virus) { + * console.log(virus.name); // name is required + * console.log(virus.taxonomy); // taxonomy is not + * }) + * + * @param {Function} fn + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.get = function(fn) { + if (typeof fn !== 'function') { + throw new TypeError('A getter must be a function.'); + } + this.getters.push(fn); + return this; +}; + +/** + * Adds validator(s) for this document path. + * + * Validators always receive the value to validate as their first argument and must return `Boolean`. Returning `false` means validation failed. + * + * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. + * + * ####Examples: + * + * // make sure every value is equal to "something" + * function validator (val) { + * return val == 'something'; + * } + * new Schema({ name: { type: String, validate: validator }}); + * + * // with a custom error message + * + * var custom = [validator, 'Uh oh, {PATH} does not equal "something".'] + * new Schema({ name: { type: String, validate: custom }}); + * + * // adding many validators at a time + * + * var many = [ + * { validator: validator, msg: 'uh oh' } + * , { validator: anotherValidator, msg: 'failed' } + * ] + * new Schema({ name: { type: String, validate: many }}); + * + * // or utilizing SchemaType methods directly: + * + * var schema = new Schema({ name: 'string' }); + * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); + * + * ####Error message templates: + * + * From the examples above, you may have noticed that error messages support basic templating. There are a few other template keywords besides `{PATH}` and `{VALUE}` too. To find out more, details are available [here](#error_messages_MongooseError-messages) + * + * ####Asynchronous validation: + * + * Passing a validator function that receives two arguments tells mongoose that the validator is an asynchronous validator. The first argument passed to the validator function is the value being validated. The second argument is a callback function that must called when you finish validating the value and passed either `true` or `false` to communicate either success or failure respectively. + * + * schema.path('name').validate(function (value, respond) { + * doStuff(value, function () { + * ... + * respond(false); // validation failed + * }) + * }, '{PATH} failed validation.'); + * + * // or with dynamic message + * + * schema.path('name').validate(function (value, respond) { + * doStuff(value, function () { + * ... + * respond(false, 'this message gets to the validation error'); + * }); + * }, 'this message does not matter'); + * + * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. + * + * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). + * + * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. + * + * var conn = mongoose.createConnection(..); + * conn.on('error', handleError); + * + * var Product = conn.model('Product', yourSchema); + * var dvd = new Product(..); + * dvd.save(); // emits error on the `conn` above + * + * If you desire handling these errors at the Model level, attach an `error` listener to your Model and the event will instead be emitted there. + * + * // registering an error listener on the Model lets us handle errors more locally + * Product.on('error', handleError); + * + * @param {RegExp|Function|Object} obj validator + * @param {String} [errorMsg] optional error message + * @param {String} [type] optional validator type + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.validate = function(obj, message, type) { + if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') { + var properties; + if (message instanceof Object && !type) { + properties = utils.clone(message); + if (!properties.message) { + properties.message = properties.msg; + } + properties.validator = obj; + properties.type = properties.type || 'user defined'; + } else { + if (!message) { + message = errorMessages.general.default; + } + if (!type) { + type = 'user defined'; + } + properties = {message: message, type: type, validator: obj}; + } + this.validators.push(properties); + return this; + } + + var i, + length, + arg; + + for (i = 0, length = arguments.length; i < length; i++) { + arg = arguments[i]; + if (!(arg && utils.getFunctionName(arg.constructor) === 'Object')) { + var msg = 'Invalid validator. Received (' + typeof arg + ') ' + + arg + + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; + + throw new Error(msg); + } + this.validate(arg.validator, arg); + } + + return this; +}; + +/** + * Adds a required validator to this schematype. The required validator is added + * to the front of the validators array using `unshift()`. + * + * ####Example: + * + * var s = new Schema({ born: { type: Date, required: true }) + * + * // or with custom error message + * + * var s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) + * + * // or through the path API + * + * Schema.path('name').required(true); + * + * // with custom error messaging + * + * Schema.path('name').required(true, 'grrr :( '); + * + * + * @param {Boolean} required enable/disable the validator + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaType.prototype.required = function(required, message) { + if (required === false) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.requiredValidator; + }, this); + + this.isRequired = false; + return this; + } + + var _this = this; + this.isRequired = true; + + this.requiredValidator = function(v) { + // in here, `this` refers to the validating document. + // no validation when this path wasn't selected in the query. + if ('isSelected' in this && !this.isSelected(_this.path) && !this.isModified(_this.path)) { + return true; + } + + return ((typeof required === 'function') && !required.apply(this)) || + _this.checkRequired(v, this); + }; + + if (typeof required === 'string') { + message = required; + required = undefined; + } + + var msg = message || errorMessages.general.required; + this.validators.unshift({ + validator: this.requiredValidator, + message: msg, + type: 'required' + }); + + return this; +}; + +/** + * Gets the default value + * + * @param {Object} scope the scope which callback are executed + * @param {Boolean} init + * @api private + */ + +SchemaType.prototype.getDefault = function(scope, init) { + var ret = typeof this.defaultValue === 'function' + ? this.defaultValue.call(scope) + : this.defaultValue; + + if (ret !== null && ret !== undefined) { + return this.cast(ret, scope, init); + } + return ret; +}; + +/** + * Applies setters + * + * @param {Object} value + * @param {Object} scope + * @param {Boolean} init + * @api private + */ + +SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) { + var v = value, + setters = this.setters, + len = setters.length, + caster = this.caster; + + while (len--) { + v = setters[len].call(scope, v, this); + } + + if (Array.isArray(v) && caster && caster.setters) { + var newVal = []; + for (var i = 0; i < v.length; i++) { + newVal.push(caster.applySetters(v[i], scope, init, priorVal)); + } + v = newVal; + } + + if (v === null || v === undefined) { + return v; + } + + // do not cast until all setters are applied #665 + v = this.cast(v, scope, init, priorVal, options); + + return v; +}; + +/** + * Applies getters to a value + * + * @param {Object} value + * @param {Object} scope + * @api private + */ + +SchemaType.prototype.applyGetters = function(value, scope) { + var v = value, + getters = this.getters, + len = getters.length; + + if (!len) { + return v; + } + + while (len--) { + v = getters[len].call(scope, v, this); + } + + return v; +}; + +/** + * Sets default `select()` behavior for this path. + * + * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. + * + * ####Example: + * + * T = db.model('T', new Schema({ x: { type: String, select: true }})); + * T.find(..); // field x will always be selected .. + * // .. unless overridden; + * T.find().select('-x').exec(callback); + * + * @param {Boolean} val + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.select = function select(val) { + this.selected = !!val; + return this; +}; + +/** + * Performs a validation of `value` using the validators declared for this SchemaType. + * + * @param {any} value + * @param {Function} callback + * @param {Object} scope + * @api private + */ + +SchemaType.prototype.doValidate = function(value, fn, scope) { + var err = false, + path = this.path, + count = this.validators.length; + + if (!count) { + return fn(null); + } + + var validate = function(ok, validatorProperties) { + if (err) { + return; + } + if (ok === undefined || ok) { + --count || fn(null); + } else { + err = new ValidatorError(validatorProperties); + fn(err); + } + }; + + var _this = this; + this.validators.forEach(function(v) { + if (err) { + return; + } + + var validator = v.validator; + + var validatorProperties = utils.clone(v); + validatorProperties.path = path; + validatorProperties.value = value; + + if (validator instanceof RegExp) { + validate(validator.test(value), validatorProperties); + } else if (typeof validator === 'function') { + if (value === undefined && !_this.isRequired) { + validate(true, validatorProperties); + return; + } + if (validator.length === 2) { + validator.call(scope, value, function(ok, customMsg) { + if (customMsg) { + validatorProperties.message = customMsg; + } + validate(ok, validatorProperties); + }); + } else { + validate(validator.call(scope, value), validatorProperties); + } + } + }); +}; + +/** + * Performs a validation of `value` using the validators declared for this SchemaType. + * + * ####Note: + * + * This method ignores the asynchronous validators. + * + * @param {any} value + * @param {Object} scope + * @return {MongooseError|undefined} + * @api private + */ + +SchemaType.prototype.doValidateSync = function(value, scope) { + var err = null, + path = this.path, + count = this.validators.length; + + if (!count) { + return null; + } + + var validate = function(ok, validatorProperties) { + if (err) { + return; + } + if (ok !== undefined && !ok) { + err = new ValidatorError(validatorProperties); + } + }; + + var _this = this; + if (value === undefined && !_this.isRequired) { + return null; + } + + this.validators.forEach(function(v) { + if (err) { + return; + } + + var validator = v.validator; + var validatorProperties = utils.clone(v); + validatorProperties.path = path; + validatorProperties.value = value; + + if (validator instanceof RegExp) { + validate(validator.test(value), validatorProperties); + } else if (typeof validator === 'function') { + // if not async validators + if (validator.length !== 2) { + validate(validator.call(scope, value), validatorProperties); + } + } + }); + + return err; +}; + +/** + * Determines if value is a valid Reference. + * + * @param {SchemaType} self + * @param {Object} value + * @param {Document} doc + * @param {Boolean} init + * @return {Boolean} + * @api private + */ + +SchemaType._isRef = function(self, value, doc, init) { + // fast path + var ref = init && self.options && self.options.ref; + + if (!ref && doc && doc.$__fullPath) { + // checks for + // - this populated with adhoc model and no ref was set in schema OR + // - setting / pushing values after population + var path = doc.$__fullPath(self.path); + var owner = doc.ownerDocument ? doc.ownerDocument() : doc; + ref = owner.populated(path); + } + + if (ref) { + if (value == null) { + return true; + } + if (!Buffer.isBuffer(value) && // buffers are objects too + value._bsontype !== 'Binary' // raw binary value from the db + && utils.isObject(value) // might have deselected _id in population query + ) { + return true; + } + } + + return false; +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.castForQuery(val); +} + +/*! + * ignore + */ + +function handleArray(val) { + var _this = this; + if (!Array.isArray(val)) { + return [this.castForQuery(val)]; + } + return val.map(function(m) { + return _this.castForQuery(m); + }); +} + +/*! + * ignore + */ + +SchemaType.prototype.$conditionalHandlers = { + $all: handleArray, + $eq: handleSingle, + $in: handleArray, + $ne: handleSingle, + $nin: handleArray +}; + +/** + * Cast the given value with the given optional query operator. + * + * @param {String} [$conditional] query operator, like `$eq` or `$in` + * @param {any} val + * @api private + */ + +SchemaType.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional); + } + return handler.call(this, val); + } + val = $conditional; + return this.cast(val); +}; + +/** + * Default check for if this path satisfies the `required` validator. + * + * @param {any} val + * @api private + */ + +SchemaType.prototype.checkRequired = function(val) { + return val != null; +}; + +/*! + * Module exports. + */ + +module.exports = exports = SchemaType; + +exports.CastError = CastError; + +exports.ValidatorError = ValidatorError; diff --git a/5-2/service/node_modules/mongoose/lib/services/updateValidators.js b/5-2/service/node_modules/mongoose/lib/services/updateValidators.js new file mode 100644 index 0000000..fd12989 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/services/updateValidators.js @@ -0,0 +1,204 @@ +/*! + * Module dependencies. + */ + +var async = require('async'); +var ValidationError = require('../error/validation.js'); +var ObjectId = require('../types/objectid'); + +/** + * Applies validators and defaults to update and findOneAndUpdate operations, + * specifically passing a null doc as `this` to validators and defaults + * + * @param {Query} query + * @param {Schema} schema + * @param {Object} castedDoc + * @param {Object} options + * @method runValidatorsOnUpdate + * @api private + */ + +module.exports = function(query, schema, castedDoc, options) { + var keys = Object.keys(castedDoc || {}); + var updatedKeys = {}; + var updatedValues = {}; + var numKeys = keys.length; + var hasDollarUpdate = false; + var modified = {}; + + for (var i = 0; i < numKeys; ++i) { + if (keys[i].charAt(0) === '$') { + modifiedPaths(castedDoc[keys[i]], '', modified); + var flat = flatten(castedDoc[keys[i]]); + var paths = Object.keys(flat); + var numPaths = paths.length; + for (var j = 0; j < numPaths; ++j) { + var updatedPath = paths[j].replace('.$.', '.0.'); + updatedPath = updatedPath.replace(/\.\$$/, '.0'); + if (keys[i] === '$set' || keys[i] === '$setOnInsert') { + updatedValues[updatedPath] = flat[paths[j]]; + } else if (keys[i] === '$unset') { + updatedValues[updatedPath] = undefined; + } + updatedKeys[updatedPath] = true; + } + hasDollarUpdate = true; + } + } + + if (!hasDollarUpdate) { + modifiedPaths(castedDoc, '', modified); + updatedValues = flatten(castedDoc); + updatedKeys = Object.keys(updatedValues); + } + + if (options && options.upsert) { + paths = Object.keys(query._conditions); + numPaths = keys.length; + for (i = 0; i < numPaths; ++i) { + var path = paths[i]; + var condition = query._conditions[path]; + if (condition && typeof condition === 'object') { + var conditionKeys = Object.keys(condition); + var numConditionKeys = conditionKeys.length; + var hasDollarKey = false; + for (j = 0; j < numConditionKeys; ++j) { + if (conditionKeys[j].charAt(0) === '$') { + hasDollarKey = true; + break; + } + } + if (hasDollarKey) { + continue; + } + } + updatedKeys[path] = true; + modified[path] = true; + } + + if (options.setDefaultsOnInsert) { + schema.eachPath(function(path, schemaType) { + if (path === '_id') { + // Ignore _id for now because it causes bugs in 2.4 + return; + } + if (schemaType.$isSingleNested) { + // Only handle nested schemas 1-level deep to avoid infinite + // recursion re: https://github.com/mongodb-js/mongoose-autopopulate/issues/11 + schemaType.schema.eachPath(function(_path, _schemaType) { + if (path === '_id') { + // Ignore _id for now because it causes bugs in 2.4 + return; + } + + var def = _schemaType.getDefault(null, true); + if (!modified[path + '.' + _path] && typeof def !== 'undefined') { + castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; + castedDoc.$setOnInsert[path + '.' + _path] = def; + updatedValues[path + '.' + _path] = def; + } + }); + } else { + var def = schemaType.getDefault(null, true); + if (!modified[path] && typeof def !== 'undefined') { + castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; + castedDoc.$setOnInsert[path] = def; + updatedValues[path] = def; + } + } + }); + } + } + + var updates = Object.keys(updatedValues); + var numUpdates = updates.length; + var validatorsToExecute = []; + var validationErrors = []; + function iter(i) { + var schemaPath = schema._getSchema(updates[i]); + if (schemaPath) { + validatorsToExecute.push(function(callback) { + schemaPath.doValidate( + updatedValues[updates[i]], + function(err) { + if (err) { + err.path = updates[i]; + validationErrors.push(err); + } + callback(null); + }, + options && options.context === 'query' ? query : null, + {updateValidator: true}); + }); + } + } + for (i = 0; i < numUpdates; ++i) { + iter(i); + } + + return function(callback) { + async.parallel(validatorsToExecute, function() { + if (validationErrors.length) { + var err = new ValidationError(null); + for (var i = 0; i < validationErrors.length; ++i) { + err.errors[validationErrors[i].path] = validationErrors[i]; + } + return callback(err); + } + callback(null); + }); + }; +}; + +function modifiedPaths(update, path, result) { + var keys = Object.keys(update); + var numKeys = keys.length; + result = result || {}; + path = path ? path + '.' : ''; + + for (var i = 0; i < numKeys; ++i) { + var key = keys[i]; + var val = update[key]; + + result[path + key] = true; + if (shouldFlatten(val)) { + modifiedPaths(val, path + key, result); + } + } + + return result; +} + +function flatten(update, path) { + var keys = Object.keys(update); + var numKeys = keys.length; + var result = {}; + path = path ? path + '.' : ''; + + for (var i = 0; i < numKeys; ++i) { + var key = keys[i]; + var val = update[key]; + if (shouldFlatten(val)) { + var flat = flatten(val, path + key); + for (var k in flat) { + result[k] = flat[k]; + } + if (Array.isArray(val)) { + result[path + key] = val; + } + } else { + result[path + key] = val; + } + } + + return result; +} + +function shouldFlatten(val) { + return val && + typeof val === 'object' && + !(val instanceof Date) && + !(val instanceof ObjectId) && + (!Array.isArray(val) || val.length > 0) && + !(val instanceof Buffer); +} diff --git a/5-2/service/node_modules/mongoose/lib/statemachine.js b/5-2/service/node_modules/mongoose/lib/statemachine.js new file mode 100644 index 0000000..3bba519 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/statemachine.js @@ -0,0 +1,178 @@ + +/*! + * Module dependencies. + */ + +var utils = require('./utils'); + +/*! + * StateMachine represents a minimal `interface` for the + * constructors it builds via StateMachine.ctor(...). + * + * @api private + */ + +var StateMachine = module.exports = exports = function StateMachine() { +}; + +/*! + * StateMachine.ctor('state1', 'state2', ...) + * A factory method for subclassing StateMachine. + * The arguments are a list of states. For each state, + * the constructor's prototype gets state transition + * methods named after each state. These transition methods + * place their path argument into the given state. + * + * @param {String} state + * @param {String} [state] + * @return {Function} subclass constructor + * @private + */ + +StateMachine.ctor = function() { + var states = utils.args(arguments); + + var ctor = function() { + StateMachine.apply(this, arguments); + this.paths = {}; + this.states = {}; + this.stateNames = states; + + var i = states.length, + state; + + while (i--) { + state = states[i]; + this.states[state] = {}; + } + }; + + ctor.prototype = new StateMachine(); + + states.forEach(function(state) { + // Changes the `path`'s state to `state`. + ctor.prototype[state] = function(path) { + this._changeState(path, state); + }; + }); + + return ctor; +}; + +/*! + * This function is wrapped by the state change functions: + * + * - `require(path)` + * - `modify(path)` + * - `init(path)` + * + * @api private + */ + +StateMachine.prototype._changeState = function _changeState(path, nextState) { + var prevBucket = this.states[this.paths[path]]; + if (prevBucket) delete prevBucket[path]; + + this.paths[path] = nextState; + this.states[nextState][path] = true; +}; + +/*! + * ignore + */ + +StateMachine.prototype.clear = function clear(state) { + var keys = Object.keys(this.states[state]), + i = keys.length, + path; + + while (i--) { + path = keys[i]; + delete this.states[state][path]; + delete this.paths[path]; + } +}; + +/*! + * Checks to see if at least one path is in the states passed in via `arguments` + * e.g., this.some('required', 'inited') + * + * @param {String} state that we want to check for. + * @private + */ + +StateMachine.prototype.some = function some() { + var _this = this; + var what = arguments.length ? arguments : this.stateNames; + return Array.prototype.some.call(what, function(state) { + return Object.keys(_this.states[state]).length; + }); +}; + +/*! + * This function builds the functions that get assigned to `forEach` and `map`, + * since both of those methods share a lot of the same logic. + * + * @param {String} iterMethod is either 'forEach' or 'map' + * @return {Function} + * @api private + */ + +StateMachine.prototype._iter = function _iter(iterMethod) { + return function() { + var numArgs = arguments.length, + states = utils.args(arguments, 0, numArgs - 1), + callback = arguments[numArgs - 1]; + + if (!states.length) states = this.stateNames; + + var _this = this; + + var paths = states.reduce(function(paths, state) { + return paths.concat(Object.keys(_this.states[state])); + }, []); + + return paths[iterMethod](function(path, i, paths) { + return callback(path, i, paths); + }); + }; +}; + +/*! + * Iterates over the paths that belong to one of the parameter states. + * + * The function profile can look like: + * this.forEach(state1, fn); // iterates over all paths in state1 + * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 + * this.forEach(fn); // iterates over all paths in all states + * + * @param {String} [state] + * @param {String} [state] + * @param {Function} callback + * @private + */ + +StateMachine.prototype.forEach = function forEach() { + this.forEach = this._iter('forEach'); + return this.forEach.apply(this, arguments); +}; + +/*! + * Maps over the paths that belong to one of the parameter states. + * + * The function profile can look like: + * this.forEach(state1, fn); // iterates over all paths in state1 + * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 + * this.forEach(fn); // iterates over all paths in all states + * + * @param {String} [state] + * @param {String} [state] + * @param {Function} callback + * @return {Array} + * @private + */ + +StateMachine.prototype.map = function map() { + this.map = this._iter('map'); + return this.map.apply(this, arguments); +}; diff --git a/5-2/service/node_modules/mongoose/lib/types/array.js b/5-2/service/node_modules/mongoose/lib/types/array.js new file mode 100644 index 0000000..5bb07f2 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/types/array.js @@ -0,0 +1,786 @@ +/*! + * Module dependencies. + */ + +var EmbeddedDocument = require('./embedded'); +var Document = require('../document'); +var ObjectId = require('./objectid'); +var utils = require('../utils'); +var isMongooseObject = utils.isMongooseObject; + +/** + * Mongoose Array constructor. + * + * ####NOTE: + * + * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ + * + * @param {Array} values + * @param {String} path + * @param {Document} doc parent document + * @api private + * @inherits Array + * @see http://bit.ly/f6CnZU + */ + +function MongooseArray(values, path, doc) { + var arr = [].concat(values); + var props = { + isMongooseArray: true, + validators: [], + _path: path, + _atomics: {}, + _schema: void 0 + }; + var tmp = {}; + + var keysMA = Object.keys(MongooseArray.mixin); + for (var i = 0; i < keysMA.length; ++i) { + tmp[keysMA[i]] = {enumerable: false, configurable: true, writable: true, value: MongooseArray.mixin[keysMA[i]]}; + } + + var keysP = Object.keys(props); + for (var j = 0; j < keysP.length; ++j) { + tmp[keysP[j]] = {enumerable: false, configurable: true, writable: true, value: props[keysP[j]]}; + } + + Object.defineProperties(arr, tmp); + + // Because doc comes from the context of another function, doc === global + // can happen if there was a null somewhere up the chain (see #3020) + // RB Jun 17, 2015 updated to check for presence of expected paths instead + // to make more proof against unusual node environments + if (doc && doc instanceof Document) { + arr._parent = doc; + arr._schema = doc.schema.path(path); + } + + return arr; +} + +MongooseArray.mixin = { + + /** + * Stores a queue of atomic operations to perform + * + * @property _atomics + * @api private + */ + + _atomics: undefined, + + /** + * Parent owner document + * + * @property _parent + * @api private + * @receiver MongooseArray + */ + + _parent: undefined, + + /** + * Casts a member based on this arrays schema. + * + * @param {any} value + * @return value the casted value + * @method _cast + * @api private + * @receiver MongooseArray + */ + + _cast: function(value) { + var owner = this._owner; + var populated = false; + var Model; + + if (this._parent) { + // if a populated array, we must cast to the same model + // instance as specified in the original query. + if (!owner) { + owner = this._owner = this._parent.ownerDocument + ? this._parent.ownerDocument() + : this._parent; + } + + populated = owner.populated(this._path, true); + } + + if (populated && value !== null && value !== undefined) { + // cast to the populated Models schema + Model = populated.options.model; + + // only objects are permitted so we can safely assume that + // non-objects are to be interpreted as _id + if (Buffer.isBuffer(value) || + value instanceof ObjectId || !utils.isObject(value)) { + value = {_id: value}; + } + + // gh-2399 + // we should cast model only when it's not a discriminator + var isDisc = value.schema && value.schema.discriminatorMapping && + value.schema.discriminatorMapping.key !== undefined; + if (!isDisc) { + value = new Model(value); + } + return this._schema.caster.cast(value, this._parent, true); + } + + return this._schema.caster.cast(value, this._parent, false); + }, + + /** + * Marks this array as modified. + * + * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) + * + * @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array + * @param {String} embeddedPath the path which changed in the embeddedDoc + * @method _markModified + * @api private + * @receiver MongooseArray + */ + + _markModified: function(elem, embeddedPath) { + var parent = this._parent, + dirtyPath; + + if (parent) { + dirtyPath = this._path; + + if (arguments.length) { + if (embeddedPath != null) { + // an embedded doc bubbled up the change + dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath; + } else { + // directly set an index + dirtyPath = dirtyPath + '.' + elem; + } + } + + parent.markModified(dirtyPath); + } + + return this; + }, + + /** + * Register an atomic operation with the parent. + * + * @param {Array} op operation + * @param {any} val + * @method _registerAtomic + * @api private + * @receiver MongooseArray + */ + + _registerAtomic: function(op, val) { + if (op === '$set') { + // $set takes precedence over all other ops. + // mark entire array modified. + this._atomics = {$set: val}; + return this; + } + + var atomics = this._atomics; + + // reset pop/shift after save + if (op === '$pop' && !('$pop' in atomics)) { + var _this = this; + this._parent.once('save', function() { + _this._popped = _this._shifted = null; + }); + } + + // check for impossible $atomic combos (Mongo denies more than one + // $atomic op on a single path + if (this._atomics.$set || + Object.keys(atomics).length && !(op in atomics)) { + // a different op was previously registered. + // save the entire thing. + this._atomics = {$set: this}; + return this; + } + + var selector; + + if (op === '$pullAll' || op === '$pushAll' || op === '$addToSet') { + atomics[op] || (atomics[op] = []); + atomics[op] = atomics[op].concat(val); + } else if (op === '$pullDocs') { + var pullOp = atomics['$pull'] || (atomics['$pull'] = {}); + if (val[0] instanceof EmbeddedDocument) { + selector = pullOp['$or'] || (pullOp['$or'] = []); + Array.prototype.push.apply(selector, val.map(function(v) { + return v.toObject({virtuals: false}); + })); + } else { + selector = pullOp['_id'] || (pullOp['_id'] = {$in: []}); + selector['$in'] = selector['$in'].concat(val); + } + } else { + atomics[op] = val; + } + + return this; + }, + + /** + * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. + * + * If no atomics exist, we return all array values after conversion. + * + * @return {Array} + * @method $__getAtomics + * @memberOf MongooseArray + * @api private + */ + + $__getAtomics: function() { + var ret = []; + var keys = Object.keys(this._atomics); + var i = keys.length; + + if (i === 0) { + ret[0] = ['$set', this.toObject({depopulate: 1, transform: false})]; + return ret; + } + + while (i--) { + var op = keys[i]; + var val = this._atomics[op]; + + // the atomic values which are arrays are not MongooseArrays. we + // need to convert their elements as if they were MongooseArrays + // to handle populated arrays versus DocumentArrays properly. + if (isMongooseObject(val)) { + val = val.toObject({depopulate: 1, transform: false}); + } else if (Array.isArray(val)) { + val = this.toObject.call(val, {depopulate: 1, transform: false}); + } else if (val.valueOf) { + val = val.valueOf(); + } + + if (op === '$addToSet') { + val = {$each: val}; + } + + ret.push([op, val]); + } + + return ret; + }, + + /** + * Returns the number of pending atomic operations to send to the db for this array. + * + * @api private + * @return {Number} + * @method hasAtomics + * @receiver MongooseArray + */ + + hasAtomics: function hasAtomics() { + if (!(this._atomics && this._atomics.constructor.name === 'Object')) { + return 0; + } + + return Object.keys(this._atomics).length; + }, + + /** + * Internal helper for .map() + * + * @api private + * @return {Number} + * @method _mapCast + * @receiver MongooseArray + */ + _mapCast: function(val, index) { + return this._cast(val, this.length + index); + }, + + /** + * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. + * + * @param {Object} [args...] + * @api public + * @method push + * @receiver MongooseArray + */ + + push: function() { + var values = [].map.call(arguments, this._mapCast, this); + values = this._schema.applySetters(values, this._parent, undefined, + undefined, {skipDocumentArrayCast: true}); + var ret = [].push.apply(this, values); + + // $pushAll might be fibbed (could be $push). But it makes it easier to + // handle what could have been $push, $pushAll combos + this._registerAtomic('$pushAll', values); + this._markModified(); + return ret; + }, + + /** + * Pushes items to the array non-atomically. + * + * ####NOTE: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @param {any} [args...] + * @api public + * @method nonAtomicPush + * @receiver MongooseArray + */ + + nonAtomicPush: function() { + var values = [].map.call(arguments, this._mapCast, this); + var ret = [].push.apply(this, values); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Pops the array atomically at most one time per document `save()`. + * + * #### NOTE: + * + * _Calling this mulitple times on an array before saving sends the same command as calling it once._ + * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ + * + * doc.array = [1,2,3]; + * + * var popped = doc.array.$pop(); + * console.log(popped); // 3 + * console.log(doc.array); // [1,2] + * + * // no affect + * popped = doc.array.$pop(); + * console.log(doc.array); // [1,2] + * + * doc.save(function (err) { + * if (err) return handleError(err); + * + * // we saved, now $pop works again + * popped = doc.array.$pop(); + * console.log(popped); // 2 + * console.log(doc.array); // [1] + * }) + * + * @api public + * @method $pop + * @memberOf MongooseArray + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop + * @method $pop + * @receiver MongooseArray + */ + + $pop: function() { + this._registerAtomic('$pop', 1); + this._markModified(); + + // only allow popping once + if (this._popped) { + return; + } + this._popped = true; + + return [].pop.call(this); + }, + + /** + * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. + * + * ####Note: + * + * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @see MongooseArray#$pop #types_array_MongooseArray-%24pop + * @api public + * @method pop + * @receiver MongooseArray + */ + + pop: function() { + var ret = [].pop.call(this); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Atomically shifts the array at most one time per document `save()`. + * + * ####NOTE: + * + * _Calling this mulitple times on an array before saving sends the same command as calling it once._ + * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ + * + * doc.array = [1,2,3]; + * + * var shifted = doc.array.$shift(); + * console.log(shifted); // 1 + * console.log(doc.array); // [2,3] + * + * // no affect + * shifted = doc.array.$shift(); + * console.log(doc.array); // [2,3] + * + * doc.save(function (err) { + * if (err) return handleError(err); + * + * // we saved, now $shift works again + * shifted = doc.array.$shift(); + * console.log(shifted ); // 2 + * console.log(doc.array); // [3] + * }) + * + * @api public + * @memberOf MongooseArray + * @method $shift + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop + */ + + $shift: function $shift() { + this._registerAtomic('$pop', -1); + this._markModified(); + + // only allow shifting once + if (this._shifted) { + return; + } + this._shifted = true; + + return [].shift.call(this); + }, + + /** + * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + * + * ####Example: + * + * doc.array = [2,3]; + * var res = doc.array.shift(); + * console.log(res) // 2 + * console.log(doc.array) // [3] + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method shift + * @receiver MongooseArray + */ + + shift: function() { + var ret = [].shift.call(this); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Pulls items from the array atomically. Equality is determined by casting + * the provided value to an embedded document and comparing using + * [the `Document.equals()` function.](./api.html#document_Document-equals) + * + * ####Examples: + * + * doc.array.pull(ObjectId) + * doc.array.pull({ _id: 'someId' }) + * doc.array.pull(36) + * doc.array.pull('tag 1', 'tag 2') + * + * To remove a document from a subdocument array we may pass an object with a matching `_id`. + * + * doc.subdocs.push({ _id: 4815162342 }) + * doc.subdocs.pull({ _id: 4815162342 }) // removed + * + * Or we may passing the _id directly and let mongoose take care of it. + * + * doc.subdocs.push({ _id: 4815162342 }) + * doc.subdocs.pull(4815162342); // works + * + * @param {any} [args...] + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull + * @api public + * @method pull + * @receiver MongooseArray + */ + + pull: function() { + var values = [].map.call(arguments, this._cast, this), + cur = this._parent.get(this._path), + i = cur.length, + mem; + + while (i--) { + mem = cur[i]; + if (mem instanceof Document) { + var some = values.some(function(v) { + return v.equals(mem); + }); + if (some) { + [].splice.call(cur, i, 1); + } + } else if (~cur.indexOf.call(values, mem)) { + [].splice.call(cur, i, 1); + } + } + + if (values[0] instanceof EmbeddedDocument) { + this._registerAtomic('$pullDocs', values.map(function(v) { + return v._id || v; + })); + } else { + this._registerAtomic('$pullAll', values); + } + + this._markModified(); + return this; + }, + + /** + * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method splice + * @receiver MongooseArray + */ + + splice: function splice() { + var ret, vals, i; + + if (arguments.length) { + vals = []; + for (i = 0; i < arguments.length; ++i) { + vals[i] = i < 2 + ? arguments[i] + : this._cast(arguments[i], arguments[0] + (i - 2)); + } + ret = [].splice.apply(this, vals); + this._registerAtomic('$set', this); + this._markModified(); + } + + return ret; + }, + + /** + * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method unshift + * @receiver MongooseArray + */ + + unshift: function() { + var values = [].map.call(arguments, this._cast, this); + values = this._schema.applySetters(values, this._parent); + [].unshift.apply(this, values); + this._registerAtomic('$set', this); + this._markModified(); + return this.length; + }, + + /** + * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. + * + * ####NOTE: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method sort + * @receiver MongooseArray + */ + + sort: function() { + var ret = [].sort.apply(this, arguments); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Adds values to the array if not already present. + * + * ####Example: + * + * console.log(doc.array) // [2,3,4] + * var added = doc.array.addToSet(4,5); + * console.log(doc.array) // [2,3,4,5] + * console.log(added) // [5] + * + * @param {any} [args...] + * @return {Array} the values that were added + * @receiver MongooseArray + * @api public + * @method addToSet + */ + + addToSet: function addToSet() { + var values = [].map.call(arguments, this._mapCast, this); + values = this._schema.applySetters(values, this._parent); + var added = []; + var type = ''; + if (values[0] instanceof EmbeddedDocument) { + type = 'doc'; + } else if (values[0] instanceof Date) { + type = 'date'; + } + + values.forEach(function(v) { + var found; + switch (type) { + case 'doc': + found = this.some(function(doc) { + return doc.equals(v); + }); + break; + case 'date': + var val = +v; + found = this.some(function(d) { + return +d === val; + }); + break; + default: + found = ~this.indexOf(v); + } + + if (!found) { + [].push.call(this, v); + this._registerAtomic('$addToSet', v); + this._markModified(); + [].push.call(added, v); + } + }, this); + + return added; + }, + + /** + * Sets the casted `val` at index `i` and marks the array modified. + * + * ####Example: + * + * // given documents based on the following + * var Doc = mongoose.model('Doc', new Schema({ array: [Number] })); + * + * var doc = new Doc({ array: [2,3,4] }) + * + * console.log(doc.array) // [2,3,4] + * + * doc.array.set(1,"5"); + * console.log(doc.array); // [2,5,4] // properly cast to number + * doc.save() // the change is saved + * + * // VS not using array#set + * doc.array[1] = "5"; + * console.log(doc.array); // [2,"5",4] // no casting + * doc.save() // change is not saved + * + * @return {Array} this + * @api public + * @method set + * @receiver MongooseArray + */ + + set: function set(i, val) { + var value = this._cast(val, i); + value = this._schema.caster instanceof EmbeddedDocument ? + value : + this._schema.caster.applySetters(val, this._parent) + ; + this[i] = value; + this._markModified(i); + return this; + }, + + /** + * Returns a native js Array. + * + * @param {Object} options + * @return {Array} + * @api public + * @method toObject + * @receiver MongooseArray + */ + + toObject: function(options) { + if (options && options.depopulate) { + return this.map(function(doc) { + return doc instanceof Document + ? doc.toObject(options) + : doc; + }); + } + + return this.slice(); + }, + + /** + * Helper for console.log + * + * @api public + * @method inspect + * @receiver MongooseArray + */ + + inspect: function() { + return JSON.stringify(this); + }, + + /** + * Return the index of `obj` or `-1` if not found. + * + * @param {Object} obj the item to look for + * @return {Number} + * @api public + * @method indexOf + * @receiver MongooseArray + */ + + indexOf: function indexOf(obj) { + if (obj instanceof ObjectId) { + obj = obj.toString(); + } + for (var i = 0, len = this.length; i < len; ++i) { + if (obj == this[i]) { + return i; + } + } + return -1; + } +}; + +/** + * Alias of [pull](#types_array_MongooseArray-pull) + * + * @see MongooseArray#pull #types_array_MongooseArray-pull + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull + * @api public + * @memberOf MongooseArray + * @method remove + */ + +MongooseArray.mixin.remove = MongooseArray.mixin.pull; + +/*! + * Module exports. + */ + +module.exports = exports = MongooseArray; diff --git a/5-2/service/node_modules/mongoose/lib/types/buffer.js b/5-2/service/node_modules/mongoose/lib/types/buffer.js new file mode 100644 index 0000000..0c7bbe3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/types/buffer.js @@ -0,0 +1,273 @@ +/*! + * Module dependencies. + */ + +var Binary = require('../drivers').Binary, + utils = require('../utils'); + +/** + * Mongoose Buffer constructor. + * + * Values always have to be passed to the constructor to initialize. + * + * @param {Buffer} value + * @param {String} encode + * @param {Number} offset + * @api private + * @inherits Buffer + * @see http://bit.ly/f6CnZU + */ + +function MongooseBuffer(value, encode, offset) { + var length = arguments.length; + var val; + + if (length === 0 || arguments[0] === null || arguments[0] === undefined) { + val = 0; + } else { + val = value; + } + + var encoding; + var path; + var doc; + + if (Array.isArray(encode)) { + // internal casting + path = encode[0]; + doc = encode[1]; + } else { + encoding = encode; + } + + var buf = new Buffer(val, encoding, offset); + utils.decorate(buf, MongooseBuffer.mixin); + buf.isMongooseBuffer = true; + + // make sure these internal props don't show up in Object.keys() + Object.defineProperties(buf, { + validators: {value: []}, + _path: {value: path}, + _parent: {value: doc} + }); + + if (doc && typeof path === 'string') { + Object.defineProperty(buf, '_schema', { + value: doc.schema.path(path) + }); + } + + buf._subtype = 0; + return buf; +} + +/*! + * Inherit from Buffer. + */ + +// MongooseBuffer.prototype = new Buffer(0); + +MongooseBuffer.mixin = { + + /** + * Parent owner document + * + * @api private + * @property _parent + * @receiver MongooseBuffer + */ + + _parent: undefined, + + /** + * Default subtype for the Binary representing this Buffer + * + * @api private + * @property _subtype + * @receiver MongooseBuffer + */ + + _subtype: undefined, + + /** + * Marks this buffer as modified. + * + * @api private + * @method _markModified + * @receiver MongooseBuffer + */ + + _markModified: function() { + var parent = this._parent; + + if (parent) { + parent.markModified(this._path); + } + return this; + }, + + /** + * Writes the buffer. + * + * @api public + * @method write + * @receiver MongooseBuffer + */ + + write: function() { + var written = Buffer.prototype.write.apply(this, arguments); + + if (written > 0) { + this._markModified(); + } + + return written; + }, + + /** + * Copies the buffer. + * + * ####Note: + * + * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. + * + * @return {MongooseBuffer} + * @param {Buffer} target + * @method copy + * @receiver MongooseBuffer + */ + + copy: function(target) { + var ret = Buffer.prototype.copy.apply(this, arguments); + + if (target && target.isMongooseBuffer) { + target._markModified(); + } + + return ret; + } +}; + +/*! + * Compile other Buffer methods marking this buffer as modified. + */ + +( +// node < 0.5 + 'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' + + 'writeFloat writeDouble fill ' + + 'utf8Write binaryWrite asciiWrite set ' + + +// node >= 0.5 + 'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' + + 'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' + + 'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE' +).split(' ').forEach(function(method) { + if (!Buffer.prototype[method]) { + return; + } + MongooseBuffer.mixin[method] = function() { + var ret = Buffer.prototype[method].apply(this, arguments); + this._markModified(); + return ret; + }; +}); + +/** + * Converts this buffer to its Binary type representation. + * + * ####SubTypes: + * + * var bson = require('bson') + * bson.BSON_BINARY_SUBTYPE_DEFAULT + * bson.BSON_BINARY_SUBTYPE_FUNCTION + * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY + * bson.BSON_BINARY_SUBTYPE_UUID + * bson.BSON_BINARY_SUBTYPE_MD5 + * bson.BSON_BINARY_SUBTYPE_USER_DEFINED + * + * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED); + * + * @see http://bsonspec.org/#/specification + * @param {Hex} [subtype] + * @return {Binary} + * @api public + * @method toObject + * @receiver MongooseBuffer + */ + +MongooseBuffer.mixin.toObject = function(options) { + var subtype = typeof options === 'number' + ? options + : (this._subtype || 0); + return new Binary(this, subtype); +}; + +/** + * Determines if this buffer is equals to `other` buffer + * + * @param {Buffer} other + * @return {Boolean} + * @method equals + * @receiver MongooseBuffer + */ + +MongooseBuffer.mixin.equals = function(other) { + if (!Buffer.isBuffer(other)) { + return false; + } + + if (this.length !== other.length) { + return false; + } + + for (var i = 0; i < this.length; ++i) { + if (this[i] !== other[i]) { + return false; + } + } + + return true; +}; + +/** + * Sets the subtype option and marks the buffer modified. + * + * ####SubTypes: + * + * var bson = require('bson') + * bson.BSON_BINARY_SUBTYPE_DEFAULT + * bson.BSON_BINARY_SUBTYPE_FUNCTION + * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY + * bson.BSON_BINARY_SUBTYPE_UUID + * bson.BSON_BINARY_SUBTYPE_MD5 + * bson.BSON_BINARY_SUBTYPE_USER_DEFINED + * + * doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID); + * + * @see http://bsonspec.org/#/specification + * @param {Hex} subtype + * @api public + * @method subtype + * @receiver MongooseBuffer + */ + +MongooseBuffer.mixin.subtype = function(subtype) { + if (typeof subtype !== 'number') { + throw new TypeError('Invalid subtype. Expected a number'); + } + + if (this._subtype !== subtype) { + this._markModified(); + } + + this._subtype = subtype; +}; + +/*! + * Module exports. + */ + +MongooseBuffer.Binary = Binary; + +module.exports = MongooseBuffer; diff --git a/5-2/service/node_modules/mongoose/lib/types/documentarray.js b/5-2/service/node_modules/mongoose/lib/types/documentarray.js new file mode 100644 index 0000000..5382b35 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/types/documentarray.js @@ -0,0 +1,245 @@ +/*! + * Module dependencies. + */ + +var MongooseArray = require('./array'), + ObjectId = require('./objectid'), + ObjectIdSchema = require('../schema/objectid'), + utils = require('../utils'), + Document = require('../document'); + +/** + * DocumentArray constructor + * + * @param {Array} values + * @param {String} path the path to this array + * @param {Document} doc parent document + * @api private + * @return {MongooseDocumentArray} + * @inherits MongooseArray + * @see http://bit.ly/f6CnZU + */ + +function MongooseDocumentArray(values, path, doc) { + var arr = [].concat(values); + var props = { + isMongooseArray: true, + isMongooseDocumentArray: true, + validators: [], + _path: path, + _atomics: {}, + _schema: void 0, + _handlers: void 0 + }; + var tmp = {}; + + // Values always have to be passed to the constructor to initialize, since + // otherwise MongooseArray#push will mark the array as modified to the parent. + var keysMA = Object.keys(MongooseArray.mixin); + for (var j = 0; j < keysMA.length; ++j) { + tmp[keysMA[j]] = {enumerable: false, configurable: true, writable: true, value: MongooseArray.mixin[keysMA[j]]}; + } + + var keysMDA = Object.keys(MongooseDocumentArray.mixin); + for (var i = 0; i < keysMDA.length; ++i) { + tmp[keysMDA[i]] = {enumerable: false, configurable: true, writable: true, value: MongooseDocumentArray.mixin[keysMDA[i]]}; + } + + var keysP = Object.keys(props); + for (var k = 0; k < keysP.length; ++k) { + tmp[keysP[k]] = {enumerable: false, configurable: true, writable: true, value: props[keysP[k]]}; + } + + Object.defineProperties(arr, tmp); + + // Because doc comes from the context of another function, doc === global + // can happen if there was a null somewhere up the chain (see #3020 && #3034) + // RB Jun 17, 2015 updated to check for presence of expected paths instead + // to make more proof against unusual node environments + if (doc && doc instanceof Document) { + arr._parent = doc; + arr._schema = doc.schema.path(path); + arr._handlers = { + isNew: arr.notify('isNew'), + save: arr.notify('save') + }; + + doc.on('save', arr._handlers.save); + doc.on('isNew', arr._handlers.isNew); + } + + return arr; +} + +/*! + * Inherits from MongooseArray + */ +// MongooseDocumentArray.mixin = Object.create( MongooseArray.mixin ); +MongooseDocumentArray.mixin = { + + /** + * Overrides MongooseArray#cast + * + * @method _cast + * @api private + * @receiver MongooseDocumentArray + */ + + _cast: function(value, index) { + if (value instanceof this._schema.casterConstructor) { + if (!(value.__parent && value.__parentArray)) { + // value may have been created using array.create() + value.__parent = this._parent; + value.__parentArray = this; + } + value.__index = index; + return value; + } + + // handle cast('string') or cast(ObjectId) etc. + // only objects are permitted so we can safely assume that + // non-objects are to be interpreted as _id + if (Buffer.isBuffer(value) || + value instanceof ObjectId || !utils.isObject(value)) { + value = {_id: value}; + } + return new this._schema.casterConstructor(value, this, undefined, undefined, index); + }, + + /** + * Searches array items for the first document with a matching _id. + * + * ####Example: + * + * var embeddedDoc = m.array.id(some_id); + * + * @return {EmbeddedDocument|null} the subdocument or null if not found. + * @param {ObjectId|String|Number|Buffer} id + * @TODO cast to the _id based on schema for proper comparison + * @method id + * @api public + * @receiver MongooseDocumentArray + */ + + id: function(id) { + var casted, + sid, + _id; + + try { + var casted_ = ObjectIdSchema.prototype.cast.call({}, id); + if (casted_) { + casted = String(casted_); + } + } catch (e) { + casted = null; + } + + for (var i = 0, l = this.length; i < l; i++) { + _id = this[i].get('_id'); + + if (_id === null || typeof _id === 'undefined') { + continue; + } else if (_id instanceof Document) { + sid || (sid = String(id)); + if (sid == _id._id) { + return this[i]; + } + } else if (!(_id instanceof ObjectId)) { + if (utils.deepEqual(id, _id)) { + return this[i]; + } + } else if (casted == _id) { + return this[i]; + } + } + + return null; + }, + + /** + * Returns a native js Array of plain js objects + * + * ####NOTE: + * + * _Each sub-document is converted to a plain object by calling its `#toObject` method._ + * + * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion + * @return {Array} + * @method toObject + * @api public + * @receiver MongooseDocumentArray + */ + + toObject: function(options) { + return this.map(function(doc) { + return doc && doc.toObject(options) || null; + }); + }, + + /** + * Helper for console.log + * + * @method inspect + * @api public + * @receiver MongooseDocumentArray + */ + + inspect: function() { + return Array.prototype.slice.call(this); + }, + + /** + * Creates a subdocument casted to this schema. + * + * This is the same subdocument constructor used for casting. + * + * @param {Object} obj the value to cast to this arrays SubDocument schema + * @method create + * @api public + * @receiver MongooseDocumentArray + */ + + create: function(obj) { + return new this._schema.casterConstructor(obj); + }, + + /** + * Creates a fn that notifies all child docs of `event`. + * + * @param {String} event + * @return {Function} + * @method notify + * @api private + * @receiver MongooseDocumentArray + */ + + notify: function notify(event) { + var _this = this; + return function notify(val) { + var i = _this.length; + while (i--) { + if (!_this[i]) { + continue; + } + switch (event) { + // only swap for save event for now, we may change this to all event types later + case 'save': + val = _this[i]; + break; + default: + // NO-OP + break; + } + _this[i].emit(event, val); + } + }; + } + +}; + +/*! + * Module exports. + */ + +module.exports = MongooseDocumentArray; diff --git a/5-2/service/node_modules/mongoose/lib/types/embedded.js b/5-2/service/node_modules/mongoose/lib/types/embedded.js new file mode 100644 index 0000000..feecf12 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/types/embedded.js @@ -0,0 +1,319 @@ +/* eslint no-func-assign: 1 */ + +/*! + * Module dependencies. + */ + +var Document = require('../document_provider')(); +var PromiseProvider = require('../promise_provider'); + +/** + * EmbeddedDocument constructor. + * + * @param {Object} obj js object returned from the db + * @param {MongooseDocumentArray} parentArr the parent array of this document + * @param {Boolean} skipId + * @inherits Document + * @api private + */ + +function EmbeddedDocument(obj, parentArr, skipId, fields, index) { + if (parentArr) { + this.__parentArray = parentArr; + this.__parent = parentArr._parent; + } else { + this.__parentArray = undefined; + this.__parent = undefined; + } + this.__index = index; + + Document.call(this, obj, fields, skipId); + + var _this = this; + this.on('isNew', function(val) { + _this.isNew = val; + }); +} + +/*! + * Inherit from Document + */ +EmbeddedDocument.prototype = Object.create(Document.prototype); +EmbeddedDocument.prototype.constructor = EmbeddedDocument; + +/** + * Marks the embedded doc modified. + * + * ####Example: + * + * var doc = blogpost.comments.id(hexstring); + * doc.mixed.type = 'changed'; + * doc.markModified('mixed.type'); + * + * @param {String} path the path which changed + * @api public + * @receiver EmbeddedDocument + */ + +EmbeddedDocument.prototype.markModified = function(path) { + this.$__.activePaths.modify(path); + if (!this.__parentArray) { + return; + } + + if (this.isNew) { + // Mark the WHOLE parent array as modified + // if this is a new document (i.e., we are initializing + // a document), + this.__parentArray._markModified(); + } else { + this.__parentArray._markModified(this, path); + } +}; + +/** + * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) + * + * ####NOTE: + * + * _This is a no-op. Does not actually save the doc to the db._ + * + * @param {Function} [fn] + * @return {Promise} resolved Promise + * @api private + */ + +EmbeddedDocument.prototype.save = function(fn) { + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve) { + fn && fn(); + resolve(); + }); +}; + +/*! + * Registers remove event listeners for triggering + * on subdocuments. + * + * @param {EmbeddedDocument} sub + * @api private + */ + +function registerRemoveListener(sub) { + var owner = sub.ownerDocument(); + + function emitRemove() { + owner.removeListener('save', emitRemove); + owner.removeListener('remove', emitRemove); + sub.emit('remove', sub); + owner = sub = null; + } + + owner.on('save', emitRemove); + owner.on('remove', emitRemove); +} + +/** + * Removes the subdocument from its parent array. + * + * @param {Function} [fn] + * @api public + */ + +EmbeddedDocument.prototype.remove = function(fn) { + if (!this.__parentArray) { + return this; + } + + var _id; + if (!this.willRemove) { + _id = this._doc._id; + if (!_id) { + throw new Error('For your own good, Mongoose does not know ' + + 'how to remove an EmbeddedDocument that has no _id'); + } + this.__parentArray.pull({_id: _id}); + this.willRemove = true; + registerRemoveListener(this); + } + + if (fn) { + fn(null); + } + + return this; +}; + +/** + * Override #update method of parent documents. + * @api private + */ + +EmbeddedDocument.prototype.update = function() { + throw new Error('The #update method is not available on EmbeddedDocuments'); +}; + +/** + * Helper for console.log + * + * @api public + */ + +EmbeddedDocument.prototype.inspect = function() { + return this.toObject(); +}; + +/** + * Marks a path as invalid, causing validation to fail. + * + * @param {String} path the field to invalidate + * @param {String|Error} err error which states the reason `path` was invalid + * @return {Boolean} + * @api public + */ + +EmbeddedDocument.prototype.invalidate = function(path, err, val, first) { + if (!this.__parent) { + var msg = 'Unable to invalidate a subdocument that has not been added to an array.'; + throw new Error(msg); + } + + var index = this.__index; + if (typeof index !== 'undefined') { + var parentPath = this.__parentArray._path; + var fullPath = [parentPath, index, path].join('.'); + this.__parent.invalidate(fullPath, err, val); + } + + if (first) { + this.$__.validationError = this.ownerDocument().$__.validationError; + } + + return true; +}; + +/** + * Marks a path as valid, removing existing validation errors. + * + * @param {String} path the field to mark as valid + * @api private + * @method $markValid + * @receiver EmbeddedDocument + */ + +EmbeddedDocument.prototype.$markValid = function(path) { + if (!this.__parent) { + return; + } + + var index = this.__index; + if (typeof index !== 'undefined') { + var parentPath = this.__parentArray._path; + var fullPath = [parentPath, index, path].join('.'); + this.__parent.$markValid(fullPath); + } +}; + +/** + * Checks if a path is invalid + * + * @param {String} path the field to check + * @api private + * @method $isValid + * @receiver EmbeddedDocument + */ + +EmbeddedDocument.prototype.$isValid = function(path) { + var index = this.__index; + if (typeof index !== 'undefined') { + return !this.__parent.$__.validationError || !this.__parent.$__.validationError.errors[path]; + } + + return true; +}; + +/** + * Returns the top level document of this sub-document. + * + * @return {Document} + */ + +EmbeddedDocument.prototype.ownerDocument = function() { + if (this.$__.ownerDocument) { + return this.$__.ownerDocument; + } + + var parent = this.__parent; + if (!parent) { + return this; + } + + while (parent.__parent) { + parent = parent.__parent; + } + + this.$__.ownerDocument = parent; + return this.$__.ownerDocument; +}; + +/** + * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. + * + * @param {String} [path] + * @return {String} + * @api private + * @method $__fullPath + * @memberOf EmbeddedDocument + */ + +EmbeddedDocument.prototype.$__fullPath = function(path) { + if (!this.$__.fullPath) { + var parent = this; // eslint-disable-line consistent-this + if (!parent.__parent) { + return path; + } + + var paths = []; + while (parent.__parent) { + paths.unshift(parent.__parentArray._path); + parent = parent.__parent; + } + + this.$__.fullPath = paths.join('.'); + + if (!this.$__.ownerDocument) { + // optimization + this.$__.ownerDocument = parent; + } + } + + return path + ? this.$__.fullPath + '.' + path + : this.$__.fullPath; +}; + +/** + * Returns this sub-documents parent document. + * + * @api public + */ + +EmbeddedDocument.prototype.parent = function() { + return this.__parent; +}; + +/** + * Returns this sub-documents parent array. + * + * @api public + */ + +EmbeddedDocument.prototype.parentArray = function() { + return this.__parentArray; +}; + +/*! + * Module exports. + */ + +module.exports = EmbeddedDocument; diff --git a/5-2/service/node_modules/mongoose/lib/types/index.js b/5-2/service/node_modules/mongoose/lib/types/index.js new file mode 100644 index 0000000..0d01923 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/types/index.js @@ -0,0 +1,15 @@ + +/*! + * Module exports. + */ + +exports.Array = require('./array'); +exports.Buffer = require('./buffer'); + +exports.Document = // @deprecate +exports.Embedded = require('./embedded'); + +exports.DocumentArray = require('./documentarray'); +exports.ObjectId = require('./objectid'); + +exports.Subdocument = require('./subdocument'); diff --git a/5-2/service/node_modules/mongoose/lib/types/objectid.js b/5-2/service/node_modules/mongoose/lib/types/objectid.js new file mode 100644 index 0000000..9fe0b97 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/types/objectid.js @@ -0,0 +1,13 @@ +/** + * ObjectId type constructor + * + * ####Example + * + * var id = new mongoose.Types.ObjectId; + * + * @constructor ObjectId + */ + +var ObjectId = require('../drivers').ObjectId; + +module.exports = ObjectId; diff --git a/5-2/service/node_modules/mongoose/lib/types/subdocument.js b/5-2/service/node_modules/mongoose/lib/types/subdocument.js new file mode 100644 index 0000000..de127a5 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/types/subdocument.js @@ -0,0 +1,123 @@ +var Document = require('../document'); +var PromiseProvider = require('../promise_provider'); + +module.exports = Subdocument; + +/** + * Subdocument constructor. + * + * @inherits Document + * @api private + */ + +function Subdocument() { + Document.apply(this, arguments); + this.$isSingleNested = true; +} + +Subdocument.prototype = Object.create(Document.prototype); + +/** + * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) + * + * ####NOTE: + * + * _This is a no-op. Does not actually save the doc to the db._ + * + * @param {Function} [fn] + * @return {Promise} resolved Promise + * @api private + */ + +Subdocument.prototype.save = function(fn) { + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve) { + fn && fn(); + resolve(); + }); +}; + +Subdocument.prototype.$isValid = function(path) { + if (this.$parent) { + return this.$parent.$isValid([this.$basePath, path].join('.')); + } +}; + +Subdocument.prototype.markModified = function(path) { + if (this.$parent) { + this.$parent.markModified([this.$basePath, path].join('.')); + } +}; + +Subdocument.prototype.$markValid = function(path) { + if (this.$parent) { + this.$parent.$markValid([this.$basePath, path].join('.')); + } +}; + +Subdocument.prototype.invalidate = function(path, err, val) { + if (this.$parent) { + this.$parent.invalidate([this.$basePath, path].join('.'), err, val); + } else if (err.kind === 'cast' || err.name === 'CastError') { + throw err; + } +}; + +/** + * Returns the top level document of this sub-document. + * + * @return {Document} + */ + +Subdocument.prototype.ownerDocument = function() { + if (this.$__.ownerDocument) { + return this.$__.ownerDocument; + } + + var parent = this.$parent; + if (!parent) { + return this; + } + + while (parent.$parent) { + parent = parent.$parent; + } + this.$__.ownerDocument = parent; + return this.$__.ownerDocument; +}; + +/** + * Null-out this subdoc + * + * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove + */ + +Subdocument.prototype.remove = function(callback) { + this.$parent.set(this.$basePath, null); + registerRemoveListener(this); + if (callback) { + callback(null); + } +}; + +/*! + * Registers remove event listeners for triggering + * on subdocuments. + * + * @param {EmbeddedDocument} sub + * @api private + */ + +function registerRemoveListener(sub) { + var owner = sub.ownerDocument(); + + function emitRemove() { + owner.removeListener('save', emitRemove); + owner.removeListener('remove', emitRemove); + sub.emit('remove', sub); + owner = sub = null; + } + + owner.on('save', emitRemove); + owner.on('remove', emitRemove); +} diff --git a/5-2/service/node_modules/mongoose/lib/utils.js b/5-2/service/node_modules/mongoose/lib/utils.js new file mode 100644 index 0000000..8747774 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/utils.js @@ -0,0 +1,841 @@ +/*! + * Module dependencies. + */ + +var ObjectId = require('./types/objectid'); +var cloneRegExp = require('regexp-clone'); +var sliced = require('sliced'); +var mpath = require('mpath'); +var ms = require('ms'); +var MongooseBuffer; +var MongooseArray; +var Document; + +/*! + * Produces a collection name from model `name`. + * + * @param {String} name a model name + * @return {String} a collection name + * @api private + */ + +exports.toCollectionName = function(name, options) { + options = options || {}; + if (name === 'system.profile') { + return name; + } + if (name === 'system.indexes') { + return name; + } + if (options.pluralization === false) { + return name; + } + return pluralize(name.toLowerCase()); +}; + +/** + * Pluralization rules. + * + * These rules are applied while processing the argument to `toCollectionName`. + * + * @deprecated remove in 4.x gh-1350 + */ + +exports.pluralization = [ + [/(m)an$/gi, '$1en'], + [/(pe)rson$/gi, '$1ople'], + [/(child)$/gi, '$1ren'], + [/^(ox)$/gi, '$1en'], + [/(ax|test)is$/gi, '$1es'], + [/(octop|vir)us$/gi, '$1i'], + [/(alias|status)$/gi, '$1es'], + [/(bu)s$/gi, '$1ses'], + [/(buffal|tomat|potat)o$/gi, '$1oes'], + [/([ti])um$/gi, '$1a'], + [/sis$/gi, 'ses'], + [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'], + [/(hive)$/gi, '$1s'], + [/([^aeiouy]|qu)y$/gi, '$1ies'], + [/(x|ch|ss|sh)$/gi, '$1es'], + [/(matr|vert|ind)ix|ex$/gi, '$1ices'], + [/([m|l])ouse$/gi, '$1ice'], + [/(kn|w|l)ife$/gi, '$1ives'], + [/(quiz)$/gi, '$1zes'], + [/s$/gi, 's'], + [/([^a-z])$/, '$1'], + [/$/gi, 's'] +]; +var rules = exports.pluralization; + +/** + * Uncountable words. + * + * These words are applied while processing the argument to `toCollectionName`. + * @api public + */ + +exports.uncountables = [ + 'advice', + 'energy', + 'excretion', + 'digestion', + 'cooperation', + 'health', + 'justice', + 'labour', + 'machinery', + 'equipment', + 'information', + 'pollution', + 'sewage', + 'paper', + 'money', + 'species', + 'series', + 'rain', + 'rice', + 'fish', + 'sheep', + 'moose', + 'deer', + 'news', + 'expertise', + 'status', + 'media' +]; +var uncountables = exports.uncountables; + +/*! + * Pluralize function. + * + * @author TJ Holowaychuk (extracted from _ext.js_) + * @param {String} string to pluralize + * @api private + */ + +function pluralize(str) { + var found; + if (!~uncountables.indexOf(str.toLowerCase())) { + found = rules.filter(function(rule) { + return str.match(rule[0]); + }); + if (found[0]) { + return str.replace(found[0][0], found[0][1]); + } + } + return str; +} + +/*! + * Determines if `a` and `b` are deep equal. + * + * Modified from node/lib/assert.js + * + * @param {any} a a value to compare to `b` + * @param {any} b a value to compare to `a` + * @return {Boolean} + * @api private + */ + +exports.deepEqual = function deepEqual(a, b) { + if (a === b) { + return true; + } + + if (a instanceof Date && b instanceof Date) { + return a.getTime() === b.getTime(); + } + + if (a instanceof ObjectId && b instanceof ObjectId) { + return a.toString() === b.toString(); + } + + if (a instanceof RegExp && b instanceof RegExp) { + return a.source === b.source && + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline && + a.global === b.global; + } + + if (typeof a !== 'object' && typeof b !== 'object') { + return a == b; + } + + if (a === null || b === null || a === undefined || b === undefined) { + return false; + } + + if (a.prototype !== b.prototype) { + return false; + } + + // Handle MongooseNumbers + if (a instanceof Number && b instanceof Number) { + return a.valueOf() === b.valueOf(); + } + + if (Buffer.isBuffer(a)) { + return exports.buffer.areEqual(a, b); + } + + if (isMongooseObject(a)) { + a = a.toObject(); + } + if (isMongooseObject(b)) { + b = b.toObject(); + } + + try { + var ka = Object.keys(a), + kb = Object.keys(b), + key, i; + } catch (e) { + // happens when one is a string literal and the other isn't + return false; + } + + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) { + return false; + } + + // the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + + // ~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) { + return false; + } + } + + // equivalent values for every corresponding key, and + // ~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!deepEqual(a[key], b[key])) { + return false; + } + } + + return true; +}; + +/*! + * Object clone with Mongoose natives support. + * + * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. + * + * Functions are never cloned. + * + * @param {Object} obj the object to clone + * @param {Object} options + * @return {Object} the cloned object + * @api private + */ + +exports.clone = function clone(obj, options) { + if (obj === undefined || obj === null) { + return obj; + } + + if (Array.isArray(obj)) { + return cloneArray(obj, options); + } + + if (isMongooseObject(obj)) { + if (options && options.json && typeof obj.toJSON === 'function') { + return obj.toJSON(options); + } + return obj.toObject(options); + } + + if (obj.constructor) { + switch (exports.getFunctionName(obj.constructor)) { + case 'Object': + return cloneObject(obj, options); + case 'Date': + return new obj.constructor(+obj); + case 'RegExp': + return cloneRegExp(obj); + default: + // ignore + break; + } + } + + if (obj instanceof ObjectId) { + return new ObjectId(obj.id); + } + + if (!obj.constructor && exports.isObject(obj)) { + // object created with Object.create(null) + return cloneObject(obj, options); + } + + if (obj.valueOf) { + return obj.valueOf(); + } +}; +var clone = exports.clone; + +/*! + * ignore + */ + +function cloneObject(obj, options) { + var retainKeyOrder = options && options.retainKeyOrder, + minimize = options && options.minimize, + ret = {}, + hasKeys, + keys, + val, + k, + i; + + if (retainKeyOrder) { + for (k in obj) { + val = clone(obj[k], options); + + if (!minimize || (typeof val !== 'undefined')) { + hasKeys || (hasKeys = true); + ret[k] = val; + } + } + } else { + // faster + + keys = Object.keys(obj); + i = keys.length; + + while (i--) { + k = keys[i]; + val = clone(obj[k], options); + + if (!minimize || (typeof val !== 'undefined')) { + if (!hasKeys) { + hasKeys = true; + } + ret[k] = val; + } + } + } + + return minimize + ? hasKeys && ret + : ret; +} + +function cloneArray(arr, options) { + var ret = []; + for (var i = 0, l = arr.length; i < l; i++) { + ret.push(clone(arr[i], options)); + } + return ret; +} + +/*! + * Shallow copies defaults into options. + * + * @param {Object} defaults + * @param {Object} options + * @return {Object} the merged object + * @api private + */ + +exports.options = function(defaults, options) { + var keys = Object.keys(defaults), + i = keys.length, + k; + + options = options || {}; + + while (i--) { + k = keys[i]; + if (!(k in options)) { + options[k] = defaults[k]; + } + } + + return options; +}; + +/*! + * Generates a random string + * + * @api private + */ + +exports.random = function() { + return Math.random().toString().substr(3); +}; + +/*! + * Merges `from` into `to` without overwriting existing properties. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +exports.merge = function merge(to, from) { + var keys = Object.keys(from), + i = keys.length, + key; + + while (i--) { + key = keys[i]; + if (typeof to[key] === 'undefined') { + to[key] = from[key]; + } else if (exports.isObject(from[key])) { + merge(to[key], from[key]); + } + } +}; + +/*! + * toString helper + */ + +var toString = Object.prototype.toString; + +/*! + * Applies toObject recursively. + * + * @param {Document|Array|Object} obj + * @return {Object} + * @api private + */ + +exports.toObject = function toObject(obj) { + var ret; + + if (exports.isNullOrUndefined(obj)) { + return obj; + } + + if (obj instanceof Document) { + return obj.toObject(); + } + + if (Array.isArray(obj)) { + ret = []; + + for (var i = 0, len = obj.length; i < len; ++i) { + ret.push(toObject(obj[i])); + } + + return ret; + } + + if ((obj.constructor && exports.getFunctionName(obj.constructor) === 'Object') || + (!obj.constructor && exports.isObject(obj))) { + ret = {}; + + for (var k in obj) { + ret[k] = toObject(obj[k]); + } + + return ret; + } + + return obj; +}; + +/*! + * Determines if `arg` is an object. + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @api private + * @return {Boolean} + */ + +exports.isObject = function(arg) { + if (Buffer.isBuffer(arg)) { + return true; + } + return toString.call(arg) === '[object Object]'; +}; + +/*! + * A faster Array.prototype.slice.call(arguments) alternative + * @api private + */ + +exports.args = sliced; + +/*! + * process.nextTick helper. + * + * Wraps `callback` in a try/catch + nextTick. + * + * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. + * + * @param {Function} callback + * @api private + */ + +exports.tick = function tick(callback) { + if (typeof callback !== 'function') { + return; + } + return function() { + try { + callback.apply(this, arguments); + } catch (err) { + // only nextTick on err to get out of + // the event loop and avoid state corruption. + process.nextTick(function() { + throw err; + }); + } + }; +}; + +/*! + * Returns if `v` is a mongoose object that has a `toObject()` method we can use. + * + * This is for compatibility with libs like Date.js which do foolish things to Natives. + * + * @param {any} v + * @api private + */ + +exports.isMongooseObject = function(v) { + Document || (Document = require('./document')); + MongooseArray || (MongooseArray = require('./types').Array); + MongooseBuffer || (MongooseBuffer = require('./types').Buffer); + + return v instanceof Document || + (v && v.isMongooseArray) || + (v && v.isMongooseBuffer); +}; +var isMongooseObject = exports.isMongooseObject; + +/*! + * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. + * + * @param {Object} object + * @api private + */ + +exports.expires = function expires(object) { + if (!(object && object.constructor.name === 'Object')) { + return; + } + if (!('expires' in object)) { + return; + } + + var when; + if (typeof object.expires !== 'string') { + when = object.expires; + } else { + when = Math.round(ms(object.expires) / 1000); + } + object.expireAfterSeconds = when; + delete object.expires; +}; + +/*! + * Populate options constructor + */ + +function PopulateOptions(path, select, match, options, model, subPopulate) { + this.path = path; + this.match = match; + this.select = select; + this.options = options; + this.model = model; + if (typeof subPopulate === 'object') { + this.populate = subPopulate; + } + this._docs = {}; +} + +// make it compatible with utils.clone +PopulateOptions.prototype.constructor = Object; + +// expose +exports.PopulateOptions = PopulateOptions; + +/*! + * populate helper + */ + +exports.populate = function populate(path, select, model, match, options, subPopulate) { + // The order of select/conditions args is opposite Model.find but + // necessary to keep backward compatibility (select could be + // an array, string, or object literal). + + // might have passed an object specifying all arguments + if (arguments.length === 1) { + if (path instanceof PopulateOptions) { + return [path]; + } + + if (Array.isArray(path)) { + return path.map(function(o) { + return exports.populate(o)[0]; + }); + } + + if (exports.isObject(path)) { + match = path.match; + options = path.options; + select = path.select; + model = path.model; + subPopulate = path.populate; + path = path.path; + } + } else if (typeof model !== 'string' && typeof model !== 'function') { + options = match; + match = model; + model = undefined; + } + + if (typeof path !== 'string') { + throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); + } + + if (typeof subPopulate === 'object') { + subPopulate = exports.populate(subPopulate); + } + + var ret = []; + var paths = path.split(' '); + for (var i = 0; i < paths.length; ++i) { + ret.push(new PopulateOptions(paths[i], select, match, options, model, subPopulate)); + } + + return ret; +}; + +/*! + * Return the value of `obj` at the given `path`. + * + * @param {String} path + * @param {Object} obj + */ + +exports.getValue = function(path, obj, map) { + return mpath.get(path, obj, '_doc', map); +}; + +/*! + * Sets the value of `obj` at the given `path`. + * + * @param {String} path + * @param {Anything} val + * @param {Object} obj + */ + +exports.setValue = function(path, val, obj, map) { + mpath.set(path, val, obj, '_doc', map); +}; + +/*! + * Returns an array of values from object `o`. + * + * @param {Object} o + * @return {Array} + * @private + */ + +exports.object = {}; +exports.object.vals = function vals(o) { + var keys = Object.keys(o), + i = keys.length, + ret = []; + + while (i--) { + ret.push(o[keys[i]]); + } + + return ret; +}; + +/*! + * @see exports.options + */ + +exports.object.shallowCopy = exports.options; + +/*! + * Safer helper for hasOwnProperty checks + * + * @param {Object} obj + * @param {String} prop + */ + +var hop = Object.prototype.hasOwnProperty; +exports.object.hasOwnProperty = function(obj, prop) { + return hop.call(obj, prop); +}; + +/*! + * Determine if `val` is null or undefined + * + * @return {Boolean} + */ + +exports.isNullOrUndefined = function(val) { + return val === null || val === undefined; +}; + +/*! + * ignore + */ + +exports.array = {}; + +/*! + * Flattens an array. + * + * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] + * + * @param {Array} arr + * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsey value, the item will not be included in the results. + * @return {Array} + * @private + */ + +exports.array.flatten = function flatten(arr, filter, ret) { + ret || (ret = []); + + arr.forEach(function(item) { + if (Array.isArray(item)) { + flatten(item, filter, ret); + } else { + if (!filter || filter(item)) { + ret.push(item); + } + } + }); + + return ret; +}; + +/*! + * Removes duplicate values from an array + * + * [1, 2, 3, 3, 5] => [1, 2, 3, 5] + * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ] + * => [ObjectId("550988ba0c19d57f697dc45e")] + * + * @param {Array} arr + * @return {Array} + * @private + */ + +exports.array.unique = function(arr) { + var primitives = {}; + var ids = {}; + var ret = []; + var length = arr.length; + for (var i = 0; i < length; ++i) { + if (typeof arr[i] === 'number' || typeof arr[i] === 'string') { + if (primitives[arr[i]]) { + continue; + } + ret.push(arr[i]); + primitives[arr[i]] = true; + } else if (arr[i] instanceof ObjectId) { + if (ids[arr[i].toString()]) { + continue; + } + ret.push(arr[i]); + ids[arr[i].toString()] = true; + } else { + ret.push(arr[i]); + } + } + + return ret; +}; + +/*! + * Determines if two buffers are equal. + * + * @param {Buffer} a + * @param {Object} b + */ + +exports.buffer = {}; +exports.buffer.areEqual = function(a, b) { + if (!Buffer.isBuffer(a)) { + return false; + } + if (!Buffer.isBuffer(b)) { + return false; + } + if (a.length !== b.length) { + return false; + } + for (var i = 0, len = a.length; i < len; ++i) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +}; + +exports.getFunctionName = function(fn) { + if (fn.name) { + return fn.name; + } + return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; +}; + +exports.decorate = function(destination, source) { + for (var key in source) { + destination[key] = source[key]; + } +}; + +/** + * merges to with a copy of from + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +exports.mergeClone = function(to, from) { + var keys = Object.keys(from), + i = keys.length, + key; + + while (i--) { + key = keys[i]; + if (typeof to[key] === 'undefined') { + // make sure to retain key order here because of a bug handling the $each + // operator in mongodb 2.4.4 + to[key] = exports.clone(from[key], {retainKeyOrder: 1}); + } else { + if (exports.isObject(from[key])) { + exports.mergeClone(to[key], from[key]); + } else { + // make sure to retain key order here because of a bug handling the + // $each operator in mongodb 2.4.4 + to[key] = exports.clone(from[key], {retainKeyOrder: 1}); + } + } + } +}; + +/** + * Executes a function on each element of an array (like _.each) + * + * @param {Array} arr + * @param {Function} fn + * @api private + */ + +exports.each = function(arr, fn) { + for (var i = 0; i < arr.length; ++i) { + fn(arr[i]); + } +}; diff --git a/5-2/service/node_modules/mongoose/lib/virtualtype.js b/5-2/service/node_modules/mongoose/lib/virtualtype.js new file mode 100644 index 0000000..f43cbe2 --- /dev/null +++ b/5-2/service/node_modules/mongoose/lib/virtualtype.js @@ -0,0 +1,103 @@ + +/** + * VirtualType constructor + * + * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. + * + * ####Example: + * + * var fullname = schema.virtual('fullname'); + * fullname instanceof mongoose.VirtualType // true + * + * @parma {Object} options + * @api public + */ + +function VirtualType(options, name) { + this.path = name; + this.getters = []; + this.setters = []; + this.options = options || {}; +} + +/** + * Defines a getter. + * + * ####Example: + * + * var virtual = schema.virtual('fullname'); + * virtual.get(function () { + * return this.name.first + ' ' + this.name.last; + * }); + * + * @param {Function} fn + * @return {VirtualType} this + * @api public + */ + +VirtualType.prototype.get = function(fn) { + this.getters.push(fn); + return this; +}; + +/** + * Defines a setter. + * + * ####Example: + * + * var virtual = schema.virtual('fullname'); + * virtual.set(function (v) { + * var parts = v.split(' '); + * this.name.first = parts[0]; + * this.name.last = parts[1]; + * }); + * + * @param {Function} fn + * @return {VirtualType} this + * @api public + */ + +VirtualType.prototype.set = function(fn) { + this.setters.push(fn); + return this; +}; + +/** + * Applies getters to `value` using optional `scope`. + * + * @param {Object} value + * @param {Object} scope + * @return {any} the value after applying all getters + * @api public + */ + +VirtualType.prototype.applyGetters = function(value, scope) { + var v = value; + for (var l = this.getters.length - 1; l >= 0; l--) { + v = this.getters[l].call(scope, v, this); + } + return v; +}; + +/** + * Applies setters to `value` using optional `scope`. + * + * @param {Object} value + * @param {Object} scope + * @return {any} the value after applying all setters + * @api public + */ + +VirtualType.prototype.applySetters = function(value, scope) { + var v = value; + for (var l = this.setters.length - 1; l >= 0; l--) { + v = this.setters[l].call(scope, v, this); + } + return v; +}; + +/*! + * exports + */ + +module.exports = VirtualType; diff --git a/5-2/service/node_modules/mongoose/node_modules/async/CHANGELOG.md b/5-2/service/node_modules/mongoose/node_modules/async/CHANGELOG.md new file mode 100644 index 0000000..f15e081 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/async/CHANGELOG.md @@ -0,0 +1,125 @@ +# v1.5.2 +- Allow using `"consructor"` as an argument in `memoize` (#998) +- Give a better error messsage when `auto` dependency checking fails (#994) +- Various doc updates (#936, #956, #979, #1002) + +# v1.5.1 +- Fix issue with `pause` in `queue` with concurrency enabled (#946) +- `while` and `until` now pass the final result to callback (#963) +- `auto` will properly handle concurrency when there is no callback (#966) +- `auto` will now properly stop execution when an error occurs (#988, #993) +- Various doc fixes (#971, #980) + +# v1.5.0 + +- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) (#892) +- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. (#873) +- `auto` now accepts an optional `concurrency` argument to limit the number of running tasks (#637) +- Added `queue#workersList()`, to retrieve the list of currently running tasks. (#891) +- Various code simplifications (#896, #904) +- Various doc fixes :scroll: (#890, #894, #903, #905, #912) + +# v1.4.2 + +- Ensure coverage files don't get published on npm (#879) + +# v1.4.1 + +- Add in overlooked `detectLimit` method (#866) +- Removed unnecessary files from npm releases (#861) +- Removed usage of a reserved word to prevent :boom: in older environments (#870) + +# v1.4.0 + +- `asyncify` now supports promises (#840) +- Added `Limit` versions of `filter` and `reject` (#836) +- Add `Limit` versions of `detect`, `some` and `every` (#828, #829) +- `some`, `every` and `detect` now short circuit early (#828, #829) +- Improve detection of the global object (#804), enabling use in WebWorkers +- `whilst` now called with arguments from iterator (#823) +- `during` now gets called with arguments from iterator (#824) +- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0)) + + +# v1.3.0 + +New Features: +- Added `constant` +- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. (#671, #806) +- Added `during` and `doDuring`, which are like `whilst` with an async truth test. (#800) +- `retry` now accepts an `interval` parameter to specify a delay between retries. (#793) +- `async` should work better in Web Workers due to better `root` detection (#804) +- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` (#642) +- Various internal updates (#786, #801, #802, #803) +- Various doc fixes (#790, #794) + +Bug Fixes: +- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. (#740, #744, #783) + + +# v1.2.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. (#782) + + +# v1.2.0 + +New Features: + +- Added `timesLimit` (#743) +- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. (#747, #772) + +Bug Fixes: + +- Fixed a regression in `each` and family with empty arrays that have additional properties. (#775, #777) + + +# v1.1.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. (#782) + + +# v1.1.0 + +New Features: + +- `cargo` now supports all of the same methods and event callbacks as `queue`. +- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. (#769) +- Optimized `map`, `eachOf`, and `waterfall` families of functions +- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array (#667). +- The callback is now optional for the composed results of `compose` and `seq`. (#618) +- Reduced file size by 4kb, (minified version by 1kb) +- Added code coverage through `nyc` and `coveralls` (#768) + +Bug Fixes: + +- `forever` will no longer stack overflow with a synchronous iterator (#622) +- `eachLimit` and other limit functions will stop iterating once an error occurs (#754) +- Always pass `null` in callbacks when there is no error (#439) +- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue (#668) +- `each` and family will properly handle an empty array (#578) +- `eachSeries` and family will finish if the underlying array is modified during execution (#557) +- `queue` will throw if a non-function is passed to `q.push()` (#593) +- Doc fixes (#629, #766) + + +# v1.0.0 + +No known breaking changes, we are simply complying with semver from here on out. + +Changes: + +- Start using a changelog! +- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) (#168 #704 #321) +- Detect deadlocks in `auto` (#663) +- Better support for require.js (#527) +- Throw if queue created with concurrency `0` (#714) +- Fix unneeded iteration in `queue.resume()` (#758) +- Guard against timer mocking overriding `setImmediate` (#609 #611) +- Miscellaneous doc fixes (#542 #596 #615 #628 #631 #690 #729) +- Use single noop function internally (#546) +- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/5-2/service/node_modules/mongoose/node_modules/async/LICENSE b/5-2/service/node_modules/mongoose/node_modules/async/LICENSE new file mode 100644 index 0000000..8f29698 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-2014 Caolan McMahon + +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/5-2/service/node_modules/mongoose/node_modules/async/README.md b/5-2/service/node_modules/mongoose/node_modules/async/README.md new file mode 100644 index 0000000..316c405 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/async/README.md @@ -0,0 +1,1877 @@ +# Async.js + +[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async) +[![NPM version](http://img.shields.io/npm/v/async.svg)](https://www.npmjs.org/package/async) +[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master) +[![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + + +Async is a utility module which provides straight-forward, powerful functions +for working with asynchronous JavaScript. Although originally designed for +use with [Node.js](http://nodejs.org) and installable via `npm install async`, +it can also be used directly in the browser. + +Async is also installable via: + +- [bower](http://bower.io/): `bower install async` +- [component](https://github.com/component/component): `component install + caolan/async` +- [jam](http://jamjs.org/): `jam install async` +- [spm](http://spmjs.io/): `spm install async` + +Async provides around 20 functions that include the usual 'functional' +suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns +for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these +functions assume you follow the Node.js convention of providing a single +callback as the last argument of your `async` function. + + +## Quick Examples + +```javascript +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); + +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); + +async.parallel([ + function(){ ... }, + function(){ ... } +], callback); + +async.series([ + function(){ ... }, + function(){ ... } +]); +``` + +There are many more functions available so take a look at the docs below for a +full list. This module aims to be comprehensive, so if you feel anything is +missing please create a GitHub issue for it. + +## Common Pitfalls [(StackOverflow)](http://stackoverflow.com/questions/tagged/async.js) +### Synchronous iteration functions + +If you get an error like `RangeError: Maximum call stack size exceeded.` or other stack overflow issues when using async, you are likely using a synchronous iterator. By *synchronous* we mean a function that calls its callback on the same tick in the javascript event loop, without doing any I/O or using any timers. Calling many callbacks iteratively will quickly overflow the stack. If you run into this issue, just defer your callback with `async.setImmediate` to start a new call stack on the next tick of the event loop. + +This can also arise by accident if you callback early in certain cases: + +```js +async.eachSeries(hugeArray, function iterator(item, callback) { + if (inCache(item)) { + callback(null, cache[item]); // if many items are cached, you'll overflow + } else { + doSomeIO(item, callback); + } +}, function done() { + //... +}); +``` + +Just change it to: + +```js +async.eachSeries(hugeArray, function iterator(item, callback) { + if (inCache(item)) { + async.setImmediate(function () { + callback(null, cache[item]); + }); + } else { + doSomeIO(item, callback); + //... +``` + +Async guards against synchronous functions in some, but not all, cases. If you are still running into stack overflows, you can defer as suggested above, or wrap functions with [`async.ensureAsync`](#ensureAsync) Functions that are asynchronous by their nature do not have this problem and don't need the extra callback deferral. + +If JavaScript's event loop is still a bit nebulous, check out [this article](http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/) or [this talk](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html) for more detailed information about how it works. + + +### Multiple callbacks + +Make sure to always `return` when calling a callback early, otherwise you will cause multiple callbacks and unpredictable behavior in many cases. + +```js +async.waterfall([ + function (callback) { + getSomething(options, function (err, result) { + if (err) { + callback(new Error("failed getting something:" + err.message)); + // we should return here + } + // since we did not return, this callback still will be called and + // `processData` will be called twice + callback(null, result); + }); + }, + processData +], done) +``` + +It is always good practice to `return callback(err, result)` whenever a callback call is not the last statement of a function. + + +### Binding a context to an iterator + +This section is really about `bind`, not about `async`. If you are wondering how to +make `async` execute your iterators in a given context, or are confused as to why +a method of another library isn't working as an iterator, study this example: + +```js +// Here is a simple object with an (unnecessarily roundabout) squaring method +var AsyncSquaringLibrary = { + squareExponent: 2, + square: function(number, callback){ + var result = Math.pow(number, this.squareExponent); + setTimeout(function(){ + callback(null, result); + }, 200); + } +}; + +async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){ + // result is [NaN, NaN, NaN] + // This fails because the `this.squareExponent` expression in the square + // function is not evaluated in the context of AsyncSquaringLibrary, and is + // therefore undefined. +}); + +async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){ + // result is [1, 4, 9] + // With the help of bind we can attach a context to the iterator before + // passing it to async. Now the square function will be executed in its + // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent` + // will be as expected. +}); +``` + +## Download + +The source is available for download from +[GitHub](https://github.com/caolan/async/blob/master/lib/async.js). +Alternatively, you can install using Node Package Manager (`npm`): + + npm install async + +As well as using Bower: + + bower install async + +__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed + +## In the Browser + +So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. + +Usage: + +```html + + +``` + +## Documentation + +Some functions are also available in the following forms: +* `Series` - the same as `` but runs only a single async operation at a time +* `Limit` - the same as `` but runs a maximum of `limit` async operations at a time + +### Collections + +* [`each`](#each), `eachSeries`, `eachLimit` +* [`forEachOf`](#forEachOf), `forEachOfSeries`, `forEachOfLimit` +* [`map`](#map), `mapSeries`, `mapLimit` +* [`filter`](#filter), `filterSeries`, `filterLimit` +* [`reject`](#reject), `rejectSeries`, `rejectLimit` +* [`reduce`](#reduce), [`reduceRight`](#reduceRight) +* [`detect`](#detect), `detectSeries`, `detectLimit` +* [`sortBy`](#sortBy) +* [`some`](#some), `someLimit` +* [`every`](#every), `everyLimit` +* [`concat`](#concat), `concatSeries` + +### Control Flow + +* [`series`](#seriestasks-callback) +* [`parallel`](#parallel), `parallelLimit` +* [`whilst`](#whilst), [`doWhilst`](#doWhilst) +* [`until`](#until), [`doUntil`](#doUntil) +* [`during`](#during), [`doDuring`](#doDuring) +* [`forever`](#forever) +* [`waterfall`](#waterfall) +* [`compose`](#compose) +* [`seq`](#seq) +* [`applyEach`](#applyEach), `applyEachSeries` +* [`queue`](#queue), [`priorityQueue`](#priorityQueue) +* [`cargo`](#cargo) +* [`auto`](#auto) +* [`retry`](#retry) +* [`iterator`](#iterator) +* [`times`](#times), `timesSeries`, `timesLimit` + +### Utils + +* [`apply`](#apply) +* [`nextTick`](#nextTick) +* [`memoize`](#memoize) +* [`unmemoize`](#unmemoize) +* [`ensureAsync`](#ensureAsync) +* [`constant`](#constant) +* [`asyncify`](#asyncify) +* [`wrapSync`](#wrapSync) +* [`log`](#log) +* [`dir`](#dir) +* [`noConflict`](#noConflict) + +## Collections + + + +### each(arr, iterator, [callback]) + +Applies the function `iterator` to each item in `arr`, in parallel. +The `iterator` is called with an item from the list, and a callback for when it +has finished. If the `iterator` passes an error to its `callback`, the main +`callback` (for the `each` function) is immediately called with the error. + +Note, that since this function applies `iterator` to each item in parallel, +there is no guarantee that the iterator functions will complete in order. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the `callback` should be run without + arguments or with an explicit `null` argument. The array index is not passed + to the iterator. If you need the index, use [`forEachOf`](#forEachOf). +* `callback(err)` - *Optional* A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Examples__ + + +```js +// assuming openFiles is an array of file names and saveFile is a function +// to save the modified contents of that file: + +async.each(openFiles, saveFile, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +```js +// assuming openFiles is an array of file names + +async.each(openFiles, function(file, callback) { + + // Perform operation on file here. + console.log('Processing file ' + file); + + if( file.length > 32 ) { + console.log('This file name is too long'); + callback('File name too long'); + } else { + // Do work to process file here + console.log('File processed'); + callback(); + } +}, function(err){ + // if any of the file processing produced an error, err would equal that error + if( err ) { + // One of the iterations produced an error. + // All processing will now stop. + console.log('A file failed to process'); + } else { + console.log('All files have been processed successfully'); + } +}); +``` + +__Related__ + +* eachSeries(arr, iterator, [callback]) +* eachLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + + + +### forEachOf(obj, iterator, [callback]) + +Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator. + +__Arguments__ + +* `obj` - An object or array to iterate over. +* `iterator(item, key, callback)` - A function to apply to each item in `obj`. +The `key` is the item's key, or index in the case of an array. The iterator is +passed a `callback(err)` which must be called once it has completed. If no +error has occurred, the callback should be run without arguments or with an +explicit `null` argument. +* `callback(err)` - *Optional* A callback which is called when all `iterator` functions have finished, or an error occurs. + +__Example__ + +```js +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, function (value, key, callback) { + fs.readFile(__dirname + value, "utf8", function (err, data) { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }) +}, function (err) { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}) +``` + +__Related__ + +* forEachOfSeries(obj, iterator, [callback]) +* forEachOfLimit(obj, limit, iterator, [callback]) + +--------------------------------------- + + +### map(arr, iterator, [callback]) + +Produces a new array of values by mapping each value in `arr` through +the `iterator` function. The `iterator` is called with an item from `arr` and a +callback for when it has finished processing. Each of these callback takes 2 arguments: +an `error`, and the transformed item from `arr`. If `iterator` passes an error to its +callback, the main `callback` (for the `map` function) is immediately called with the error. + +Note, that since this function applies the `iterator` to each item in parallel, +there is no guarantee that the `iterator` functions will complete in order. +However, the results array will be in the same order as the original `arr`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - *Optional* A callback which is called when all `iterator` + functions have finished, or an error occurs. Results is an array of the + transformed items from the `arr`. + +__Example__ + +```js +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +__Related__ +* mapSeries(arr, iterator, [callback]) +* mapLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + + +### filter(arr, iterator, [callback]) + +__Alias:__ `select` + +Returns a new array of all the values in `arr` which pass an async truth test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. This operation is +performed in parallel, but the results array will be in the same order as the +original. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The `iterator` is passed a `callback(truthValue)`, which must be called with a + boolean argument once it has completed. +* `callback(results)` - *Optional* A callback which is called after all the `iterator` + functions have finished. + +__Example__ + +```js +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); +``` + +__Related__ + +* filterSeries(arr, iterator, [callback]) +* filterLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + +### reject(arr, iterator, [callback]) + +The opposite of [`filter`](#filter). Removes values that pass an `async` truth test. + +__Related__ + +* rejectSeries(arr, iterator, [callback]) +* rejectLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + +### reduce(arr, memo, iterator, [callback]) + +__Aliases:__ `inject`, `foldl` + +Reduces `arr` into a single value using an async `iterator` to return +each successive step. `memo` is the initial state of the reduction. +This function only operates in series. + +For performance reasons, it may make sense to split a call to this function into +a parallel map, and then use the normal `Array.prototype.reduce` on the results. +This function is for situations where each step in the reduction needs to be async; +if you can get the data before reducing it, then it's probably a good idea to do so. + +__Arguments__ + +* `arr` - An array to iterate over. +* `memo` - The initial state of the reduction. +* `iterator(memo, item, callback)` - A function applied to each item in the + array to produce the next step in the reduction. The `iterator` is passed a + `callback(err, reduction)` which accepts an optional error as its first + argument, and the state of the reduction as the second. If an error is + passed to the callback, the reduction is stopped and the main `callback` is + immediately called with the error. +* `callback(err, result)` - *Optional* A callback which is called after all the `iterator` + functions have finished. Result is the reduced value. + +__Example__ + +```js +async.reduce([1,2,3], 0, function(memo, item, callback){ + // pointless async: + process.nextTick(function(){ + callback(null, memo + item) + }); +}, function(err, result){ + // result is now equal to the last value of memo, which is 6 +}); +``` + +--------------------------------------- + + +### reduceRight(arr, memo, iterator, [callback]) + +__Alias:__ `foldr` + +Same as [`reduce`](#reduce), only operates on `arr` in reverse order. + + +--------------------------------------- + + +### detect(arr, iterator, [callback]) + +Returns the first value in `arr` that passes an async truth test. The +`iterator` is applied in parallel, meaning the first iterator to return `true` will +fire the detect `callback` with that result. That means the result might not be +the first item in the original `arr` (in terms of order) that passes the test. + +If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries). + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The iterator is passed a `callback(truthValue)` which must be called with a + boolean argument once it has completed. **Note: this callback does not take an error as its first argument.** +* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns + `true`, or after all the `iterator` functions have finished. Result will be + the first item in the array that passes the truth test (iterator) or the + value `undefined` if none passed. **Note: this callback does not take an error as its first argument.** + +__Example__ + +```js +async.detect(['file1','file2','file3'], fs.exists, function(result){ + // result now equals the first file in the list that exists +}); +``` + +__Related__ + +* detectSeries(arr, iterator, [callback]) +* detectLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + +### sortBy(arr, iterator, [callback]) + +Sorts a list by the results of running each `arr` value through an async `iterator`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, sortValue)` which must be called once it + has completed with an error (which can be `null`) and a value to use as the sort + criteria. +* `callback(err, results)` - *Optional* A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is the items from + the original `arr` sorted by the values returned by the `iterator` calls. + +__Example__ + +```js +async.sortBy(['file1','file2','file3'], function(file, callback){ + fs.stat(file, function(err, stats){ + callback(err, stats.mtime); + }); +}, function(err, results){ + // results is now the original array of files sorted by + // modified date +}); +``` + +__Sort Order__ + +By modifying the callback parameter the sorting order can be influenced: + +```js +//ascending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x); +}, function(err,result){ + //result callback +} ); + +//descending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x*-1); //<- x*-1 instead of x, turns the order around +}, function(err,result){ + //result callback +} ); +``` + +--------------------------------------- + + +### some(arr, iterator, [callback]) + +__Alias:__ `any` + +Returns `true` if at least one element in the `arr` satisfies an async test. +_The callback for each iterator call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. Once any iterator +call returns `true`, the main `callback` is immediately called. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a `callback(truthValue)`` which must be + called with a boolean argument once it has completed. +* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns + `true`, or after all the iterator functions have finished. Result will be + either `true` or `false` depending on the values of the async tests. + + **Note: the callbacks do not take an error as their first argument.** +__Example__ + +```js +async.some(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then at least one of the files exists +}); +``` + +__Related__ + +* someLimit(arr, limit, iterator, callback) + +--------------------------------------- + + +### every(arr, iterator, [callback]) + +__Alias:__ `all` + +Returns `true` if every element in `arr` satisfies an async test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a `callback(truthValue)` which must be + called with a boolean argument once it has completed. +* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns + `false`, or after all the iterator functions have finished. Result will be + either `true` or `false` depending on the values of the async tests. + + **Note: the callbacks do not take an error as their first argument.** + +__Example__ + +```js +async.every(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then every file exists +}); +``` + +__Related__ + +* everyLimit(arr, limit, iterator, callback) + +--------------------------------------- + + +### concat(arr, iterator, [callback]) + +Applies `iterator` to each item in `arr`, concatenating the results. Returns the +concatenated list. The `iterator`s are called in parallel, and the results are +concatenated as they return. There is no guarantee that the results array will +be returned in the original order of `arr` passed to the `iterator` function. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, results)` which must be called once it + has completed with an error (which can be `null`) and an array of results. +* `callback(err, results)` - *Optional* A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is an array containing + the concatenated results of the `iterator` function. + +__Example__ + +```js +async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ + // files is now a list of filenames that exist in the 3 directories +}); +``` + +__Related__ + +* concatSeries(arr, iterator, [callback]) + + +## Control Flow + + +### series(tasks, [callback]) + +Run the functions in the `tasks` array in series, each one running once the previous +function has completed. If any functions in the series pass an error to its +callback, no more functions are run, and `callback` is immediately called with the value of the error. +Otherwise, `callback` receives an array of results when `tasks` have completed. + +It is also possible to use an object instead of an array. Each property will be +run as a function, and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`series`](#series). + +**Note** that while many implementations preserve the order of object properties, the +[ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) +explicitly states that + +> The mechanics and order of enumerating the properties is not specified. + +So if you rely on the order in which your series of functions are executed, and want +this to work on all platforms, consider using an array. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +__Example__ + +```js +async.series([ + function(callback){ + // do some stuff ... + callback(null, 'one'); + }, + function(callback){ + // do some more stuff ... + callback(null, 'two'); + } +], +// optional callback +function(err, results){ + // results is now equal to ['one', 'two'] +}); + + +// an example using an object instead of an array +async.series({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equal to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + + +### parallel(tasks, [callback]) + +Run the `tasks` array of functions in parallel, without waiting until the previous +function has completed. If any of the functions pass an error to its +callback, the main `callback` is immediately called with the value of the error. +Once the `tasks` have completed, the results are passed to the final `callback` as an +array. + +**Note:** `parallel` is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded. + +It is also possible to use an object instead of an array. Each property will be +run as a function and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`parallel`](#parallel). + + +__Arguments__ + +* `tasks` - An array or object containing functions to run. Each function is passed + a `callback(err, result)` which it must call on completion with an error `err` + (which can be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed successfully. This function gets a results array (or object) containing all + the result arguments passed to the task callbacks. + +__Example__ + +```js +async.parallel([ + function(callback){ + setTimeout(function(){ + callback(null, 'one'); + }, 200); + }, + function(callback){ + setTimeout(function(){ + callback(null, 'two'); + }, 100); + } +], +// optional callback +function(err, results){ + // the results array will equal ['one','two'] even though + // the second function had a shorter timeout. +}); + + +// an example using an object instead of an array +async.parallel({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equals to: {one: 1, two: 2} +}); +``` + +__Related__ + +* parallelLimit(tasks, limit, [callback]) + +--------------------------------------- + + +### whilst(test, fn, callback) + +Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +__Arguments__ + +* `test()` - synchronous truth test to perform before each execution of `fn`. +* `fn(callback)` - A function which is called each time `test` passes. The function is + passed a `callback(err)`, which must be called once it has completed with an + optional `err` argument. +* `callback(err, [results])` - A callback which is called after the test + function has failed and repeated execution of `fn` has stopped. `callback` + will be passed an error and any arguments passed to the final `fn`'s callback. + +__Example__ + +```js +var count = 0; + +async.whilst( + function () { return count < 5; }, + function (callback) { + count++; + setTimeout(function () { + callback(null, count); + }, 1000); + }, + function (err, n) { + // 5 seconds have passed, n = 5 + } +); +``` + +--------------------------------------- + + +### doWhilst(fn, test, callback) + +The post-check version of [`whilst`](#whilst). To reflect the difference in +the order of operations, the arguments `test` and `fn` are switched. + +`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + +--------------------------------------- + + +### until(test, fn, callback) + +Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped, +or an error occurs. `callback` will be passed an error and any arguments passed +to the final `fn`'s callback. + +The inverse of [`whilst`](#whilst). + +--------------------------------------- + + +### doUntil(fn, test, callback) + +Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`. + +--------------------------------------- + + +### during(test, fn, callback) + +Like [`whilst`](#whilst), except the `test` is an asynchronous function that is passed a callback in the form of `function (err, truth)`. If error is passed to `test` or `fn`, the main callback is immediately called with the value of the error. + +__Example__ + +```js +var count = 0; + +async.during( + function (callback) { + return callback(null, count < 5); + }, + function (callback) { + count++; + setTimeout(callback, 1000); + }, + function (err) { + // 5 seconds have passed + } +); +``` + +--------------------------------------- + + +### doDuring(fn, test, callback) + +The post-check version of [`during`](#during). To reflect the difference in +the order of operations, the arguments `test` and `fn` are switched. + +Also a version of [`doWhilst`](#doWhilst) with asynchronous `test` function. + +--------------------------------------- + + +### forever(fn, [errback]) + +Calls the asynchronous function `fn` with a callback parameter that allows it to +call itself again, in series, indefinitely. + +If an error is passed to the callback then `errback` is called with the +error, and execution stops, otherwise it will never be called. + +```js +async.forever( + function(next) { + // next is suitable for passing to things that need a callback(err [, whatever]); + // it will result in this function being called again. + }, + function(err) { + // if next is called with a value in its first parameter, it will appear + // in here as 'err', and execution will stop. + } +); +``` + +--------------------------------------- + + +### waterfall(tasks, [callback]) + +Runs the `tasks` array of functions in series, each passing their results to the next in +the array. However, if any of the `tasks` pass an error to their own callback, the +next function is not executed, and the main `callback` is immediately called with +the error. + +__Arguments__ + +* `tasks` - An array of functions to run, each function is passed a + `callback(err, result1, result2, ...)` it must call on completion. The first + argument is an error (which can be `null`) and any further arguments will be + passed as arguments in order to the next task. +* `callback(err, [results])` - An optional callback to run once all the functions + have completed. This will be passed the results of the last task's callback. + + + +__Example__ + +```js +async.waterfall([ + function(callback) { + callback(null, 'one', 'two'); + }, + function(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); + }, + function(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); + } +], function (err, result) { + // result now equals 'done' +}); +``` +Or, with named functions: + +```js +async.waterfall([ + myFirstFunction, + mySecondFunction, + myLastFunction, +], function (err, result) { + // result now equals 'done' +}); +function myFirstFunction(callback) { + callback(null, 'one', 'two'); +} +function mySecondFunction(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); +} +function myLastFunction(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); +} +``` + +Or, if you need to pass any argument to the first function: + +```js +async.waterfall([ + async.apply(myFirstFunction, 'zero'), + mySecondFunction, + myLastFunction, +], function (err, result) { + // result now equals 'done' +}); +function myFirstFunction(arg1, callback) { + // arg1 now equals 'zero' + callback(null, 'one', 'two'); +} +function mySecondFunction(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); +} +function myLastFunction(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); +} +``` + +--------------------------------------- + +### compose(fn1, fn2...) + +Creates a function which is a composition of the passed asynchronous +functions. Each function consumes the return value of the function that +follows. Composing functions `f()`, `g()`, and `h()` would produce the result of +`f(g(h()))`, only this version uses callbacks to obtain the return values. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* `functions...` - the asynchronous functions to compose + + +__Example__ + +```js +function add1(n, callback) { + setTimeout(function () { + callback(null, n + 1); + }, 10); +} + +function mul3(n, callback) { + setTimeout(function () { + callback(null, n * 3); + }, 10); +} + +var add1mul3 = async.compose(mul3, add1); + +add1mul3(4, function (err, result) { + // result now equals 15 +}); +``` + +--------------------------------------- + +### seq(fn1, fn2...) + +Version of the compose function that is more natural to read. +Each function consumes the return value of the previous function. +It is the equivalent of [`compose`](#compose) with the arguments reversed. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* `functions...` - the asynchronous functions to compose + + +__Example__ + +```js +// Requires lodash (or underscore), express3 and dresende's orm2. +// Part of an app, that fetches cats of the logged user. +// This example uses `seq` function to avoid overnesting and error +// handling clutter. +app.get('/cats', function(request, response) { + var User = request.models.User; + async.seq( + _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + function(user, fn) { + user.getCats(fn); // 'getCats' has signature (callback(err, data)) + } + )(req.session.user_id, function (err, cats) { + if (err) { + console.error(err); + response.json({ status: 'error', message: err.message }); + } else { + response.json({ status: 'ok', message: 'Cats found', data: cats }); + } + }); +}); +``` + +--------------------------------------- + +### applyEach(fns, args..., callback) + +Applies the provided arguments to each function in the array, calling +`callback` after all functions have completed. If you only provide the first +argument, then it will return a function which lets you pass in the +arguments as if it were a single function call. + +__Arguments__ + +* `fns` - the asynchronous functions to all call with the same arguments +* `args...` - any number of separate arguments to pass to the function +* `callback` - the final argument should be the callback, called when all + functions have completed processing + + +__Example__ + +```js +async.applyEach([enableSearch, updateSchema], 'bucket', callback); + +// partial application example: +async.each( + buckets, + async.applyEach([enableSearch, updateSchema]), + callback +); +``` + +__Related__ + +* applyEachSeries(tasks, args..., [callback]) + +--------------------------------------- + + +### queue(worker, [concurrency]) + +Creates a `queue` object with the specified `concurrency`. Tasks added to the +`queue` are processed in parallel (up to the `concurrency` limit). If all +`worker`s are in progress, the task is queued until one becomes available. +Once a `worker` completes a `task`, that `task`'s callback is called. + +__Arguments__ + +* `worker(task, callback)` - An asynchronous function for processing a queued + task, which must call its `callback(err)` argument when finished, with an + optional `error` as an argument. If you want to handle errors from an individual task, pass a callback to `q.push()`. +* `concurrency` - An `integer` for determining how many `worker` functions should be + run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown. + +__Queue objects__ + +The `queue` object returned by this function has the following properties and +methods: + +* `length()` - a function returning the number of items waiting to be processed. +* `started` - a function returning whether or not any items have been pushed and processed by the queue +* `running()` - a function returning the number of items currently being processed. +* `workersList()` - a function returning the array of items currently being processed. +* `idle()` - a function returning false if there are items waiting or being processed, or true if not. +* `concurrency` - an integer for determining how many `worker` functions should be + run in parallel. This property can be changed after a `queue` is created to + alter the concurrency on-the-fly. +* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once + the `worker` has finished processing the task. Instead of a single task, a `tasks` array + can be submitted. The respective callback is used for every task in the list. +* `unshift(task, [callback])` - add a new task to the front of the `queue`. +* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, + and further tasks will be queued. +* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`. +* `paused` - a boolean for determining whether the queue is in a paused state +* `pause()` - a function that pauses the processing of tasks until `resume()` is called. +* `resume()` - a function that resumes the processing of queued tasks when the queue is paused. +* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle. + +__Example__ + +```js +// create a queue object with concurrency 2 + +var q = async.queue(function (task, callback) { + console.log('hello ' + task.name); + callback(); +}, 2); + + +// assign a callback +q.drain = function() { + console.log('all items have been processed'); +} + +// add some items to the queue + +q.push({name: 'foo'}, function (err) { + console.log('finished processing foo'); +}); +q.push({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); + +// add some items to the queue (batch-wise) + +q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { + console.log('finished processing item'); +}); + +// add some items to the front of the queue + +q.unshift({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); +``` + + +--------------------------------------- + + +### priorityQueue(worker, concurrency) + +The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects: + +* `push(task, priority, [callback])` - `priority` should be a number. If an array of + `tasks` is given, all tasks will be assigned the same priority. +* The `unshift` method was removed. + +--------------------------------------- + + +### cargo(worker, [payload]) + +Creates a `cargo` object with the specified payload. Tasks added to the +cargo will be processed altogether (up to the `payload` limit). If the +`worker` is in progress, the task is queued until it becomes available. Once +the `worker` has completed some tasks, each callback of those tasks is called. +Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work. + +While [queue](#queue) passes only one task to one of a group of workers +at a time, cargo passes an array of tasks to a single worker, repeating +when the worker is finished. + +__Arguments__ + +* `worker(tasks, callback)` - An asynchronous function for processing an array of + queued tasks, which must call its `callback(err)` argument when finished, with + an optional `err` argument. +* `payload` - An optional `integer` for determining how many tasks should be + processed per round; if omitted, the default is unlimited. + +__Cargo objects__ + +The `cargo` object returned by this function has the following properties and +methods: + +* `length()` - A function returning the number of items waiting to be processed. +* `payload` - An `integer` for determining how many tasks should be + process per round. This property can be changed after a `cargo` is created to + alter the payload on-the-fly. +* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called + once the `worker` has finished processing the task. Instead of a single task, an array of `tasks` + can be submitted. The respective callback is used for every task in the list. +* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued. +* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`. +* `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event calbacks as [`queue`](#queue) + +__Example__ + +```js +// create a cargo object with payload 2 + +var cargo = async.cargo(function (tasks, callback) { + for(var i=0; i +### auto(tasks, [concurrency], [callback]) + +Determines the best order for running the functions in `tasks`, based on their requirements. Each function can optionally depend on other functions being completed first, and each function is run as soon as its requirements are satisfied. + +If any of the functions pass an error to their callback, the `auto` sequence will stop. Further tasks will not execute (so any other functions depending on it will not run), and the main `callback` is immediately called with the error. Functions also receive an object containing the results of functions which have completed so far. + +Note, all functions are called with a `results` object as a second argument, +so it is unsafe to pass functions in the `tasks` object which cannot handle the +extra argument. + +For example, this snippet of code: + +```js +async.auto({ + readData: async.apply(fs.readFile, 'data.txt', 'utf-8') +}, callback); +``` + +will have the effect of calling `readFile` with the results object as the last +argument, which will fail: + +```js +fs.readFile('data.txt', 'utf-8', cb, {}); +``` + +Instead, wrap the call to `readFile` in a function which does not forward the +`results` object: + +```js +async.auto({ + readData: function(cb, results){ + fs.readFile('data.txt', 'utf-8', cb); + } +}, callback); +``` + +__Arguments__ + +* `tasks` - An object. Each of its properties is either a function or an array of + requirements, with the function itself the last item in the array. The object's key + of a property serves as the name of the task defined by that property, + i.e. can be used when specifying requirements for other tasks. + The function receives two arguments: (1) a `callback(err, result)` which must be + called when finished, passing an `error` (which can be `null`) and the result of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions. +* `concurrency` - An optional `integer` for determining the maximum number of tasks that can be run in parallel. By default, as many as possible. +* `callback(err, results)` - An optional callback which is called when all the + tasks have been completed. It receives the `err` argument if any `tasks` + pass an error to their callback. Results are always returned; however, if + an error occurs, no further `tasks` will be performed, and the results + object will only contain partial results. + + +__Example__ + +```js +async.auto({ + get_data: function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + make_folder: function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + }, + write_file: ['get_data', 'make_folder', function(callback, results){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + callback(null, 'filename'); + }], + email_link: ['write_file', function(callback, results){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + // results.write_file contains the filename returned by write_file. + callback(null, {'file':results.write_file, 'email':'user@example.com'}); + }] +}, function(err, results) { + console.log('err = ', err); + console.log('results = ', results); +}); +``` + +This is a fairly trivial example, but to do this using the basic parallel and +series functions would look like this: + +```js +async.parallel([ + function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + } +], +function(err, results){ + async.series([ + function(callback){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + results.push('filename'); + callback(null); + }, + function(callback){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + callback(null, {'file':results.pop(), 'email':'user@example.com'}); + } + ]); +}); +``` + +For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding +new tasks much easier (and the code more readable). + + +--------------------------------------- + + +### retry([opts = {times: 5, interval: 0}| 5], task, [callback]) + +Attempts to get a successful response from `task` no more than `times` times before +returning an error. If the task is successful, the `callback` will be passed the result +of the successful task. If all attempts fail, the callback will be passed the error and +result (if any) of the final attempt. + +__Arguments__ + +* `opts` - Can be either an object with `times` and `interval` or a number. + * `times` - The number of attempts to make before giving up. The default is `5`. + * `interval` - The time to wait between retries, in milliseconds. The default is `0`. + * If `opts` is a number, the number specifies the number of times to retry, with the default interval of `0`. +* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)` + which must be called when finished, passing `err` (which can be `null`) and the `result` of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions (if nested inside another control flow). +* `callback(err, results)` - An optional callback which is called when the + task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`. + +The [`retry`](#retry) function can be used as a stand-alone control flow by passing a callback, as shown below: + +```js +// try calling apiMethod 3 times +async.retry(3, apiMethod, function(err, result) { + // do something with the result +}); +``` + +```js +// try calling apiMethod 3 times, waiting 200 ms between each retry +async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + // do something with the result +}); +``` + +```js +// try calling apiMethod the default 5 times no delay between each retry +async.retry(apiMethod, function(err, result) { + // do something with the result +}); +``` + +It can also be embedded within other control flow functions to retry individual methods +that are not as reliable, like this: + +```js +async.auto({ + users: api.getUsers.bind(api), + payments: async.retry(3, api.getPayments.bind(api)) +}, function(err, results) { + // do something with the results +}); +``` + + +--------------------------------------- + + +### iterator(tasks) + +Creates an iterator function which calls the next function in the `tasks` array, +returning a continuation to call the next one after that. It's also possible to +“peek” at the next iterator with `iterator.next()`. + +This function is used internally by the `async` module, but can be useful when +you want to manually control the flow of functions in series. + +__Arguments__ + +* `tasks` - An array of functions to run. + +__Example__ + +```js +var iterator = async.iterator([ + function(){ sys.p('one'); }, + function(){ sys.p('two'); }, + function(){ sys.p('three'); } +]); + +node> var iterator2 = iterator(); +'one' +node> var iterator3 = iterator2(); +'two' +node> iterator3(); +'three' +node> var nextfn = iterator2.next(); +node> nextfn(); +'three' +``` + +--------------------------------------- + + +### apply(function, arguments..) + +Creates a continuation function with some arguments already applied. + +Useful as a shorthand when combined with other control flow functions. Any arguments +passed to the returned function are added to the arguments originally passed +to apply. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to automatically apply when the + continuation is called. + +__Example__ + +```js +// using apply + +async.parallel([ + async.apply(fs.writeFile, 'testfile1', 'test1'), + async.apply(fs.writeFile, 'testfile2', 'test2'), +]); + + +// the same process without using apply + +async.parallel([ + function(callback){ + fs.writeFile('testfile1', 'test1', callback); + }, + function(callback){ + fs.writeFile('testfile2', 'test2', callback); + } +]); +``` + +It's possible to pass any number of additional arguments when calling the +continuation: + +```js +node> var fn = async.apply(sys.puts, 'one'); +node> fn('two', 'three'); +one +two +three +``` + +--------------------------------------- + + +### nextTick(callback), setImmediate(callback) + +Calls `callback` on a later loop around the event loop. In Node.js this just +calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)` +if available, otherwise `setTimeout(callback, 0)`, which means other higher priority +events may precede the execution of `callback`. + +This is used internally for browser-compatibility purposes. + +__Arguments__ + +* `callback` - The function to call on a later loop around the event loop. + +__Example__ + +```js +var call_order = []; +async.nextTick(function(){ + call_order.push('two'); + // call_order now equals ['one','two'] +}); +call_order.push('one') +``` + + +### times(n, iterator, [callback]) + +Calls the `iterator` function `n` times, and accumulates results in the same manner +you would use with [`map`](#map). + +__Arguments__ + +* `n` - The number of times to run the function. +* `iterator` - The function to call `n` times. +* `callback` - see [`map`](#map) + +__Example__ + +```js +// Pretend this is some complicated async factory +var createUser = function(id, callback) { + callback(null, { + id: 'user' + id + }) +} +// generate 5 users +async.times(5, function(n, next){ + createUser(n, function(err, user) { + next(err, user) + }) +}, function(err, users) { + // we should now have 5 users +}); +``` + +__Related__ + +* timesSeries(n, iterator, [callback]) +* timesLimit(n, limit, iterator, [callback]) + + +## Utils + + +### memoize(fn, [hasher]) + +Caches the results of an `async` function. When creating a hash to store function +results against, the callback is omitted from the hash and an optional hash +function can be used. + +If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function. + +The cache of results is exposed as the `memo` property of the function returned +by `memoize`. + +__Arguments__ + +* `fn` - The function to proxy and cache results from. +* `hasher` - An optional function for generating a custom hash for storing + results. It has all the arguments applied to it apart from the callback, and + must be synchronous. + +__Example__ + +```js +var slow_fn = function (name, callback) { + // do something + callback(null, result); +}; +var fn = async.memoize(slow_fn); + +// fn can now be used as if it were slow_fn +fn('some name', function () { + // callback +}); +``` + + +### unmemoize(fn) + +Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized +form. Handy for testing. + +__Arguments__ + +* `fn` - the memoized function + +--------------------------------------- + + +### ensureAsync(fn) + +Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained. + +__Arguments__ + +* `fn` - an async function, one that expects a node-style callback as its last argument + +Returns a wrapped function with the exact same call signature as the function passed in. + +__Example__ + +```js +function sometimesAsync(arg, callback) { + if (cache[arg]) { + return callback(null, cache[arg]); // this would be synchronous!! + } else { + doSomeIO(arg, callback); // this IO would be asynchronous + } +} + +// this has a risk of stack overflows if many results are cached in a row +async.mapSeries(args, sometimesAsync, done); + +// this will defer sometimesAsync's callback if necessary, +// preventing stack overflows +async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + +``` + +--------------------------------------- + + +### constant(values...) + +Returns a function that when called, calls-back with the values provided. Useful as the first function in a `waterfall`, or for plugging values in to `auto`. + +__Example__ + +```js +async.waterfall([ + async.constant(42), + function (value, next) { + // value === 42 + }, + //... +], callback); + +async.waterfall([ + async.constant(filename, "utf8"), + fs.readFile, + function (fileData, next) { + //... + } + //... +], callback); + +async.auto({ + hostname: async.constant("https://server.net/"), + port: findFreePort, + launchServer: ["hostname", "port", function (cb, options) { + startServer(options, cb); + }], + //... +}, callback); + +``` + +--------------------------------------- + + + +### asyncify(func) + +__Alias:__ `wrapSync` + +Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback. + +__Example__ + +```js +async.waterfall([ + async.apply(fs.readFile, filename, "utf8"), + async.asyncify(JSON.parse), + function (data, next) { + // data is the result of parsing the text. + // If there was a parsing error, it would have been caught. + } +], callback) +``` + +If the function passed to `asyncify` returns a Promise, that promises's resolved/rejected state will be used to call the callback, rather than simply the synchronous return value. Example: + +```js +async.waterfall([ + async.apply(fs.readFile, filename, "utf8"), + async.asyncify(function (contents) { + return db.model.create(contents); + }), + function (model, next) { + // `model` is the instantiated model object. + // If there was an error, this function would be skipped. + } +], callback) +``` + +This also means you can asyncify ES2016 `async` functions. + +```js +var q = async.queue(async.asyncify(async function (file) { + var intermediateStep = await processFile(file); + return await somePromise(intermediateStep) +})); + +q.push(files); +``` + +--------------------------------------- + + +### log(function, arguments) + +Logs the result of an `async` function to the `console`. Only works in Node.js or +in browsers that support `console.log` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.log` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, 'hello ' + name); + }, 1000); +}; +``` +```js +node> async.log(hello, 'world'); +'hello world' +``` + +--------------------------------------- + + +### dir(function, arguments) + +Logs the result of an `async` function to the `console` using `console.dir` to +display the properties of the resulting object. Only works in Node.js or +in browsers that support `console.dir` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.dir` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, {hello: name}); + }, 1000); +}; +``` +```js +node> async.dir(hello, 'world'); +{hello: 'world'} +``` + +--------------------------------------- + + +### noConflict() + +Changes the value of `async` back to its original value, returning a reference to the +`async` object. diff --git a/5-2/service/node_modules/mongoose/node_modules/async/dist/async.js b/5-2/service/node_modules/mongoose/node_modules/async/dist/async.js new file mode 100644 index 0000000..31e7620 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/async/dist/async.js @@ -0,0 +1,1265 @@ +/*! + * async + * https://github.com/caolan/async + * + * Copyright 2010-2014 Caolan McMahon + * Released under the MIT license + */ +(function () { + + var async = {}; + function noop() {} + function identity(v) { + return v; + } + function toBool(v) { + return !!v; + } + function notId(v) { + return !v; + } + + // global on the server, window in the browser + var previous_async; + + // Establish the root object, `window` (`self`) in the browser, `global` + // on the server, or `this` in some virtual machines. We use `self` + // instead of `window` for `WebWorker` support. + var root = typeof self === 'object' && self.self === self && self || + typeof global === 'object' && global.global === global && global || + this; + + if (root != null) { + previous_async = root.async; + } + + async.noConflict = function () { + root.async = previous_async; + return async; + }; + + function only_once(fn) { + return function() { + if (fn === null) throw new Error("Callback was already called."); + fn.apply(this, arguments); + fn = null; + }; + } + + function _once(fn) { + return function() { + if (fn === null) return; + fn.apply(this, arguments); + fn = null; + }; + } + + //// cross-browser compatiblity functions //// + + var _toString = Object.prototype.toString; + + var _isArray = Array.isArray || function (obj) { + return _toString.call(obj) === '[object Array]'; + }; + + // Ported from underscore.js isObject + var _isObject = function(obj) { + var type = typeof obj; + return type === 'function' || type === 'object' && !!obj; + }; + + function _isArrayLike(arr) { + return _isArray(arr) || ( + // has a positive integer length property + typeof arr.length === "number" && + arr.length >= 0 && + arr.length % 1 === 0 + ); + } + + function _arrayEach(arr, iterator) { + var index = -1, + length = arr.length; + + while (++index < length) { + iterator(arr[index], index, arr); + } + } + + function _map(arr, iterator) { + var index = -1, + length = arr.length, + result = Array(length); + + while (++index < length) { + result[index] = iterator(arr[index], index, arr); + } + return result; + } + + function _range(count) { + return _map(Array(count), function (v, i) { return i; }); + } + + function _reduce(arr, iterator, memo) { + _arrayEach(arr, function (x, i, a) { + memo = iterator(memo, x, i, a); + }); + return memo; + } + + function _forEachOf(object, iterator) { + _arrayEach(_keys(object), function (key) { + iterator(object[key], key); + }); + } + + function _indexOf(arr, item) { + for (var i = 0; i < arr.length; i++) { + if (arr[i] === item) return i; + } + return -1; + } + + var _keys = Object.keys || function (obj) { + var keys = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + }; + + function _keyIterator(coll) { + var i = -1; + var len; + var keys; + if (_isArrayLike(coll)) { + len = coll.length; + return function next() { + i++; + return i < len ? i : null; + }; + } else { + keys = _keys(coll); + len = keys.length; + return function next() { + i++; + return i < len ? keys[i] : null; + }; + } + } + + // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) + // This accumulates the arguments passed into an array, after a given index. + // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). + function _restParam(func, startIndex) { + startIndex = startIndex == null ? func.length - 1 : +startIndex; + return function() { + var length = Math.max(arguments.length - startIndex, 0); + var rest = Array(length); + for (var index = 0; index < length; index++) { + rest[index] = arguments[index + startIndex]; + } + switch (startIndex) { + case 0: return func.call(this, rest); + case 1: return func.call(this, arguments[0], rest); + } + // Currently unused but handle cases outside of the switch statement: + // var args = Array(startIndex + 1); + // for (index = 0; index < startIndex; index++) { + // args[index] = arguments[index]; + // } + // args[startIndex] = rest; + // return func.apply(this, args); + }; + } + + function _withoutIndex(iterator) { + return function (value, index, callback) { + return iterator(value, callback); + }; + } + + //// exported async module functions //// + + //// nextTick implementation with browser-compatible fallback //// + + // capture the global reference to guard against fakeTimer mocks + var _setImmediate = typeof setImmediate === 'function' && setImmediate; + + var _delay = _setImmediate ? function(fn) { + // not a direct alias for IE10 compatibility + _setImmediate(fn); + } : function(fn) { + setTimeout(fn, 0); + }; + + if (typeof process === 'object' && typeof process.nextTick === 'function') { + async.nextTick = process.nextTick; + } else { + async.nextTick = _delay; + } + async.setImmediate = _setImmediate ? _delay : async.nextTick; + + + async.forEach = + async.each = function (arr, iterator, callback) { + return async.eachOf(arr, _withoutIndex(iterator), callback); + }; + + async.forEachSeries = + async.eachSeries = function (arr, iterator, callback) { + return async.eachOfSeries(arr, _withoutIndex(iterator), callback); + }; + + + async.forEachLimit = + async.eachLimit = function (arr, limit, iterator, callback) { + return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); + }; + + async.forEachOf = + async.eachOf = function (object, iterator, callback) { + callback = _once(callback || noop); + object = object || []; + + var iter = _keyIterator(object); + var key, completed = 0; + + while ((key = iter()) != null) { + completed += 1; + iterator(object[key], key, only_once(done)); + } + + if (completed === 0) callback(null); + + function done(err) { + completed--; + if (err) { + callback(err); + } + // Check key is null in case iterator isn't exhausted + // and done resolved synchronously. + else if (key === null && completed <= 0) { + callback(null); + } + } + }; + + async.forEachOfSeries = + async.eachOfSeries = function (obj, iterator, callback) { + callback = _once(callback || noop); + obj = obj || []; + var nextKey = _keyIterator(obj); + var key = nextKey(); + function iterate() { + var sync = true; + if (key === null) { + return callback(null); + } + iterator(obj[key], key, only_once(function (err) { + if (err) { + callback(err); + } + else { + key = nextKey(); + if (key === null) { + return callback(null); + } else { + if (sync) { + async.setImmediate(iterate); + } else { + iterate(); + } + } + } + })); + sync = false; + } + iterate(); + }; + + + + async.forEachOfLimit = + async.eachOfLimit = function (obj, limit, iterator, callback) { + _eachOfLimit(limit)(obj, iterator, callback); + }; + + function _eachOfLimit(limit) { + + return function (obj, iterator, callback) { + callback = _once(callback || noop); + obj = obj || []; + var nextKey = _keyIterator(obj); + if (limit <= 0) { + return callback(null); + } + var done = false; + var running = 0; + var errored = false; + + (function replenish () { + if (done && running <= 0) { + return callback(null); + } + + while (running < limit && !errored) { + var key = nextKey(); + if (key === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iterator(obj[key], key, only_once(function (err) { + running -= 1; + if (err) { + callback(err); + errored = true; + } + else { + replenish(); + } + })); + } + })(); + }; + } + + + function doParallel(fn) { + return function (obj, iterator, callback) { + return fn(async.eachOf, obj, iterator, callback); + }; + } + function doParallelLimit(fn) { + return function (obj, limit, iterator, callback) { + return fn(_eachOfLimit(limit), obj, iterator, callback); + }; + } + function doSeries(fn) { + return function (obj, iterator, callback) { + return fn(async.eachOfSeries, obj, iterator, callback); + }; + } + + function _asyncMap(eachfn, arr, iterator, callback) { + callback = _once(callback || noop); + arr = arr || []; + var results = _isArrayLike(arr) ? [] : {}; + eachfn(arr, function (value, index, callback) { + iterator(value, function (err, v) { + results[index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + + async.map = doParallel(_asyncMap); + async.mapSeries = doSeries(_asyncMap); + async.mapLimit = doParallelLimit(_asyncMap); + + // reduce only has a series version, as doing reduce in parallel won't + // work in many situations. + async.inject = + async.foldl = + async.reduce = function (arr, memo, iterator, callback) { + async.eachOfSeries(arr, function (x, i, callback) { + iterator(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); + }; + + async.foldr = + async.reduceRight = function (arr, memo, iterator, callback) { + var reversed = _map(arr, identity).reverse(); + async.reduce(reversed, memo, iterator, callback); + }; + + async.transform = function (arr, memo, iterator, callback) { + if (arguments.length === 3) { + callback = iterator; + iterator = memo; + memo = _isArray(arr) ? [] : {}; + } + + async.eachOf(arr, function(v, k, cb) { + iterator(memo, v, k, cb); + }, function(err) { + callback(err, memo); + }); + }; + + function _filter(eachfn, arr, iterator, callback) { + var results = []; + eachfn(arr, function (x, index, callback) { + iterator(x, function (v) { + if (v) { + results.push({index: index, value: x}); + } + callback(); + }); + }, function () { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + } + + async.select = + async.filter = doParallel(_filter); + + async.selectLimit = + async.filterLimit = doParallelLimit(_filter); + + async.selectSeries = + async.filterSeries = doSeries(_filter); + + function _reject(eachfn, arr, iterator, callback) { + _filter(eachfn, arr, function(value, cb) { + iterator(value, function(v) { + cb(!v); + }); + }, callback); + } + async.reject = doParallel(_reject); + async.rejectLimit = doParallelLimit(_reject); + async.rejectSeries = doSeries(_reject); + + function _createTester(eachfn, check, getResult) { + return function(arr, limit, iterator, cb) { + function done() { + if (cb) cb(getResult(false, void 0)); + } + function iteratee(x, _, callback) { + if (!cb) return callback(); + iterator(x, function (v) { + if (cb && check(v)) { + cb(getResult(true, x)); + cb = iterator = false; + } + callback(); + }); + } + if (arguments.length > 3) { + eachfn(arr, limit, iteratee, done); + } else { + cb = iterator; + iterator = limit; + eachfn(arr, iteratee, done); + } + }; + } + + async.any = + async.some = _createTester(async.eachOf, toBool, identity); + + async.someLimit = _createTester(async.eachOfLimit, toBool, identity); + + async.all = + async.every = _createTester(async.eachOf, notId, notId); + + async.everyLimit = _createTester(async.eachOfLimit, notId, notId); + + function _findGetResult(v, x) { + return x; + } + async.detect = _createTester(async.eachOf, identity, _findGetResult); + async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); + async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); + + async.sortBy = function (arr, iterator, callback) { + async.map(arr, function (x, callback) { + iterator(x, function (err, criteria) { + if (err) { + callback(err); + } + else { + callback(null, {value: x, criteria: criteria}); + } + }); + }, function (err, results) { + if (err) { + return callback(err); + } + else { + callback(null, _map(results.sort(comparator), function (x) { + return x.value; + })); + } + + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + }; + + async.auto = function (tasks, concurrency, callback) { + if (typeof arguments[1] === 'function') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = _once(callback || noop); + var keys = _keys(tasks); + var remainingTasks = keys.length; + if (!remainingTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = remainingTasks; + } + + var results = {}; + var runningTasks = 0; + + var hasError = false; + + var listeners = []; + function addListener(fn) { + listeners.unshift(fn); + } + function removeListener(fn) { + var idx = _indexOf(listeners, fn); + if (idx >= 0) listeners.splice(idx, 1); + } + function taskComplete() { + remainingTasks--; + _arrayEach(listeners.slice(0), function (fn) { + fn(); + }); + } + + addListener(function () { + if (!remainingTasks) { + callback(null, results); + } + }); + + _arrayEach(keys, function (k) { + if (hasError) return; + var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; + var taskCallback = _restParam(function(err, args) { + runningTasks--; + if (args.length <= 1) { + args = args[0]; + } + if (err) { + var safeResults = {}; + _forEachOf(results, function(val, rkey) { + safeResults[rkey] = val; + }); + safeResults[k] = args; + hasError = true; + + callback(err, safeResults); + } + else { + results[k] = args; + async.setImmediate(taskComplete); + } + }); + var requires = task.slice(0, task.length - 1); + // prevent dead-locks + var len = requires.length; + var dep; + while (len--) { + if (!(dep = tasks[requires[len]])) { + throw new Error('Has nonexistent dependency in ' + requires.join(', ')); + } + if (_isArray(dep) && _indexOf(dep, k) >= 0) { + throw new Error('Has cyclic dependencies'); + } + } + function ready() { + return runningTasks < concurrency && _reduce(requires, function (a, x) { + return (a && results.hasOwnProperty(x)); + }, true) && !results.hasOwnProperty(k); + } + if (ready()) { + runningTasks++; + task[task.length - 1](taskCallback, results); + } + else { + addListener(listener); + } + function listener() { + if (ready()) { + runningTasks++; + removeListener(listener); + task[task.length - 1](taskCallback, results); + } + } + }); + }; + + + + async.retry = function(times, task, callback) { + var DEFAULT_TIMES = 5; + var DEFAULT_INTERVAL = 0; + + var attempts = []; + + var opts = { + times: DEFAULT_TIMES, + interval: DEFAULT_INTERVAL + }; + + function parseTimes(acc, t){ + if(typeof t === 'number'){ + acc.times = parseInt(t, 10) || DEFAULT_TIMES; + } else if(typeof t === 'object'){ + acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; + acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; + } else { + throw new Error('Unsupported argument type for \'times\': ' + typeof t); + } + } + + var length = arguments.length; + if (length < 1 || length > 3) { + throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); + } else if (length <= 2 && typeof times === 'function') { + callback = task; + task = times; + } + if (typeof times !== 'function') { + parseTimes(opts, times); + } + opts.callback = callback; + opts.task = task; + + function wrappedTask(wrappedCallback, wrappedResults) { + function retryAttempt(task, finalAttempt) { + return function(seriesCallback) { + task(function(err, result){ + seriesCallback(!err || finalAttempt, {err: err, result: result}); + }, wrappedResults); + }; + } + + function retryInterval(interval){ + return function(seriesCallback){ + setTimeout(function(){ + seriesCallback(null); + }, interval); + }; + } + + while (opts.times) { + + var finalAttempt = !(opts.times-=1); + attempts.push(retryAttempt(opts.task, finalAttempt)); + if(!finalAttempt && opts.interval > 0){ + attempts.push(retryInterval(opts.interval)); + } + } + + async.series(attempts, function(done, data){ + data = data[data.length - 1]; + (wrappedCallback || opts.callback)(data.err, data.result); + }); + } + + // If a callback is passed, run this as a controll flow + return opts.callback ? wrappedTask() : wrappedTask; + }; + + async.waterfall = function (tasks, callback) { + callback = _once(callback || noop); + if (!_isArray(tasks)) { + var err = new Error('First argument to waterfall must be an array of functions'); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + function wrapIterator(iterator) { + return _restParam(function (err, args) { + if (err) { + callback.apply(null, [err].concat(args)); + } + else { + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } + else { + args.push(callback); + } + ensureAsync(iterator).apply(null, args); + } + }); + } + wrapIterator(async.iterator(tasks))(); + }; + + function _parallel(eachfn, tasks, callback) { + callback = callback || noop; + var results = _isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, function (task, key, callback) { + task(_restParam(function (err, args) { + if (args.length <= 1) { + args = args[0]; + } + results[key] = args; + callback(err); + })); + }, function (err) { + callback(err, results); + }); + } + + async.parallel = function (tasks, callback) { + _parallel(async.eachOf, tasks, callback); + }; + + async.parallelLimit = function(tasks, limit, callback) { + _parallel(_eachOfLimit(limit), tasks, callback); + }; + + async.series = function(tasks, callback) { + _parallel(async.eachOfSeries, tasks, callback); + }; + + async.iterator = function (tasks) { + function makeCallback(index) { + function fn() { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + } + fn.next = function () { + return (index < tasks.length - 1) ? makeCallback(index + 1): null; + }; + return fn; + } + return makeCallback(0); + }; + + async.apply = _restParam(function (fn, args) { + return _restParam(function (callArgs) { + return fn.apply( + null, args.concat(callArgs) + ); + }); + }); + + function _concat(eachfn, arr, fn, callback) { + var result = []; + eachfn(arr, function (x, index, cb) { + fn(x, function (err, y) { + result = result.concat(y || []); + cb(err); + }); + }, function (err) { + callback(err, result); + }); + } + async.concat = doParallel(_concat); + async.concatSeries = doSeries(_concat); + + async.whilst = function (test, iterator, callback) { + callback = callback || noop; + if (test()) { + var next = _restParam(function(err, args) { + if (err) { + callback(err); + } else if (test.apply(this, args)) { + iterator(next); + } else { + callback.apply(null, [null].concat(args)); + } + }); + iterator(next); + } else { + callback(null); + } + }; + + async.doWhilst = function (iterator, test, callback) { + var calls = 0; + return async.whilst(function() { + return ++calls <= 1 || test.apply(this, arguments); + }, iterator, callback); + }; + + async.until = function (test, iterator, callback) { + return async.whilst(function() { + return !test.apply(this, arguments); + }, iterator, callback); + }; + + async.doUntil = function (iterator, test, callback) { + return async.doWhilst(iterator, function() { + return !test.apply(this, arguments); + }, callback); + }; + + async.during = function (test, iterator, callback) { + callback = callback || noop; + + var next = _restParam(function(err, args) { + if (err) { + callback(err); + } else { + args.push(check); + test.apply(this, args); + } + }); + + var check = function(err, truth) { + if (err) { + callback(err); + } else if (truth) { + iterator(next); + } else { + callback(null); + } + }; + + test(check); + }; + + async.doDuring = function (iterator, test, callback) { + var calls = 0; + async.during(function(next) { + if (calls++ < 1) { + next(null, true); + } else { + test.apply(this, arguments); + } + }, iterator, callback); + }; + + function _queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + function _insert(q, data, pos, callback) { + if (callback != null && typeof callback !== "function") { + throw new Error("task callback must be a function"); + } + q.started = true; + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + q.drain(); + }); + } + _arrayEach(data, function(task) { + var item = { + data: task, + callback: callback || noop + }; + + if (pos) { + q.tasks.unshift(item); + } else { + q.tasks.push(item); + } + + if (q.tasks.length === q.concurrency) { + q.saturated(); + } + }); + async.setImmediate(q.process); + } + function _next(q, tasks) { + return function(){ + workers -= 1; + + var removed = false; + var args = arguments; + _arrayEach(tasks, function (task) { + _arrayEach(workersList, function (worker, index) { + if (worker === task && !removed) { + workersList.splice(index, 1); + removed = true; + } + }); + + task.callback.apply(task, args); + }); + if (q.tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + } + + var workers = 0; + var workersList = []; + var q = { + tasks: [], + concurrency: concurrency, + payload: payload, + saturated: noop, + empty: noop, + drain: noop, + started: false, + paused: false, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + kill: function () { + q.drain = noop; + q.tasks = []; + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + while(!q.paused && workers < q.concurrency && q.tasks.length){ + + var tasks = q.payload ? + q.tasks.splice(0, q.payload) : + q.tasks.splice(0, q.tasks.length); + + var data = _map(tasks, function (task) { + return task.data; + }); + + if (q.tasks.length === 0) { + q.empty(); + } + workers += 1; + workersList.push(tasks[0]); + var cb = only_once(_next(q, tasks)); + worker(data, cb); + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + }, + workersList: function () { + return workersList; + }, + idle: function() { + return q.tasks.length + workers === 0; + }, + pause: function () { + q.paused = true; + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + var resumeCount = Math.min(q.concurrency, q.tasks.length); + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= resumeCount; w++) { + async.setImmediate(q.process); + } + } + }; + return q; + } + + async.queue = function (worker, concurrency) { + var q = _queue(function (items, cb) { + worker(items[0], cb); + }, concurrency, 1); + + return q; + }; + + async.priorityQueue = function (worker, concurrency) { + + function _compareTasks(a, b){ + return a.priority - b.priority; + } + + function _binarySearch(sequence, item, compare) { + var beg = -1, + end = sequence.length - 1; + while (beg < end) { + var mid = beg + ((end - beg + 1) >>> 1); + if (compare(item, sequence[mid]) >= 0) { + beg = mid; + } else { + end = mid - 1; + } + } + return beg; + } + + function _insert(q, data, priority, callback) { + if (callback != null && typeof callback !== "function") { + throw new Error("task callback must be a function"); + } + q.started = true; + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + q.drain(); + }); + } + _arrayEach(data, function(task) { + var item = { + data: task, + priority: priority, + callback: typeof callback === 'function' ? callback : noop + }; + + q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); + + if (q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + // Start with a normal queue + var q = async.queue(worker, concurrency); + + // Override push to accept second parameter representing priority + q.push = function (data, priority, callback) { + _insert(q, data, priority, callback); + }; + + // Remove unshift function + delete q.unshift; + + return q; + }; + + async.cargo = function (worker, payload) { + return _queue(worker, 1, payload); + }; + + function _console_fn(name) { + return _restParam(function (fn, args) { + fn.apply(null, args.concat([_restParam(function (err, args) { + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } + else if (console[name]) { + _arrayEach(args, function (x) { + console[name](x); + }); + } + } + })])); + }); + } + async.log = _console_fn('log'); + async.dir = _console_fn('dir'); + /*async.info = _console_fn('info'); + async.warn = _console_fn('warn'); + async.error = _console_fn('error');*/ + + async.memoize = function (fn, hasher) { + var memo = {}; + var queues = {}; + var has = Object.prototype.hasOwnProperty; + hasher = hasher || identity; + var memoized = _restParam(function memoized(args) { + var callback = args.pop(); + var key = hasher.apply(null, args); + if (has.call(memo, key)) { + async.setImmediate(function () { + callback.apply(null, memo[key]); + }); + } + else if (has.call(queues, key)) { + queues[key].push(callback); + } + else { + queues[key] = [callback]; + fn.apply(null, args.concat([_restParam(function (args) { + memo[key] = args; + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, args); + } + })])); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + }; + + async.unmemoize = function (fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + }; + + function _times(mapper) { + return function (count, iterator, callback) { + mapper(_range(count), iterator, callback); + }; + } + + async.times = _times(async.map); + async.timesSeries = _times(async.mapSeries); + async.timesLimit = function (count, limit, iterator, callback) { + return async.mapLimit(_range(count), limit, iterator, callback); + }; + + async.seq = function (/* functions... */) { + var fns = arguments; + return _restParam(function (args) { + var that = this; + + var callback = args[args.length - 1]; + if (typeof callback == 'function') { + args.pop(); + } else { + callback = noop; + } + + async.reduce(fns, args, function (newargs, fn, cb) { + fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { + cb(err, nextargs); + })])); + }, + function (err, results) { + callback.apply(that, [err].concat(results)); + }); + }); + }; + + async.compose = function (/* functions... */) { + return async.seq.apply(null, Array.prototype.reverse.call(arguments)); + }; + + + function _applyEach(eachfn) { + return _restParam(function(fns, args) { + var go = _restParam(function(args) { + var that = this; + var callback = args.pop(); + return eachfn(fns, function (fn, _, cb) { + fn.apply(that, args.concat([cb])); + }, + callback); + }); + if (args.length) { + return go.apply(this, args); + } + else { + return go; + } + }); + } + + async.applyEach = _applyEach(async.eachOf); + async.applyEachSeries = _applyEach(async.eachOfSeries); + + + async.forever = function (fn, callback) { + var done = only_once(callback || noop); + var task = ensureAsync(fn); + function next(err) { + if (err) { + return done(err); + } + task(next); + } + next(); + }; + + function ensureAsync(fn) { + return _restParam(function (args) { + var callback = args.pop(); + args.push(function () { + var innerArgs = arguments; + if (sync) { + async.setImmediate(function () { + callback.apply(null, innerArgs); + }); + } else { + callback.apply(null, innerArgs); + } + }); + var sync = true; + fn.apply(this, args); + sync = false; + }); + } + + async.ensureAsync = ensureAsync; + + async.constant = _restParam(function(values) { + var args = [null].concat(values); + return function (callback) { + return callback.apply(this, args); + }; + }); + + async.wrapSync = + async.asyncify = function asyncify(func) { + return _restParam(function (args) { + var callback = args.pop(); + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (_isObject(result) && typeof result.then === "function") { + result.then(function(value) { + callback(null, value); + })["catch"](function(err) { + callback(err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); + }; + + // Node.js + if (typeof module === 'object' && module.exports) { + module.exports = async; + } + // AMD / RequireJS + else if (typeof define === 'function' && define.amd) { + define([], function () { + return async; + }); + } + // included directly via + + + + + +``` + +A simple example of how to use BSON in `node.js`: + +```javascript +var bson = require("bson"); +var BSON = new 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. + * **promoteBuffers** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. + * @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/5-2/service/node_modules/mongoose/node_modules/bson/alternate_parsers/bson.js b/5-2/service/node_modules/mongoose/node_modules/bson/alternate_parsers/bson.js new file mode 100644 index 0000000..555aa79 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/alternate_parsers/bson.js @@ -0,0 +1,1574 @@ +var Long = require('../lib/bson/long').Long + , Double = require('../lib/bson/double').Double + , Timestamp = require('../lib/bson/timestamp').Timestamp + , ObjectID = require('../lib/bson/objectid').ObjectID + , Symbol = require('../lib/bson/symbol').Symbol + , Code = require('../lib/bson/code').Code + , MinKey = require('../lib/bson/min_key').MinKey + , MaxKey = require('../lib/bson/max_key').MaxKey + , DBRef = require('../lib/bson/db_ref').DBRef + , Binary = require('../lib/bson/binary').Binary + , BinaryParser = require('../lib/bson/binary_parser').BinaryParser + , writeIEEE754 = require('../lib/bson/float_parser').writeIEEE754 + , readIEEE754 = require('../lib/bson/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 + */ +module.exports = BSON; +module.exports.Code = Code; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/alternate_parsers/faster_bson.js b/5-2/service/node_modules/mongoose/node_modules/bson/alternate_parsers/faster_bson.js new file mode 100644 index 0000000..f19e44f --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/alternate_parsers/faster_bson.js @@ -0,0 +1,429 @@ +/// reduced to ~ 410 LOCs (parser only 300 vs. 1400+) with (some, needed) BSON classes "inlined". +/// Compare ~ 4,300 (22KB vs. 157KB) in browser build at: https://github.com/mongodb/js-bson/blob/master/browser_build/bson.js + +module.exports.calculateObjectSize = calculateObjectSize; + +function calculateObjectSize(object) { + var totalLength = (4 + 1); /// handles the obj.length prefix + terminating '0' ?! + for(var key in object) { /// looks like it handles arrays under the same for...in loop!? + totalLength += calculateElement(key, object[key]) + } + return totalLength; +} + +function calculateElement(name, value) { + var len = 1; /// always starting with 1 for the data type byte! + if (name) len += Buffer.byteLength(name, 'utf8') + 1; /// cstring: name + '0' termination + + if (value === undefined || value === null) return len; /// just the type byte plus name cstring + switch( value.constructor ) { /// removed all checks 'isBuffer' if Node.js Buffer class is present!? + + case ObjectID: /// we want these sorted from most common case to least common/deprecated; + return len + 12; + case String: + return len + 4 + Buffer.byteLength(value, 'utf8') +1; /// + case Number: + if (Math.floor(value) === value) { /// case: integer; pos.# more common, '&&' stops if 1st fails! + if ( value <= 2147483647 && value >= -2147483647 ) // 32 bit + return len + 4; + else return len + 8; /// covers Long-ish JS integers as Longs! + } else return len + 8; /// 8+1 --- covers Double & std. float + case Boolean: + return len + 1; + + case Array: + case Object: + return len + calculateObjectSize(value); + + case Buffer: /// replaces the entire Binary class! + return len + 4 + value.length + 1; + + case Regex: /// these are handled as strings by serializeFast() later, hence 'gim' opts = 3 + 1 chars + return len + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) +1; + case Date: + case Long: + case Timestamp: + case Double: + return len + 8; + + case MinKey: + case MaxKey: + return len; /// these two return the type byte and name cstring only! + } + return 0; +} + +module.exports.serializeFast = serializeFast; +module.exports.serialize = function(object, checkKeys, asBuffer, serializeFunctions, index) { + var buffer = new Buffer(calculateObjectSize(object)); + return serializeFast(object, checkKeys, buffer, 0); +} + +function serializeFast(object, checkKeys, buffer, i) { /// set checkKeys = false in query(..., options object to save performance IFF you're certain your keys are safe/system-set! + var size = buffer.length; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; /// these get overwritten later! + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + if (object.constructor === Array) { /// any need to checkKeys here?!? since we're doing for rather than for...in, should be safe from extra (non-numeric) keys added to the array?! + for(var j = 0; j < object.length; j++) { + i = packElement(j.toString(), object[j], checkKeys, buffer, i); + } + } else { /// checkKeys is needed if any suspicion of end-user key tampering/"injection" (a la SQL) + for(var key in object) { /// mostly there should never be direct access to them!? + if (checkKeys && (key.indexOf('\x00') >= 0 || key === '$where') ) { /// = "no script"?!; could add back key.indexOf('$') or maybe check for 'eval'?! +/// took out: || key.indexOf('.') >= 0... Don't we allow dot notation queries?! + console.log('checkKeys error: '); + return new Error('Illegal object key!'); + } + i = packElement(key, object[key], checkKeys, buffer, i); /// checkKeys pass needed for recursion! + } + } + buffer[i++] = 0; /// write terminating zero; !we do NOT -1 the index increase here as original does! + return i; +} + +function packElement(name, value, checkKeys, buffer, i) { /// serializeFunctions removed! checkKeys needed for Array & Object cases pass through (calling serializeFast recursively!) + if (value === undefined || value === null){ + buffer[i++] = 10; /// = BSON.BSON_DATA_NULL; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; /// buffer.write(...) returns bytesWritten! + return i; + } + switch(value.constructor) { + + case ObjectID: + buffer[i++] = 7; /// = BSON.BSON_DATA_OID; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// i += buffer.write(value.id, i, 'binary'); /// OLD: writes a String to a Buffer; 'binary' deprecated!! + value.id.copy(buffer, i); /// NEW ObjectID version has this.id = Buffer at the ready! + return i += 12; + + case String: + buffer[i++] = 2; /// = BSON.BSON_DATA_STRING; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + + var size = Buffer.byteLength(value) + 1; /// includes the terminating '0'!? + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + i += buffer.write(value, i, 'utf8'); buffer[i++] = 0; + return i; + + case Number: + if ( ~~(value) === value) { /// double-Tilde is equiv. to Math.floor(value) + if ( value <= 2147483647 && value >= -2147483647){ /// = BSON.BSON_INT32_MAX / MIN asf. + buffer[i++] = 16; /// = BSON.BSON_DATA_INT; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + buffer[i++] = value & 0xff; buffer[i++] = (value >> 8) & 0xff; + buffer[i++] = (value >> 16) & 0xff; buffer[i++] = (value >> 24) & 0xff; + +// Else large-ish JS int!? to Long!? + } else { /// if (value <= BSON.JS_INT_MAX && value >= BSON.JS_INT_MIN){ /// 9007199254740992 asf. + buffer[i++] = 18; /// = BSON.BSON_DATA_LONG; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var lowBits = ( value % 4294967296 ) | 0, highBits = ( value / 4294967296 ) | 0; + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + } + } else { /// we have a float / Double + buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); + buffer.writeDoubleLE(value, i); i += 8; + } + return i; + + case Boolean: + buffer[i++] = 8; /// = BSON.BSON_DATA_BOOLEAN; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + buffer[i++] = value ? 1 : 0; + return i; + + case Array: + case Object: + buffer[i++] = value.constructor === Array ? 4 : 3; /// = BSON.BSON_DATA_ARRAY / _OBJECT; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + + var endIndex = serializeFast(value, checkKeys, buffer, i); /// + 4); no longer needed b/c serializeFast writes a temp 4 bytes for length + var size = endIndex - i; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + return endIndex; + + /// case Binary: /// is basically identical unless special/deprecated options! + case Buffer: /// solves ALL of our Binary needs without the BSON.Binary class!? + buffer[i++] = 5; /// = BSON.BSON_DATA_BINARY; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var size = value.length; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + buffer[i++] = 0; /// write BSON.BSON_BINARY_SUBTYPE_DEFAULT; + value.copy(buffer, i); ///, 0, size); << defaults to sourceStart=0, sourceEnd=sourceBuffer.length); + i += size; + return i; + + case RegExp: + buffer[i++] = 11; /// = BSON.BSON_DATA_REGEXP; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + i += buffer.write(value.source, i, 'utf8'); buffer[i++] = 0x00; + + if (value.global) buffer[i++] = 0x73; // s = 'g' for JS Regex! + if (value.ignoreCase) buffer[i++] = 0x69; // i + if (value.multiline) buffer[i++] = 0x6d; // m + buffer[i++] = 0x00; + return i; + + case Date: + buffer[i++] = 9; /// = BSON.BSON_DATA_DATE; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var millis = value.getTime(); + var lowBits = ( millis % 4294967296 ) | 0, highBits = ( millis / 4294967296 ) | 0; + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + return i; + + case Long: + case Timestamp: + buffer[i++] = value.constructor === Long ? 18 : 17; /// = BSON.BSON_DATA_LONG / _TIMESTAMP + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var lowBits = value.getLowBits(), highBits = value.getHighBits(); + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + return i; + + case Double: + buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); i += 8; + buffer.writeDoubleLE(value, i); i += 8; + return i + + case MinKey: /// = BSON.BSON_DATA_MINKEY; + buffer[i++] = 127; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + return i; + case MaxKey: /// = BSON.BSON_DATA_MAXKEY; + buffer[i++] = 255; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + return i; + + } /// end of switch + return i; /// ?! If no value to serialize +} + + +module.exports.deserializeFast = deserializeFast; + +function deserializeFast(buffer, i, isArray){ //// , options, isArray) { //// no more options! + if (buffer.length < 5) return new Error('Corrupt bson message < 5 bytes long'); /// from 'throw' + var elementType, tempindex = 0, name; + var string, low, high; /// = lowBits / highBits + /// using 'i' as the index to keep the lines shorter: + i || ( i = 0 ); /// for parseResponse it's 0; set to running index in deserialize(object/array) recursion + var object = isArray ? [] : {}; /// needed for type ARRAY recursion later! + var size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + if(size < 5 || size > buffer.length) return new Error('Corrupt BSON message'); +/// 'size' var was not used by anything after this, so we can reuse it + + while(true) { // While we have more left data left keep parsing + elementType = buffer[i++]; // Read the type + if (elementType === 0) break; // If we get a zero it's the last byte, exit + + tempindex = i; /// inlined readCStyleString & removed extra i= buffer.length) return new Error('Corrupt BSON document: illegal CString') + name = buffer.toString('utf8', i, tempindex); + i = tempindex + 1; /// Update index position to after the string + '0' termination + + switch(elementType) { + + case 7: /// = BSON.BSON_DATA_OID: + var buf = new Buffer(12); + buffer.copy(buf, 0, i, i += 12 ); /// copy 12 bytes from the current 'i' offset into fresh Buffer + object[name] = new ObjectID(buf); ///... & attach to the new ObjectID instance + break; + + case 2: /// = BSON.BSON_DATA_STRING: + size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; + object[name] = buffer.toString('utf8', i, i += size -1 ); + i++; break; /// need to get the '0' index "tick-forward" back! + + case 16: /// = BSON.BSON_DATA_INT: // Decode the 32bit value + object[name] = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; break; + + case 1: /// = BSON.BSON_DATA_NUMBER: // Decode the double value + object[name] = buffer.readDoubleLE(i); /// slightly faster depending on dec.points; a LOT cleaner + /// OLD: object[name] = readIEEE754(buffer, i, 'little', 52, 8); + i += 8; break; + + case 8: /// = BSON.BSON_DATA_BOOLEAN: + object[name] = buffer[i++] == 1; break; + + case 6: /// = BSON.BSON_DATA_UNDEFINED: /// deprecated + case 10: /// = BSON.BSON_DATA_NULL: + object[name] = null; break; + + case 4: /// = BSON.BSON_DATA_ARRAY + size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; /// NO 'i' increment since the size bytes are reread during the recursion! + object[name] = deserializeFast(buffer, i, true ); /// pass current index & set isArray = true + i += size; break; + case 3: /// = BSON.BSON_DATA_OBJECT: + size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; + object[name] = deserializeFast(buffer, i, false ); /// isArray = false => Object + i += size; break; + + case 5: /// = BSON.BSON_DATA_BINARY: // Decode the size of the binary blob + size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + buffer[i++]; /// Skip, as we assume always default subtype, i.e. 0! + object[name] = buffer.slice(i, i += size); /// creates a new Buffer "slice" view of the same memory! + break; + + case 9: /// = BSON.BSON_DATA_DATE: /// SEE notes below on the Date type vs. other options... + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + object[name] = new Date( high * 4294967296 + (low < 0 ? low + 4294967296 : low) ); break; + + case 18: /// = BSON.BSON_DATA_LONG: /// usage should be somewhat rare beyond parseResponse() -> cursorId, where it is handled inline, NOT as part of deserializeFast(returnedObjects); get lowBits, highBits: + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + + size = high * 4294967296 + (low < 0 ? low + 4294967296 : low); /// from long.toNumber() + if (size < JS_INT_MAX && size > JS_INT_MIN) object[name] = size; /// positive # more likely! + else object[name] = new Long(low, high); break; + + case 127: /// = BSON.BSON_DATA_MIN_KEY: /// do we EVER actually get these BACK from MongoDB server?! + object[name] = new MinKey(); break; + case 255: /// = BSON.BSON_DATA_MAX_KEY: + object[name] = new MaxKey(); break; + + case 17: /// = BSON.BSON_DATA_TIMESTAMP: /// somewhat obscure internal BSON type; MongoDB uses it for (pseudo) high-res time timestamp (past millisecs precision is just a counter!) in the Oplog ts: field, etc. + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + object[name] = new Timestamp(low, high); break; + +/// case 11: /// = RegExp is skipped; we should NEVER be getting any from the MongoDB server!? + } /// end of switch(elementType) + } /// end of while(1) + return object; // Return the finalized object +} + + +function MinKey() { this._bsontype = 'MinKey'; } /// these are merely placeholders/stubs to signify the type!? + +function MaxKey() { this._bsontype = 'MaxKey'; } + +function Long(low, high) { + this._bsontype = 'Long'; + this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. +} +Long.prototype.getLowBits = function(){ return this.low_; } +Long.prototype.getHighBits = function(){ return this.high_; } + +Long.prototype.toNumber = function(){ + return this.high_ * 4294967296 + (this.low_ < 0 ? this.low_ + 4294967296 : this.low_); +} +Long.fromNumber = function(num){ + return new Long(num % 4294967296, num / 4294967296); /// |0 is forced in the constructor! +} +function Double(value) { + this._bsontype = 'Double'; + this.value = value; +} +function Timestamp(low, high) { + this._bsontype = 'Timestamp'; + this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. +} +Timestamp.prototype.getLowBits = function(){ return this.low_; } +Timestamp.prototype.getHighBits = function(){ return this.high_; } + +/////////////////////////////// ObjectID ///////////////////////////////// +/// machine & proc IDs stored as 1 string, b/c Buffer shouldn't be held for long periods (could use SlowBuffer?!) + +var MACHINE = parseInt(Math.random() * 0xFFFFFF, 10); +var PROCESS = process.pid % 0xFFFF; +var MACHINE_AND_PROC = encodeIntBE(MACHINE, 3) + encodeIntBE(PROCESS, 2); /// keep as ONE string, ready to go. + +function encodeIntBE(data, bytes){ /// encode the bytes to a string + var result = ''; + if (bytes >= 4){ result += String.fromCharCode(Math.floor(data / 0x1000000)); data %= 0x1000000; } + if (bytes >= 3){ result += String.fromCharCode(Math.floor(data / 0x10000)); data %= 0x10000; } + if (bytes >= 2){ result += String.fromCharCode(Math.floor(data / 0x100)); data %= 0x100; } + result += String.fromCharCode(Math.floor(data)); + return result; +} +var _counter = ~~(Math.random() * 0xFFFFFF); /// double-tilde is equivalent to Math.floor() +var checkForHex = new RegExp('^[0-9a-fA-F]{24}$'); + +function ObjectID(id) { + this._bsontype = 'ObjectID'; + if (!id){ this.id = createFromScratch(); /// base case, DONE. + } else { + if (id.constructor === Buffer){ + this.id = id; /// case of + } else if (id.constructor === String) { + if ( id.length === 24 && checkForHex.test(id) ) { + this.id = new Buffer(id, 'hex'); + } else { + this.id = new Error('Illegal/faulty Hexadecimal string supplied!'); /// changed from 'throw' + } + } else if (id.constructor === Number) { + this.id = createFromTime(id); /// this is what should be the only interface for this!? + } + } +} +function createFromScratch() { + var buf = new Buffer(12), i = 0; + var ts = ~~(Date.now()/1000); /// 4 bytes timestamp in seconds, BigEndian notation! + buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; + buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; + + buf.write(MACHINE_AND_PROC, i, 5, 'utf8'); i += 5; /// write 3 bytes + 2 bytes MACHINE_ID and PROCESS_ID + _counter = ++_counter % 0xFFFFFF; /// 3 bytes internal _counter for subsecond resolution; BigEndian + buf[i++] = (_counter >> 16) & 0xFF; + buf[i++] = (_counter >> 8) & 0xFF; + buf[i++] = (_counter) & 0xFF; + return buf; +} +function createFromTime(ts) { + ts || ( ts = ~~(Date.now()/1000) ); /// 4 bytes timestamp in seconds only + var buf = new Buffer(12), i = 0; + buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; + buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; + + for (;i < 12; ++i) buf[i] = 0x00; /// indeces 4 through 11 (8 bytes) get filled up with nulls + return buf; +} +ObjectID.prototype.toHexString = function toHexString() { + return this.id.toString('hex'); +} +ObjectID.prototype.getTimestamp = function getTimestamp() { + return this.id.readUIntBE(0, 4); +} +ObjectID.prototype.getTimestampDate = function getTimestampDate() { + var ts = new Date(); + ts.setTime(this.id.readUIntBE(0, 4) * 1000); + return ts; +} +ObjectID.createPk = function createPk () { ///?override if a PrivateKey factory w/ unique factors is warranted?! + return new ObjectID(); +} +ObjectID.prototype.toJSON = function toJSON() { + return "ObjectID('" +this.id.toString('hex')+ "')"; +} + +/// module.exports.BSON = BSON; /// not needed anymore!? exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.Long = Long; /// ?! we really don't want to do the complicated Long math anywhere for now!? + +//module.exports.Double = Double; +//module.exports.Timestamp = Timestamp; diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/bower.json b/5-2/service/node_modules/mongoose/node_modules/bson/bower.json new file mode 100644 index 0000000..b32140e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/bower.json @@ -0,0 +1,25 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "author": "Christian Amor Kvalheim ", + "main": "./browser_build/bson.js", + "license": "Apache-2.0", + "moduleType": [ + "globals", + "node" + ], + "ignore": [ + "**/.*", + "alternate_parsers", + "benchmarks", + "bower_components", + "node_modules", + "test", + "tools" + ] +} diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/browser_build/bson.js b/5-2/service/node_modules/mongoose/node_modules/bson/browser_build/bson.js new file mode 100644 index 0000000..8e942dd --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/browser_build/bson.js @@ -0,0 +1,4843 @@ +var bson = (function(){ + + var pkgmap = {}, + global = {}, + nativeRequire = typeof require != 'undefined' && require, + lib, ties, main, async; + + function exports(){ return main(); }; + + exports.main = exports; + exports.module = module; + exports.packages = pkgmap; + exports.pkg = pkg; + exports.require = function require(uri){ + return pkgmap.main.index.require(uri); + }; + + + ties = {}; + + aliases = {}; + + + return exports; + +function join() { + return normalize(Array.prototype.join.call(arguments, "/")); +}; + +function normalize(path) { + var ret = [], parts = path.split('/'), cur, prev; + + var i = 0, l = parts.length-1; + for (; i <= l; i++) { + cur = parts[i]; + + if (cur === "." && prev !== undefined) continue; + + if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { + ret.pop(); + prev = ret.slice(-1)[0]; + } else { + if (prev === ".") ret.pop(); + ret.push(cur); + prev = cur; + } + } + + return ret.join("/"); +}; + +function dirname(path) { + return path && path.substr(0, path.lastIndexOf("/")) || "."; +}; + +function findModule(workingModule, uri){ + var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), + moduleIndexId = join(moduleId, 'index'), + pkg = workingModule.pkg, + module; + + var i = pkg.modules.length, + id; + + while(i-->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/5-2/service/node_modules/mongoose/node_modules/bson/browser_build/package.json b/5-2/service/node_modules/mongoose/node_modules/bson/browser_build/package.json new file mode 100644 index 0000000..3ebb587 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/browser_build/package.json @@ -0,0 +1,8 @@ +{ "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/5-2/service/node_modules/mongoose/node_modules/bson/deserializer_bak.js b/5-2/service/node_modules/mongoose/node_modules/bson/deserializer_bak.js new file mode 100644 index 0000000..c879ad5 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/deserializer_bak.js @@ -0,0 +1,357 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754, + readIEEE754 = require('../float_parser').readIEEE754, + f = require('util').format, + 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, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var BSON = {}; + +/** + * 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 = {}; + +/** + * 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; + +// 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. + +var deserialize = function(buffer, options, isArray) { + var index = 0; + // 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 || buffer.length < size) { + throw new Error("corrupt bson message"); + } + + // Illegal end value + if(buffer[size - 1] != 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, options, isArray); +} + +// // Reads in a C style string +// var readCStyleStringSpecial = function(buffer, index) { +// // 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 = buffer.toString('utf8', index, i); +// // Update index position +// index = i + 1; +// // Return string +// return {s: string, i: index}; +// } + +// Reads in a C style string +var readCStyleStringSpecial = function(buffer, index) { + // 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 + return buffer.toString('utf8', index, i); +} + +var DeserializationMethods = {} +DeserializationMethods[BSON.BSON_DATA_OID] = function(name, object, buffer, index) { + var string = buffer.toString('binary', index, index + 12); + object[name] = new ObjectID(string); + return index + 12; +} + +DeserializationMethods[BSON.BSON_DATA_NUMBER] = function(name, object, buffer, index) { + object[name] = buffer.readDoubleLE(index); + return index + 8; +} + +DeserializationMethods[BSON.BSON_DATA_INT] = function(name, object, buffer, index) { + object[name] = buffer.readInt32LE(index); + return index + 4; +} + +DeserializationMethods[BSON.BSON_DATA_TIMESTAMP] = function(name, object, buffer, index) { + 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; + object[name] = new Timestamp(lowBits, highBits); + return index; +} + +DeserializationMethods[BSON.BSON_DATA_STRING] = function(name, object, buffer, index) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + return index + stringSize; +} + +DeserializationMethods[BSON.BSON_DATA_BOOLEAN] = function(name, object, buffer, index) { + object[name] = buffer[index++] == 1; + return index; +} + +var deserializeObject = 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']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? {} : options['fieldsAsRaw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + + // 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; + + // 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"); + + // Create holding object + var object = isArray ? [] : {}; + + // 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; + var name = readCStyleStringSpecial(buffer, index); + index = index + name.length + 1; + + // console.log("----------- 0 " + elementType + " :: " + name) + index = DeserializationMethods[elementType](name, object, buffer, index); + // console.log('--------------- 1') + } + + // 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; +} + +/** + * 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; +} + +module.exports = deserialize diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/binary.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/binary.js new file mode 100644 index 0000000..ef74b16 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/binary.js @@ -0,0 +1,344 @@ +/** + * 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, offset, 'binary'); + 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; diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js new file mode 100644 index 0000000..d2fc811 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js @@ -0,0 +1,385 @@ +/** + * 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/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/bson.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/bson.js new file mode 100644 index 0000000..36f0057 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/bson.js @@ -0,0 +1,323 @@ +// "use strict" + +var writeIEEE754 = require('./float_parser').writeIEEE754, + readIEEE754 = require('./float_parser').readIEEE754, + Map = require('./map'), + Long = require('./long').Long, + Double = require('./double').Double, + Timestamp = require('./timestamp').Timestamp, + ObjectID = require('./objectid').ObjectID, + BSONRegExp = require('./regexp').BSONRegExp, + 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; + +// Parts of the parser +var deserialize = require('./parser/deserializer'), + serializer = require('./parser/serializer'), + calculateObjectSize = require('./parser/calculate_size'); + +/** + * @ignore + * @api private + */ +// Max Size +var MAXSIZE = (1024*1024*17); +// Max Document Buffer size +var buffer = new Buffer(MAXSIZE); + +var BSON = function() { +} + +/** + * 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 serialize(object, checkKeys, asBuffer, serializeFunctions, index, ignoreUndefined) { + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, index || 0, 0, serializeFunctions, ignoreUndefined); + // Create the final buffer + var finishedBuffer = new Buffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +} + +/** + * 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, finalBuffer, startIndex, serializeFunctions, ignoreUndefined) { + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; +} + +/** + * 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.prototype.deserialize = function(data, options) { + return deserialize(data, options); +} + +/** + * 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, ignoreUndefined) { + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); +} + +/** + * 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.prototype.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] = this.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; +} + +/** + * @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 +module.exports = BSON; +module.exports.Code = Code; +module.exports.Map = Map; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.BSONRegExp = BSONRegExp; diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/code.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/code.js new file mode 100644 index 0000000..83a42c9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * 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/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js new file mode 100644 index 0000000..06789a6 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * 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/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/double.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/double.js new file mode 100644 index 0000000..09ed222 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * 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/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js new file mode 100644 index 0000000..6fca392 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js @@ -0,0 +1,121 @@ +// 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/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/index.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/index.js new file mode 100644 index 0000000..eca45cd --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/index.js @@ -0,0 +1,86 @@ +try { + exports.BSONPure = require('./bson'); + exports.BSONNative = require('./bson'); +} catch(err) { +} + +[ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './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 PURE JS BSON Parser +exports.pure = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './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; +} + +// Exports all the classes for the NATIVE JS BSON Parser +exports.native = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './symbol' + , './timestamp' + , './long' + ].forEach(function (path) { + var module = require(path); + for (var i in module) { + classes[i] = module[i]; + } + }); + + // Catch error and return no classes found + try { + classes['BSON'] = require('./bson'); + } catch(err) { + return exports.pure(); + } + + // Return classes list + return classes; +} diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/long.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/long.js new file mode 100644 index 0000000..6f18885 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/long.js @@ -0,0 +1,856 @@ +// 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/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/map.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/map.js new file mode 100644 index 0000000..f53c8c1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/map.js @@ -0,0 +1,126 @@ +"use strict" + +// We have an ES6 Map available, return the native instance +if(typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; +} else { + // We will return a polyfill + var Map = function(array) { + this._keys = []; + this._values = {}; + + for(var i = 0; i < array.length; i++) { + if(array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = {v: value, i: this._keys.length - 1}; + } + } + + Map.prototype.clear = function() { + this._keys = []; + this._values = {}; + } + + Map.prototype.delete = function(key) { + var value = this._values[key]; + if(value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + } + + Map.prototype.entries = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + Map.prototype.forEach = function(callback, self) { + self = self || this; + + for(var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + } + + Map.prototype.get = function(key) { + return this._values[key] ? this._values[key].v : undefined; + } + + Map.prototype.has = function(key) { + return this._values[key] != null; + } + + Map.prototype.keys = function(key) { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + Map.prototype.set = function(key, value) { + if(this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = {v: value, i: this._keys.length - 1}; + return this; + } + + Map.prototype.values = function(key, value) { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable:true, + get: function() { return this._keys.length; } + }); + + module.exports = Map; + module.exports.Map = Map; +} \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js new file mode 100644 index 0000000..03ee9cd --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * 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/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js new file mode 100644 index 0000000..5e120fb --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * 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/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js new file mode 100644 index 0000000..4c2f7cf --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js @@ -0,0 +1,278 @@ +/** + * 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) { + var id; + + if(otherID != null && (otherID instanceof ObjectID || otherID.toHexString)) { + id = otherID.id; + } else if(typeof otherID == 'string' && ObjectID.isValid(otherID)) { + id = ObjectID.createFromHexString(otherID).id; + } else { + return false; + } + + 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(typeof id == 'number') + return true; + if(typeof id == 'string') { + return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id)); + } + return false; +}; + +/** +* @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; diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/parser/calculate_size.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/parser/calculate_size.js new file mode 100644 index 0000000..03513f3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/parser/calculate_size.js @@ -0,0 +1,310 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754 + , readIEEE754 = require('../float_parser').readIEEE754 + , Long = require('../long').Long + , Double = require('../double').Double + , Timestamp = require('../timestamp').Timestamp + , ObjectID = require('../objectid').ObjectID + , Symbol = require('../symbol').Symbol + , BSONRegExp = require('../regexp').BSONRegExp + , Code = require('../code').Code + , MinKey = require('../min_key').MinKey + , MaxKey = require('../max_key').MaxKey + , DBRef = require('../db_ref').DBRef + , Binary = require('../binary').Binary; + +// 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]'; +} + +var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined) + } + } 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, false, ignoreUndefined) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + switch(typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + 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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } + case 'undefined': + if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); + return 0; + case 'boolean': + return (name != null ? (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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? (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 ? (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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + + Buffer.byteLength(value.options, 'utf8') + 1 + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else if(serializeFunctions) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; + } + } + } + + return 0; +} + +var BSON = {}; + +/** + * 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 = {}; + +/** + * 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; + +// 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. + +module.exports = calculateObjectSize; diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/parser/deserializer.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/parser/deserializer.js new file mode 100644 index 0000000..505ea59 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/parser/deserializer.js @@ -0,0 +1,525 @@ +"use strict" + +var readIEEE754 = require('../float_parser').readIEEE754, + f = require('util').format, + 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, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var deserialize = function(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // 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 || buffer.length < size) { + throw new Error("corrupt bson message"); + } + + // Illegal end value + if(buffer[size - 1] != 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index - 4, options, isArray); +} + +var deserializeObject = function(buffer, index, options, isArray) { + 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']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + var raw = options['raw'] == null ? false : options['raw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // 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"); + + // Create holding object + var object = isArray ? [] : {}; + + // 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; + + // 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") + var name = buffer.toString('utf8', index, i); + + index = i + 1; + + if(elementType == BSON.BSON_DATA_STRING) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_OID) { + var string = buffer.toString('binary', index, index + 12); + object[name] = new ObjectID(string); + index = index + 12; + } else if(elementType == BSON.BSON_DATA_INT) { + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } else if(elementType == BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if(elementType == BSON.BSON_DATA_DATE) { + 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; + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if(elementType == BSON.BSON_DATA_BOOLEAN) { + object[name] = buffer[index++] == 1; + } else if(elementType == BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + if(objectSize <= 0 || objectSize > (buffer.length - index)) throw new Error("bad embedded document length in bson"); + + // We have a raw value + if(raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if(elementType == BSON.BSON_DATA_ARRAY) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + var arrayOptions = options; + + // All elements of array to be returned as raw bson + if(fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for(var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + } else if(elementType == BSON.BSON_DATA_UNDEFINED || elementType == BSON.BSON_DATA_NULL) { + object[name] = null; + } else if(elementType == 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; + 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; + } + } else if(elementType == BSON.BSON_DATA_BINARY) { + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + 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; + } + if(promoteBuffers) { + object[name] = buffer.slice(index, index + binarySize); + } else { + 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]; + } + if(promoteBuffers) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + // Update the index + index = index + binarySize; + } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == false) { + // 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") + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // 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") + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // 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('')); + } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == true) { + // 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") + // Return the C string + var source = buffer.toString('utf8', index, i); + index = i + 1; + + // 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") + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if(elementType == BSON.BSON_DATA_SYMBOL) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_TIMESTAMP) { + 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; + object[name] = new Timestamp(lowBits, highBits); + } else if(elementType == BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if(elementType == BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if(elementType == BSON.BSON_DATA_CODE) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + 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 { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_CODE_W_SCOPE) { + 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; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Javascript function + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + var _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 = deserializeObject(buffer, _index, 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 { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; +} + +/** + * 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; +} + +var BSON = {}; + +/** + * 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 = {}; + +/** + * 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; + +// 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. + +module.exports = deserialize diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/parser/serializer.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/parser/serializer.js new file mode 100644 index 0000000..b991aec --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/parser/serializer.js @@ -0,0 +1,912 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754, + readIEEE754 = require('../float_parser').readIEEE754, + Long = require('../long').Long, + Map = require('../map'), + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + BSONRegExp = require('../regexp').BSONRegExp, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + DBRef = require('../db_ref').DBRef, + Binary = require('../binary').Binary; + +var regexp = /\x00/ + +// 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]'; +} + +var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} + +var serializeString = function(buffer, 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; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = (size + 1 >> 24) & 0xff; + buffer[index + 2] = (size + 1 >> 16) & 0xff; + buffer[index + 1] = (size + 1 >> 8) & 0xff; + buffer[index] = size + 1 & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeNumber = function(buffer, 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(buffer, 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(buffer, 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(buffer, 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(buffer, 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; + if (value.source && value.source.match(regexp) != null) { + throw Error("value " + value.source + " must not contain null bytes"); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // 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 serializeBSONRegExp = function(buffer, 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; + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options, index, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +var serializeMinMax = function(buffer, 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(buffer, 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; + + // Write the objectId into the shared buffer + buffer.write(value.id, index, 'binary') + + // Ajust index + return index + 12; +} + +var serializeBuffer = function(buffer, 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(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { + // 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(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + // Write size + var size = endIndex - index; + return endIndex; +} + +var serializeLong = function(buffer, key, value, index) { + // Write the type + buffer[index++] = value._bsontype == '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(buffer, 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 serializeFunction = function(buffer, key, value, index, checkKeys, depth) { + 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.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeCode = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { + 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(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // 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 end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined) + 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(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +} + +var serializeBinary = function(buffer, 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(buffer, 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; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} + +var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions) { + // 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(buffer, { + '$ref': value.namespace + , '$id' : value.oid + , '$db' : value.db + }, false, index, depth + 1, serializeFunctions); + } else { + endIndex = serializeInto(buffer, { + '$ref': value.namespace + , '$id' : value.oid + }, false, index, depth + 1, serializeFunctions); + } + + // 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 serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined) { + 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 value = object[i]; + + // Is there an override value + if(value && value.toBSON) { + if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + var type = typeof value; + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(type == 'undefined' || value == null) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else if(object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while(!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if(done) continue; + + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // 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 (checkKeys) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + // console.log("---------------------------------------------------") + // console.dir("key = " + key) + // console.dir("value = " + value) + + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(value === undefined && ignoreUndefined == true) { + } else if(value === null || value === undefined) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + 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"); + } + + // Iterate over all the keys + for(var key in object) { + var value = object[key]; + // Is there an override value + if(value && value.toBSON) { + if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // 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 (checkKeys) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(value === undefined && ignoreUndefined == true) { + } else if(value === null || value === undefined) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // 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; +} + +var BSON = {}; + +/** + * 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 = {}; + +/** + * 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; + +// 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. + +module.exports = serializeInto; diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/regexp.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/regexp.js new file mode 100644 index 0000000..6b148b2 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/regexp.js @@ -0,0 +1,30 @@ +/** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ +function BSONRegExp(pattern, options) { + if(!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern; + this.options = options; + + // Validate options + for(var i = 0; i < options.length; i++) { + if(!(this.options[i] == 'i' + || this.options[i] == 'm' + || this.options[i] == 'x' + || this.options[i] == 'l' + || this.options[i] == 's' + || this.options[i] == 'u' + )) { + throw new Error('the regular expression options [' + this.options[i] + "] is not supported"); + } + } +} + +module.exports = BSONRegExp; +module.exports.BSONRegExp = BSONRegExp; \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js new file mode 100644 index 0000000..7681a4d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js @@ -0,0 +1,47 @@ +/** + * 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/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js new file mode 100644 index 0000000..7718caf --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js @@ -0,0 +1,856 @@ +// 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/5-2/service/node_modules/mongoose/node_modules/bson/package.json b/5-2/service/node_modules/mongoose/node_modules/bson/package.json new file mode 100644 index 0000000..9ef4e81 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/package.json @@ -0,0 +1,70 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "version": "0.4.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" + }, + "devDependencies": { + "nodeunit": "0.9.0", + "gleak": "0.2.3", + "one": "2.X.X", + "benchmark": "1.0.0", + "colors": "1.1.0" + }, + "config": { + "native": false + }, + "main": "./lib/bson/index", + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.6.19" + }, + "scripts": { + "test": "nodeunit ./test/node" + }, + "browser": "lib/bson/bson.js", + "license": "Apache-2.0", + "gitHead": "d88c87a7924f8d6a8b37366d7b3b39531cad521c", + "homepage": "https://github.com/mongodb/js-bson", + "_id": "bson@0.4.21", + "_shasum": "b8eae38c5aa94f7b8e64e8cfed0f42e58308ed95", + "_from": "bson@0.4.21", + "_npmVersion": "2.14.12", + "_nodeVersion": "4.2.4", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "octave", + "email": "chinsay@gmail.com" + }, + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "b8eae38c5aa94f7b8e64e8cfed0f42e58308ed95", + "tarball": "http://registry.npmjs.org/bson/-/bson-0.4.21.tgz" + }, + "_resolved": "https://registry.npmjs.org/bson/-/bson-0.4.21.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/bson/tools/gleak.js b/5-2/service/node_modules/mongoose/node_modules/bson/tools/gleak.js new file mode 100644 index 0000000..c707cfc --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/bson/tools/gleak.js @@ -0,0 +1,21 @@ + +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/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/.npmignore b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/.npmignore new file mode 100644 index 0000000..96e29a8 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/.npmignore @@ -0,0 +1,2 @@ +**.swp +node_modules diff --git a/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/Makefile b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/Makefile new file mode 100644 index 0000000..1db5d65 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/Makefile @@ -0,0 +1,9 @@ +test: + @NODE_ENV=test ./node_modules/expresso/bin/expresso \ + $(TESTFLAGS) \ + ./test.js + +test-cov: + @TESTFLAGS=--cov $(MAKE) test + +.PHONY: test test-cov diff --git a/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/README.md b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/README.md new file mode 100644 index 0000000..98fe85b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/README.md @@ -0,0 +1,369 @@ +hooks +============ + +Add pre and post middleware hooks to your JavaScript methods. + +## Installation + npm install hooks + +## Motivation +Suppose you have a JavaScript object with a `save` method. + +It would be nice to be able to declare code that runs before `save` and after `save`. +For example, you might want to run validation code before every `save`, +and you might want to dispatch a job to a background job queue after `save`. + +One might have an urge to hard code this all into `save`, but that turns out to +couple all these pieces of functionality (validation, save, and job creation) more +tightly than is necessary. For example, what if someone does not want to do background +job creation after the logical save? + +It is nicer to tack on functionality using what we call `pre` and `post` hooks. These +are functions that you define and that you direct to execute before or after particular +methods. + +## Example +We can use `hooks` to add validation and background jobs in the following way: + +```javascript +var hooks = require('hooks') + , Document = require('./path/to/some/document/constructor'); + +// Add hooks' methods: `hook`, `pre`, and `post` +for (var k in hooks) { + Document[k] = hooks[k]; +} + +// Define a new method that is able to invoke pre and post middleware +Document.hook('save', Document.prototype.save); + +// Define a middleware function to be invoked before 'save' +Document.pre('save', function validate (next) { + // The `this` context inside of `pre` and `post` functions + // is the Document instance + if (this.isValid()) next(); // next() passes control to the next middleware + // or to the target method itself + else next(new Error("Invalid")); // next(error) invokes an error callback +}); + +// Define a middleware function to be invoked after 'save' +Document.post('save', function createJob (next) { + this.sendToBackgroundQueue(); + next(); +}); +``` + +If you already have defined `Document.prototype` methods for which you want pres and posts, +then you do not need to explicitly invoke `Document.hook(...)`. Invoking `Document.pre(methodName, fn)` +or `Document.post(methodName, fn)` will automatically and lazily change `Document.prototype[methodName]` +so that it plays well with `hooks`. An equivalent way to implement the previous example is: + +```javascript +var hooks = require('hooks') + , Document = require('./path/to/some/document/constructor'); + +// Add hooks' methods: `hook`, `pre`, and `post` +for (var k in hooks) { + Document[k] = hooks[k]; +} + +Document.prototype.save = function () { + // ... +}; + +// Define a middleware function to be invoked before 'save' +Document.pre('save', function validate (next) { + // The `this` context inside of `pre` and `post` functions + // is the Document instance + if (this.isValid()) next(); // next() passes control to the next middleware + // or to the target method itself + else next(new Error("Invalid")); // next(error) invokes an error callback +}); + +// Define a middleware function to be invoked after 'save' +Document.post('save', function createJob (next) { + this.sendToBackgroundQueue(); + next(); +}); +``` + +## Pres and Posts as Middleware +We structure pres and posts as middleware to give you maximum flexibility: + +1. You can define **multiple** pres (or posts) for a single method. +2. These pres (or posts) are then executed as a chain of methods. +3. Any functions in this middleware chain can choose to halt the chain's execution by `next`ing an Error from that middleware function. If this occurs, then none of the other middleware in the chain will execute, and the main method (e.g., `save`) will not execute. This is nice, for example, when we don't want a document to save if it is invalid. + +## Defining multiple pres (or posts) +`pre` and `post` are chainable, so you can define multiple via: +```javascript +Document.pre('save', function (next) { + console.log("hello"); + next(); +}).pre('save', function (next) { + console.log("world"); + next(); +}); + +Document.post('save', function (next) { + console.log("hello"); + next(); +}).post('save', function (next) { + console.log("world"); + next(); +}); +``` + +As soon as one pre finishes executing, the next one will be invoked, and so on. + +## Error Handling +You can define a default error handler by passing a 2nd function as the 3rd argument to `hook`: +```javascript +Document.hook('set', function (path, val) { + this[path] = val; +}, function (err) { + // Handler the error here + console.error(err); +}); +``` + +Then, we can pass errors to this handler from a pre or post middleware function: +```javascript +Document.pre('set', function (next, path, val) { + next(new Error()); +}); +``` + +If you do not set up a default handler, then `hooks` makes the default handler that just throws the `Error`. + +The default error handler can be over-rided on a per method invocation basis. + +If the main method that you are surrounding with pre and post middleware expects its last argument to be a function +with callback signature `function (error, ...)`, then that callback becomes the error handler, over-riding the default +error handler you may have set up. + +```javascript +Document.hook('save', function (callback) { + // Save logic goes here + ... +}); + +var doc = new Document(); +doc.save( function (err, saved) { + // We can pass err via `next` in any of our pre or post middleware functions + if (err) console.error(err); + + // Rest of callback logic follows ... +}); +``` + +## Mutating Arguments via Middleware +`pre` and `post` middleware can also accept the intended arguments for the method +they augment. This is useful if you want to mutate the arguments before passing +them along to the next middleware and eventually pass a mutated arguments list to +the main method itself. + +As a simple example, let's define a method `set` that just sets a key, value pair. +If we want to namespace the key, we can do so by adding a `pre` middleware hook +that runs before `set`, alters the arguments by namespacing the `key` argument, and passes them onto `set`: + +```javascript +Document.hook('set', function (key, val) { + this[key] = val; +}); +Document.pre('set', function (next, key, val) { + next('namespace-' + key, val); +}); +var doc = new Document(); +doc.set('hello', 'world'); +console.log(doc.hello); // undefined +console.log(doc['namespace-hello']); // 'world' +``` + +As you can see above, we pass arguments via `next`. + +If you are not mutating the arguments, then you can pass zero arguments +to `next`, and the next middleware function will still have access +to the arguments. + +```javascript +Document.hook('set', function (key, val) { + this[key] = val; +}); +Document.pre('set', function (next, key, val) { + // I have access to key and val here + next(); // We don't need to pass anything to next +}); +Document.pre('set', function (next, key, val) { + // And I still have access to the original key and val here + next(); +}); +``` + +Finally, you can add arguments that downstream middleware can also see: + +```javascript +// Note that in the definition of `set`, there is no 3rd argument, options +Document.hook('set', function (key, val) { + // But... + var options = arguments[2]; // ...I have access to an options argument + // because of pre function pre2 (defined below) + console.log(options); // '{debug: true}' + this[key] = val; +}); +Document.pre('set', function pre1 (next, key, val) { + // I only have access to key and val arguments + console.log(arguments.length); // 3 + next(key, val, {debug: true}); +}); +Document.pre('set', function pre2 (next, key, val, options) { + console.log(arguments.length); // 4 + console.log(options); // '{ debug: true}' + next(); +}); +Document.pre('set', function pre3 (next, key, val, options) { + // I still have access to key, val, AND the options argument introduced via the preceding middleware + console.log(arguments.length); // 4 + console.log(options); // '{ debug: true}' + next(); +}); + +var doc = new Document() +doc.set('hey', 'there'); +``` + +## Post middleware + +Post middleware intercepts the callback originally sent to the asynchronous function you have hooked to. + +This means that the following chain of execution will occur in a typical `save` operation: + +(1) doc.save -> (2) pre --(next)--> (3) save calls back -> (4) post --(next)--> (5) targetFn + +Illustrated below: + +``` +Document.pre('save', function (next) { + this.key = "value"; + next(); +}); +// Post handler occurs before `set` calls back. This is useful if we need to grab something +// async before `set` finishes. +Document.post('set', function (next) { + var me = this; + getSomethingAsync(function(value){ // let's assume it returns "Hello Async" + me.key2 = value; + next(); + }); +}); + +var doc = new Document(); +doc.save(function(err){ + console.log(this.key); // "value" - this value was saved + console.log(this.key2); // "Hello Async" - this value was *not* saved +} + +``` + +Post middleware must call `next()` or execution will stop. + +## Parallel `pre` middleware + +All middleware up to this point has been "serial" middleware -- i.e., middleware whose logic +is executed as a serial chain. + +Some scenarios call for parallel middleware -- i.e., middleware that can wait for several +asynchronous services at once to respond. + +For instance, you may only want to save a Document only after you have checked +that the Document is valid according to two different remote services. + +We accomplish asynchronous middleware by adding a second kind of flow control callback +(the only flow control callback so far has been `next`), called `done`. + +- `next` passes control to the next middleware in the chain +- `done` keeps track of how many parallel middleware have invoked `done` and passes + control to the target method when ALL parallel middleware have invoked `done`. If + you pass an `Error` to `done`, then the error is handled, and the main method that is + wrapped by pres and posts will not get invoked. + +We declare pre middleware that is parallel by passing a 3rd boolean argument to our `pre` +definition method. + +We illustrate via the parallel validation example mentioned above: + +```javascript +Document.hook('save', function targetFn (callback) { + // Save logic goes here + // ... + // This only gets run once the two `done`s are both invoked via preOne and preTwo. +}); + + // true marks this as parallel middleware +Document.pre('save', true, function preOne (next, doneOne, callback) { + remoteServiceOne.validate(this.serialize(), function (err, isValid) { + // The code in here will probably be run after the `next` below this block + // and could possibly be run after the console.log("Hola") in `preTwo + if (err) return doneOne(err); + if (isValid) doneOne(); + }); + next(); // Pass control to the next middleware +}); + +// We will suppose that we need 2 different remote services to validate our document +Document.pre('save', true, function preTwo (next, doneTwo, callback) { + remoteServiceTwo.validate(this.serialize(), function (err, isValid) { + if (err) return doneTwo(err); + if (isValid) doneTwo(); + }); + next(); +}); + +// While preOne and preTwo are parallel, preThree is a serial pre middleware +Document.pre('save', function preThree (next, callback) { + next(); +}); + +var doc = new Document(); +doc.save( function (err, doc) { + // Do stuff with the saved doc here... +}); +``` + +In the above example, flow control may happen in the following way: + +(1) doc.save -> (2) preOne --(next)--> (3) preTwo --(next)--> (4) preThree --(next)--> (wait for dones to invoke) -> (5) doneTwo -> (6) doneOne -> (7) targetFn + +So what's happening is that: + +1. You call `doc.save(...)` +2. First, your preOne middleware gets executed. It makes a remote call to the validation service and `next()`s to the preTwo middleware. +3. Now, your preTwo middleware gets executed. It makes a remote call to another validation service and `next()`s to the preThree middleware. +4. Your preThree middleware gets executed. It immediately `next()`s. But nothing else gets executing until both `doneOne` and `doneTwo` are invoked inside the callbacks handling the response from the two valiation services. +5. We will suppose that validation remoteServiceTwo returns a response to us first. In this case, we call `doneTwo` inside the callback to remoteServiceTwo. +6. Some fractions of a second later, remoteServiceOne returns a response to us. In this case, we call `doneOne` inside the callback to remoteServiceOne. +7. `hooks` implementation keeps track of how many parallel middleware has been defined per target function. It detects that both asynchronous pre middlewares (`preOne` and `preTwo`) have finally called their `done` functions (`doneOne` and `doneTwo`), so the implementation finally invokes our `targetFn` (i.e., our core `save` business logic). + +## Removing Pres + +You can remove a particular pre associated with a hook: + + Document.pre('set', someFn); + Document.removePre('set', someFn); + +And you can also remove all pres associated with a hook: + Document.removePre('set'); // Removes all declared `pre`s on the hook 'set' + +## Tests +To run the tests: + make test + +### Contributors +- [Brian Noguchi](https://github.com/bnoguchi) + +### License +MIT License + +--- +### Author +Brian Noguchi diff --git a/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/hooks.alt.js b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/hooks.alt.js new file mode 100644 index 0000000..6ced357 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/hooks.alt.js @@ -0,0 +1,134 @@ +/** + * Hooks are useful if we want to add a method that automatically has `pre` and `post` hooks. + * For example, it would be convenient to have `pre` and `post` hooks for `save`. + * _.extend(Model, mixins.hooks); + * Model.hook('save', function () { + * console.log('saving'); + * }); + * Model.pre('save', function (next, done) { + * console.log('about to save'); + * next(); + * }); + * Model.post('save', function (next, done) { + * console.log('saved'); + * next(); + * }); + * + * var m = new Model(); + * m.save(); + * // about to save + * // saving + * // saved + */ + +// TODO Add in pre and post skipping options +module.exports = { + /** + * Declares a new hook to which you can add pres and posts + * @param {String} name of the function + * @param {Function} the method + * @param {Function} the error handler callback + */ + hook: function (name, fn, err) { + if (arguments.length === 1 && typeof name === 'object') { + for (var k in name) { // `name` is a hash of hookName->hookFn + this.hook(k, name[k]); + } + return; + } + + if (!err) err = fn; + + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {} + , posts = proto._posts = proto._posts || {}; + pres[name] = pres[name] || []; + posts[name] = posts[name] || []; + + function noop () {} + + proto[name] = function () { + var self = this + , pres = this._pres[name] + , posts = this._posts[name] + , numAsyncPres = 0 + , hookArgs = [].slice.call(arguments) + , preChain = pres.map( function (pre, i) { + var wrapper = function () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (numAsyncPres) { + // arguments[1] === asyncComplete + if (arguments.length) + hookArgs = [].slice.call(arguments, 2); + pre.apply(self, + [ preChain[i+1] || allPresInvoked, + asyncComplete + ].concat(hookArgs) + ); + } else { + if (arguments.length) + hookArgs = [].slice.call(arguments); + pre.apply(self, + [ preChain[i+1] || allPresDone ].concat(hookArgs)); + } + }; // end wrapper = function () {... + if (wrapper.isAsync = pre.isAsync) + numAsyncPres++; + return wrapper; + }); // end posts.map(...) + function allPresInvoked () { + if (arguments[0] instanceof Error) + err(arguments[0]); + } + + function allPresDone () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (arguments.length) + hookArgs = [].slice.call(arguments); + fn.apply(self, hookArgs); + var postChain = posts.map( function (post, i) { + var wrapper = function () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (arguments.length) + hookArgs = [].slice.call(arguments); + post.apply(self, + [ postChain[i+1] || noop].concat(hookArgs)); + }; // end wrapper = function () {... + return wrapper; + }); // end posts.map(...) + if (postChain.length) postChain[0](); + } + + if (numAsyncPres) { + complete = numAsyncPres; + function asyncComplete () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + --complete || allPresDone.call(this); + } + } + (preChain[0] || allPresDone)(); + }; + + return this; + }, + + pre: function (name, fn, isAsync) { + var proto = this.prototype + , pres = proto._pres = proto._pres || {}; + if (fn.isAsync = isAsync) { + this.prototype[name].numAsyncPres++; + } + (pres[name] = pres[name] || []).push(fn); + return this; + }, + post: function (name, fn, isAsync) { + var proto = this.prototype + , posts = proto._posts = proto._posts || {}; + (posts[name] = posts[name] || []).push(fn); + return this; + } +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/hooks.js b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/hooks.js new file mode 100644 index 0000000..756c833 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/hooks.js @@ -0,0 +1,191 @@ +// TODO Add in pre and post skipping options +module.exports = { + /** + * Declares a new hook to which you can add pres and posts + * @param {String} name of the function + * @param {Function} the method + * @param {Function} the error handler callback + */ + hook: function (name, fn, errorCb) { + if (arguments.length === 1 && typeof name === 'object') { + for (var k in name) { // `name` is a hash of hookName->hookFn + this.hook(k, name[k]); + } + return; + } + + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {} + , posts = proto._posts = proto._posts || {}; + pres[name] = pres[name] || []; + posts[name] = posts[name] || []; + + proto[name] = function () { + var self = this + , hookArgs // arguments eventually passed to the hook - are mutable + , lastArg = arguments[arguments.length-1] + , pres = this._pres[name] + , posts = this._posts[name] + , _total = pres.length + , _current = -1 + , _asyncsLeft = proto[name].numAsyncPres + , _asyncsDone = function(err) { + if (err) { + return handleError(err); + } + --_asyncsLeft || _done.apply(self, hookArgs); + } + , handleError = function(err) { + if ('function' == typeof lastArg) + return lastArg(err); + if (errorCb) return errorCb.call(self, err); + throw err; + } + , _next = function () { + if (arguments[0] instanceof Error) { + return handleError(arguments[0]); + } + var _args = Array.prototype.slice.call(arguments) + , currPre + , preArgs; + if (_args.length && !(arguments[0] == null && typeof lastArg === 'function')) + hookArgs = _args; + if (++_current < _total) { + currPre = pres[_current] + if (currPre.isAsync && currPre.length < 2) + throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)"); + if (currPre.length < 1) + throw new Error("Your pre must have a next argument -- e.g., function (next, ...)"); + preArgs = (currPre.isAsync + ? [once(_next), once(_asyncsDone)] + : [once(_next)]).concat(hookArgs); + return currPre.apply(self, preArgs); + } else if (!_asyncsLeft) { + return _done.apply(self, hookArgs); + } + } + , _done = function () { + var args_ = Array.prototype.slice.call(arguments) + , ret, total_, current_, next_, done_, postArgs; + + if (_current === _total) { + + next_ = function () { + if (arguments[0] instanceof Error) { + return handleError(arguments[0]); + } + var args_ = Array.prototype.slice.call(arguments, 1) + , currPost + , postArgs; + if (args_.length) hookArgs = args_; + if (++current_ < total_) { + currPost = posts[current_] + if (currPost.length < 1) + throw new Error("Your post must have a next argument -- e.g., function (next, ...)"); + postArgs = [once(next_)].concat(hookArgs); + return currPost.apply(self, postArgs); + } else if (typeof lastArg === 'function'){ + // All post handlers are done, call original callback function + return lastArg.apply(self, arguments); + } + }; + + // We are assuming that if the last argument provided to the wrapped function is a function, it was expecting + // a callback. We trap that callback and wait to call it until all post handlers have finished. + if(typeof lastArg === 'function'){ + args_[args_.length - 1] = once(next_); + } + + total_ = posts.length; + current_ = -1; + ret = fn.apply(self, args_); // Execute wrapped function, post handlers come afterward + + if (total_ && typeof lastArg !== 'function') return next_(); // no callback provided, execute next_() manually + return ret; + } + }; + + return _next.apply(this, arguments); + }; + + proto[name].numAsyncPres = 0; + + return this; + }, + + pre: function (name, isAsync, fn, errorCb) { + if ('boolean' !== typeof arguments[1]) { + errorCb = fn; + fn = isAsync; + isAsync = false; + } + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {}; + + this._lazySetupHooks(proto, name, errorCb); + + if (fn.isAsync = isAsync) { + proto[name].numAsyncPres++; + } + + (pres[name] = pres[name] || []).push(fn); + return this; + }, + post: function (name, isAsync, fn) { + if (arguments.length === 2) { + fn = isAsync; + isAsync = false; + } + var proto = this.prototype || this + , posts = proto._posts = proto._posts || {}; + + this._lazySetupHooks(proto, name); + (posts[name] = posts[name] || []).push(fn); + return this; + }, + removePre: function (name, fnToRemove) { + var proto = this.prototype || this + , pres = proto._pres || (proto._pres || {}); + if (!pres[name]) return this; + if (arguments.length === 1) { + // Remove all pre callbacks for hook `name` + pres[name].length = 0; + } else { + pres[name] = pres[name].filter( function (currFn) { + return currFn !== fnToRemove; + }); + } + return this; + }, + removePost: function (name, fnToRemove) { + var proto = this.prototype || this + , posts = proto._posts || (proto._posts || {}); + if (!posts[name]) return this; + if (arguments.length === 1) { + // Remove all post callbacks for hook `name` + posts[name].length = 0; + } else { + posts[name] = posts[name].filter( function (currFn) { + return currFn !== fnToRemove; + }); + } + return this; + }, + + _lazySetupHooks: function (proto, methodName, errorCb) { + if ('undefined' === typeof proto[methodName].numAsyncPres) { + this.hook(methodName, proto[methodName], errorCb); + } + } +}; + +function once (fn, scope) { + return function fnWrapper () { + if (fnWrapper.hookCalled) return; + fnWrapper.hookCalled = true; + var ret = fn.apply(scope, arguments); + if (ret && ret.then) { + ret.then(function() {}, function() {}); + } + }; +} diff --git a/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/package.json b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/package.json new file mode 100644 index 0000000..c02444a --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/package.json @@ -0,0 +1,66 @@ +{ + "name": "hooks-fixed", + "description": "Adds pre and post hook functionality to your JavaScript methods.", + "version": "1.1.0", + "keywords": [ + "node", + "hooks", + "middleware", + "pre", + "post" + ], + "homepage": "https://github.com/vkarpov15/hooks-fixed/", + "repository": { + "type": "git", + "url": "git://github.com/vkarpov15/hooks-fixed.git" + }, + "author": { + "name": "Brian Noguchi", + "email": "brian.noguchi@gmail.com", + "url": "https://github.com/bnoguchi/" + }, + "main": "./hooks.js", + "directories": { + "lib": "." + }, + "scripts": { + "test": "make test" + }, + "dependencies": {}, + "devDependencies": { + "expresso": ">=0.7.6", + "should": ">=0.2.1", + "underscore": ">=1.1.4" + }, + "engines": { + "node": ">=0.4.0" + }, + "licenses": [ + "MIT" + ], + "optionalDependencies": {}, + "gitHead": "17ef258ae58d7aa6de7cec5b57f76233a4ba1c96", + "bugs": { + "url": "https://github.com/vkarpov15/hooks-fixed/issues" + }, + "_id": "hooks-fixed@1.1.0", + "_shasum": "0e8c15336708e6611185fe390b44687dd5230dbb", + "_from": "hooks-fixed@1.1.0", + "_npmVersion": "2.9.1", + "_nodeVersion": "0.12.3", + "_npmUser": { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + "dist": { + "shasum": "0e8c15336708e6611185fe390b44687dd5230dbb", + "tarball": "http://registry.npmjs.org/hooks-fixed/-/hooks-fixed-1.1.0.tgz" + }, + "maintainers": [ + { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + } + ], + "_resolved": "https://registry.npmjs.org/hooks-fixed/-/hooks-fixed-1.1.0.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/test.js b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/test.js new file mode 100644 index 0000000..81ad79e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/hooks-fixed/test.js @@ -0,0 +1,786 @@ +var hooks = require('./hooks') + , should = require('should') + , assert = require('assert') + , _ = require('underscore'); + +// TODO Add in test for making sure all pres get called if pre is defined directly on an instance. +// TODO Test for calling `done` twice or `next` twice in the same function counts only once +module.exports = { + 'should be able to assign multiple hooks at once': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook({ + hook1: function (a) {}, + hook2: function (b) {} + }); + var a = new A(); + assert.equal(typeof a.hook1, 'function'); + assert.equal(typeof a.hook2, 'function'); + }, + 'should run without pres and posts when not present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + }, + 'should run with pres when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValue.should.equal(2); + }, + 'should run with posts when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.value = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(2); + }, + 'should run pres and posts when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + A.post('save', function (next) { + this.value = 3; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(3); + a.preValue.should.equal(2); + }, + 'should run posts after pres': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.override = 100; + next(); + }); + A.post('save', function (next) { + this.override = 200; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.override.should.equal(200); + }, + 'should not run a hook if a pre fails': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function () { + this.value = 1; + }, function (err) { + counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + counter.should.equal(1); + assert.equal(typeof a.value, 'undefined'); + }, + 'should be able to run multiple pres': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.v1 = 1; + next(); + }).pre('save', function (next) { + this.v2 = 2; + next(); + }); + var a = new A(); + a.save(); + a.v1.should.equal(1); + a.v2.should.equal(2); + }, + 'should run multiple pres until a pre fails and not call the hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }, function (err) {}); + A.pre('save', function (next) { + this.v1 = 1; + next(); + }).pre('save', function (next) { + next(new Error()); + }).pre('save', function (next) { + this.v3 = 3; + next(); + }); + var a = new A(); + a.save(); + a.v1.should.equal(1); + assert.equal(typeof a.v3, 'undefined'); + assert.equal(typeof a.value, 'undefined'); + }, + 'should be able to run multiple posts': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.value = 2; + next(); + }).post('save', function (next) { + this.value = 3.14; + next(); + }).post('save', function (next) { + this.v3 = 3; + next(); + }); + var a = new A(); + a.save(); + assert.equal(a.value, 3.14); + assert.equal(a.v3, 3); + }, + 'should run only posts up until an error': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }, function (err) {}); + A.post('save', function (next) { + this.value = 2; + next(); + }).post('save', function (next) { + this.value = 3; + next(new Error()); + }).post('save', function (next) { + this.value = 4; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(3); + }, + "should fall back first to the hook method's last argument as the error handler if it is a function of arity 1 or 2": function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (callback) { + this.value = 1; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save( function (err) { + if (err instanceof Error) counter++; + }); + counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'should fall back second to the default error handler if specified': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (callback) { + this.value = 1; + }, function (err) { + if (err instanceof Error) counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'fallback default error handler should scope to the object': function () { + var A = function () { + this.counter = 0; + }; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (callback) { + this.value = 1; + }, function (err) { + if (err instanceof Error) this.counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + a.counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'should fall back last to throwing the error': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (err) { + if (err instanceof Error) return counter++; + this.value = 1; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + var didCatch = false; + try { + a.save(); + } catch (e) { + didCatch = true; + e.should.be.an.instanceof(Error); + counter.should.equal(0); + assert.equal(typeof a.value, 'undefined'); + } + didCatch.should.be.true; + }, + "should proceed without mutating arguments if `next(null|undefined)` is called in a serial pre, and the last argument of the target method is a callback with node-like signature function (err, obj) {...} or function (err) {...}": function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.prototype.save = function (callback) { + this.value = 1; + callback(); + }; + A.pre('save', function (next) { + next(null); + }); + A.pre('save', function (next) { + next(undefined); + }); + var a = new A(); + a.save( function (err) { + if (err instanceof Error) counter++; + else counter--; + }); + counter.should.equal(-1); + a.value.should.eql(1); + }, + "should proceed with mutating arguments if `next(null|undefined)` is callback in a serial pre, and the last argument of the target method is not a function": function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.set = function (v) { + this.value = v; + }; + A.pre('set', function (next) { + next(undefined); + }); + A.pre('set', function (next) { + next(null); + }); + var a = new A(); + a.set(1); + should.strictEqual(null, a.value); + }, + 'should not run any posts if a pre fails': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 2; + }, function (err) {}); + A.pre('save', function (next) { + this.value = 1; + next(new Error()); + }).post('save', function (next) { + this.value = 3; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + }, + + "can pass the hook's arguments verbatim to pres": function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + }); + A.pre('set', function (next, path, val) { + path.should.equal('hello'); + val.should.equal('world'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + a.hello.should.equal('world'); + }, +// "can pass the hook's arguments as an array to pres": function () { +// // Great for dynamic arity - e.g., slice(...) +// var A = function () {}; +// _.extend(A, hooks); +// A.hook('set', function (path, val) { +// this[path] = val; +// }); +// A.pre('set', function (next, hello, world) { +// hello.should.equal('hello'); +// world.should.equal('world'); +// next(); +// }); +// var a = new A(); +// a.set('hello', 'world'); +// assert.equal(a.hello, 'world'); +// }, + "can pass the hook's arguments verbatim to posts": function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + }); + A.post('set', function (next, path, val) { + path.should.equal('hello'); + val.should.equal('world'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(a.hello, 'world'); + }, +// "can pass the hook's arguments as an array to posts": function () { +// var A = function () {}; +// _.extend(A, hooks); +// A.hook('set', function (path, val) { +// this[path] = val; +// }); +// A.post('set', function (next, halt, args) { +// assert.equal(args[0], 'hello'); +// assert.equal(args[1], 'world'); +// next(); +// }); +// var a = new A(); +// a.set('hello', 'world'); +// assert.equal(a.hello, 'world'); +// }, + "pres should be able to modify and pass on a modified version of the hook's arguments": function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + assert.equal(arguments[2], 'optional'); + }); + A.pre('set', function (next, path, val) { + next('foo', 'bar'); + }); + A.pre('set', function (next, path, val) { + assert.equal(path, 'foo'); + assert.equal(val, 'bar'); + next('rock', 'says', 'optional'); + }); + A.pre('set', function (next, path, val, opt) { + assert.equal(path, 'rock'); + assert.equal(val, 'says'); + assert.equal(opt, 'optional'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(typeof a.hello, 'undefined'); + a.rock.should.equal('says'); + }, + 'posts should see the modified version of arguments if the pres modified them': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + }); + A.pre('set', function (next, path, val) { + next('foo', 'bar'); + }); + A.post('set', function (next, path, val) { + path.should.equal('foo'); + val.should.equal('bar'); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(typeof a.hello, 'undefined'); + a.foo.should.equal('bar'); + }, + 'should pad missing arguments (relative to expected arguments of the hook) with null': function () { + // Otherwise, with hookFn = function (a, b, next, ), + // if we use hookFn(a), then because the pre functions are of the form + // preFn = function (a, b, next, ), then it actually gets executed with + // preFn(a, next, ), so when we call next() from within preFn, we are actually + // calling () + + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val, opts) { + this[path] = val; + }); + A.pre('set', function (next, path, val, opts) { + next('foo', 'bar'); + assert.equal(typeof opts, 'undefined'); + }); + var a = new A(); + a.set('hello', 'world'); + }, + + 'should not invoke the target method until all asynchronous middleware have invoked dones': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + counter++; + this[path] = val; + counter.should.equal(7); + }); + A.pre('set', function (next, path, val) { + counter++; + next(); + }); + A.pre('set', true, function (next, done, path, val) { + counter++; + setTimeout(function () { + counter++; + done(); + }, 1000); + next(); + }); + A.pre('set', function (next, path, val) { + counter++; + next(); + }); + A.pre('set', true, function (next, done, path, val) { + counter++; + setTimeout(function () { + counter++; + done(); + }, 500); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + }, + + 'invoking a method twice should run its async middleware twice': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + if (path === 'hello') counter.should.equal(1); + if (path === 'foo') counter.should.equal(2); + }); + A.pre('set', true, function (next, done, path, val) { + setTimeout(function () { + counter++; + done(); + }, 1000); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + a.set('foo', 'bar'); + }, + + 'calling the same done multiple times should have the effect of only calling it once': function () { + var A = function () { + this.acked = false; + }; + _.extend(A, hooks); + A.hook('ack', function () { + console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); + this.acked = true; + }); + A.pre('ack', true, function (next, done) { + next(); + done(); + done(); + }); + A.pre('ack', true, function (next, done) { + next(); + // Notice that done() is not invoked here + }); + var a = new A(); + a.ack(); + setTimeout( function () { + a.acked.should.be.false; + }, 1000); + }, + + 'calling the same next multiple times should have the effect of only calling it once': function (beforeExit) { + var A = function () { + this.acked = false; + }; + _.extend(A, hooks); + A.hook('ack', function () { + console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); + this.acked = true; + }); + A.pre('ack', function (next) { + // force a throw to re-exec next() + try { + next(new Error('bam')); + } catch (err) { + next(); + } + }); + A.pre('ack', function (next) { + next(); + }); + var a = new A(); + a.ack(); + beforeExit( function () { + a.acked.should.be.false; + }); + }, + + 'asynchronous middleware should be able to pass an error via `done`, stopping the middleware chain': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val, fn) { + counter++; + this[path] = val; + fn(null); + }); + A.pre('set', true, function (next, done, path, val, fn) { + setTimeout(function () { + counter++; + done(new Error); + }, 1000); + next(); + }); + var a = new A(); + a.set('hello', 'world', function (err) { + err.should.be.an.instanceof(Error); + should.strictEqual(undefined, a['hello']); + counter.should.eql(1); + }); + }, + + 'should be able to remove a particular pre': function () { + var A = function () {} + , preTwo; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValueOne = 2; + next(); + }); + A.pre('save', preTwo = function (next) { + this.preValueTwo = 4; + next(); + }); + A.removePre('save', preTwo); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValueOne.should.equal(2); + should.strictEqual(undefined, a.preValueTwo); + }, + + 'should be able to remove all pres associated with a hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValueOne = 2; + next(); + }); + A.pre('save', function (next) { + this.preValueTwo = 4; + next(); + }); + A.removePre('save'); + var a = new A(); + a.save(); + a.value.should.equal(1); + should.strictEqual(undefined, a.preValueOne); + should.strictEqual(undefined, a.preValueTwo); + }, + + 'should be able to remove a particular post': function () { + var A = function () {} + , postTwo; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.postValueOne = 2; + next(); + }); + A.post('save', postTwo = function (next) { + this.postValueTwo = 4; + next(); + }); + A.removePost('save', postTwo); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.postValueOne.should.equal(2); + should.strictEqual(undefined, a.postValueTwo); + }, + + 'should be able to remove all posts associated with a hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.postValueOne = 2; + next(); + }); + A.post('save', function (next) { + this.postValueTwo = 4; + next(); + }); + A.removePost('save'); + var a = new A(); + a.save(); + a.value.should.equal(1); + should.strictEqual(undefined, a.postValueOne); + should.strictEqual(undefined, a.postValueTwo); + }, + + '#pre should lazily make a method hookable': function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValue.should.equal(2); + }, + + '#pre lazily making a method hookable should be able to provide a default errorHandler as the last argument': function () { + var A = function () {}; + var preValue = ""; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.pre('save', function (next) { + next(new Error); + }, function (err) { + preValue = 'ERROR'; + }); + var a = new A(); + a.save(); + should.strictEqual(undefined, a.value); + preValue.should.equal('ERROR'); + }, + + '#post should lazily make a method hookable': function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.post('save', function (next) { + this.value = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(2); + }, + + "a lazy hooks setup should handle errors via a method's last argument, if it's a callback": function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function (fn) {}; + A.pre('save', function (next) { + next(new Error("hi there")); + }); + var a = new A(); + a.save( function (err) { + err.should.be.an.instanceof(Error); + }); + }, + + 'should intercept method callbacks for post handlers': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function (val, callback) { + this.value = val; + callback(); + }); + A.post('save', function (next) { + assert.equal(a.value, 2); + this.value += 2; + setTimeout(next, 10); + }).post('save', function (next) { + assert.equal(a.value, 4); + this.value += 3; + setTimeout(next, 10); + }).post('save', function (next) { + assert.equal(a.value, 7); + this.value2 = 3; + setTimeout(next, 10); + }); + var a = new A(); + a.save(2, function(){ + assert.equal(a.value, 7); + assert.equal(a.value2, 3); + }); + }, + + 'should handle parallel followed by serial': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function (val, callback) { + this.value = val; + callback(); + }); + A.pre('save', true, function(next, done) { + process.nextTick(function() { + done(); + }); + next(); + }).pre('save', function(done) { + process.nextTick(function() { + done(); + }); + }); + var a = new A(); + a.save(2, function(){ + assert.ok(true); + }); + } +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/.npmignore b/5-2/service/node_modules/mongoose/node_modules/kareem/.npmignore new file mode 100644 index 0000000..59d842b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/.npmignore @@ -0,0 +1,28 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Commenting this out is preferred by some people, see +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- +node_modules + +# Users Environment Variables +.lock-wscript diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/.travis.yml b/5-2/service/node_modules/mongoose/node_modules/kareem/.travis.yml new file mode 100644 index 0000000..9aa8222 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "0.12" + - "0.10" + - "iojs" +script: "npm run-script test-travis" +after_script: "npm install coveralls@2.10.0 && cat ./coverage/lcov.info | coveralls" diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/LICENSE b/5-2/service/node_modules/mongoose/node_modules/kareem/LICENSE new file mode 100644 index 0000000..e06d208 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/LICENSE @@ -0,0 +1,202 @@ +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/5-2/service/node_modules/mongoose/node_modules/kareem/Makefile b/5-2/service/node_modules/mongoose/node_modules/kareem/Makefile new file mode 100644 index 0000000..f71ba90 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/Makefile @@ -0,0 +1,5 @@ +docs: + node ./docs.js + +coverage: + ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/* diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/README.md b/5-2/service/node_modules/mongoose/node_modules/kareem/README.md new file mode 100644 index 0000000..7d2dc84 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/README.md @@ -0,0 +1,379 @@ +# kareem + + [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem) + [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem) + +Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, meant to offer additional flexibility in allowing you to execute hooks whenever necessary, as opposed to simply wrapping a single function. + +Named for the NBA's all-time leading scorer Kareem Abdul-Jabbar, known for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook) + + + +# API + +## pre hooks + +Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define +pre and post hooks: pre hooks are called before a given function executes. +Unlike hooks, kareem stores hooks and other internal state in a separate +object, rather than relying on inheritance. Furthermore, kareem exposes +an `execPre()` function that allows you to execute your pre hooks when +appropriate, giving you more fine-grained control over your function hooks. + + +#### It runs without any hooks specified + +```javascript + + hooks.execPre('cook', null, function() { + done(); + }); + +``` + +#### It runs basic serial pre hooks + +pre hook functions take one parameter, a "done" function that you execute +when your pre hook is finished. + + +```javascript + + var count = 0; + + hooks.pre('cook', function(done) { + ++count; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count); + done(); + }); + +``` + +#### It can run multipe pre hooks + +```javascript + + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function(done) { + ++count1; + done(); + }); + + hooks.pre('cook', function(done) { + ++count2; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + +``` + +#### It can run fully synchronous pre hooks + +If your pre hook function takes no parameters, its assumed to be +fully synchronous. + + +```javascript + + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function() { + ++count1; + }); + + hooks.pre('cook', function() { + ++count2; + }); + + hooks.execPre('cook', null, function(error) { + assert.equal(null, error); + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + +``` + +#### It properly attaches context to pre hooks + +Pre save hook functions are bound to the second parameter to `execPre()` + + +```javascript + + hooks.pre('cook', function(done) { + this.bacon = 3; + done(); + }); + + hooks.pre('cook', function(done) { + this.eggs = 4; + done(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + // In the pre hooks, `this` will refer to `obj` + hooks.execPre('cook', obj, function(error) { + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + done(); + }); + +``` + +#### It can execute parallel (async) pre hooks + +Like the hooks module, you can declare "async" pre hooks - these take two +parameters, the functions `next()` and `done()`. `next()` passes control to +the next pre hook, but the underlying function won't be called until all +async pre hooks have called `done()`. + + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + done(); + }); + +``` + +## post hooks + +#### It runs without any hooks specified + +```javascript + + hooks.execPost('cook', null, [1], function(error, eggs) { + assert.ifError(error); + assert.equal(1, eggs); + done(); + }); + +``` + +#### It executes with parameters passed in + +```javascript + + hooks.post('cook', function(eggs, bacon, callback) { + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + +``` + +#### It can use synchronous post hooks + +```javascript + + var execed = {}; + + hooks.post('cook', function(eggs, bacon) { + execed.first = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + }); + + hooks.post('cook', function(eggs, bacon, callback) { + execed.second = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + +``` + +## wrap() + +#### It wraps pre and post calls into one call + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.ifError(error); + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj, + args); + +``` + +## createWrapper() + +#### It wraps wrap() into a callable function + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var cook = hooks.createWrapper( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj); + + cook(obj, function(error, result) { + assert.ifError(error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + +``` + +## clone() + +#### It clones a Kareem object + +```javascript + + var k1 = new Kareem(); + k1.pre('cook', function() {}); + k1.post('cook', function() {}); + + var k2 = k1.clone(); + assert.deepEqual(['cook'], Object.keys(k2._pres)); + assert.deepEqual(['cook'], Object.keys(k2._posts)); + +``` + diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/docs.js b/5-2/service/node_modules/mongoose/node_modules/kareem/docs.js new file mode 100644 index 0000000..4a8d4c8 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/docs.js @@ -0,0 +1,37 @@ +var acquit = require('acquit'); + +var content = require('fs').readFileSync('./test/examples.test.js').toString(); +var blocks = acquit.parse(content); + +var mdOutput = + '# kareem\n\n' + + ' [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem)\n' + + ' [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem)\n\n' + + 'Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, ' + + 'meant to offer additional flexibility in allowing you to execute hooks ' + + 'whenever necessary, as opposed to simply wrapping a single function.\n\n' + + 'Named for the NBA\'s all-time leading scorer Kareem Abdul-Jabbar, known ' + + 'for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook)\n\n' + + '\n\n' + + '# API\n\n'; + +for (var i = 0; i < blocks.length; ++i) { + var describe = blocks[i]; + mdOutput += '## ' + describe.contents + '\n\n'; + mdOutput += describe.comments[0] ? + acquit.trimEachLine(describe.comments[0]) + '\n\n' : + ''; + + for (var j = 0; j < describe.blocks.length; ++j) { + var it = describe.blocks[j]; + mdOutput += '#### It ' + it.contents + '\n\n'; + mdOutput += it.comments[0] ? + acquit.trimEachLine(it.comments[0]) + '\n\n' : + ''; + mdOutput += '```javascript\n'; + mdOutput += ' ' + it.code + '\n'; + mdOutput += '```\n\n'; + } +} + +require('fs').writeFileSync('README.md', mdOutput); diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/gulpfile.js b/5-2/service/node_modules/mongoose/node_modules/kareem/gulpfile.js new file mode 100644 index 0000000..635bfc7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/gulpfile.js @@ -0,0 +1,18 @@ +var gulp = require('gulp'); +var mocha = require('gulp-mocha'); +var config = require('./package.json'); +var jscs = require('gulp-jscs'); + +gulp.task('mocha', function() { + return gulp.src('./test/*'). + pipe(mocha({ reporter: 'dot' })); +}); + +gulp.task('jscs', function() { + return gulp.src('./index.js'). + pipe(jscs(config.jscsConfig)); +}); + +gulp.task('watch', function() { + gulp.watch('./index.js', ['jscs', 'mocha']); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/index.js b/5-2/service/node_modules/mongoose/node_modules/kareem/index.js new file mode 100644 index 0000000..b4b071b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/index.js @@ -0,0 +1,229 @@ +'use strict'; + +function Kareem() { + this._pres = {}; + this._posts = {}; +} + +Kareem.prototype.execPre = function(name, context, callback) { + var pres = this._pres[name] || []; + var numPres = pres.length; + var numAsyncPres = pres.numAsync || 0; + var currentPre = 0; + var asyncPresLeft = numAsyncPres; + var done = false; + + if (!numPres) { + return process.nextTick(function() { + callback(null); + }); + } + + var next = function() { + if (currentPre >= numPres) { + return; + } + var pre = pres[currentPre]; + + if (pre.isAsync) { + pre.fn.call( + context, + function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + ++currentPre; + next.apply(context, arguments); + }, + function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + if (--numAsyncPres === 0) { + return callback(null); + } + }); + } else if (pre.fn.length > 0) { + var args = [function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return callback(null); + } + } + + next.apply(context, arguments); + }]; + if (arguments.length >= 2) { + for (var i = 1; i < arguments.length; ++i) { + args.push(arguments[i]); + } + } + pre.fn.apply(context, args); + } else { + pre.fn.call(context); + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return process.nextTick(function() { + callback(null); + }); + } + } + next(); + } + }; + + next(); +}; + +Kareem.prototype.execPost = function(name, context, args, callback) { + var posts = this._posts[name] || []; + var numPosts = posts.length; + var currentPost = 0; + + if (!numPosts) { + return process.nextTick(function() { + callback.apply(null, [null].concat(args)); + }); + } + + var next = function() { + var post = posts[currentPost]; + + if (post.length > args.length) { + post.apply(context, args.concat(function(error) { + if (error) { + return callback(error); + } + + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + + next(); + })); + } else { + post.apply(context, args); + + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + + next(); + } + }; + + next(); +}; + +Kareem.prototype.wrap = function(name, fn, context, args, useLegacyPost) { + var lastArg = (args.length > 0 ? args[args.length - 1] : null); + var _this = this; + + this.execPre(name, context, function(error) { + if (error) { + if (typeof lastArg === 'function') { + return lastArg(error); + } + return; + } + + var end = (typeof lastArg === 'function' ? args.length - 1 : args.length); + + fn.apply(context, args.slice(0, end).concat(function() { + if (arguments[0]) { + // Assume error + return typeof lastArg === 'function' ? + lastArg(arguments[0]) : + undefined; + } + + if (useLegacyPost && typeof lastArg === 'function') { + lastArg.apply(context, arguments); + } + + var argsWithoutError = Array.prototype.slice.call(arguments, 1); + _this.execPost(name, context, argsWithoutError, function() { + if (arguments[0]) { + return typeof lastArg === 'function' ? + lastArg(arguments[0]) : + undefined; + } + + return typeof lastArg === 'function' && !useLegacyPost ? + lastArg.apply(context, arguments) : + undefined; + }); + })); + }); +}; + +Kareem.prototype.createWrapper = function(name, fn, context) { + var _this = this; + return function() { + var args = Array.prototype.slice.call(arguments); + _this.wrap(name, fn, context, args); + }; +}; + +Kareem.prototype.pre = function(name, isAsync, fn, error) { + if (typeof arguments[1] !== 'boolean') { + error = fn; + fn = isAsync; + isAsync = false; + } + + this._pres[name] = this._pres[name] || []; + var pres = this._pres[name]; + + if (isAsync) { + pres.numAsync = pres.numAsync || 0; + ++pres.numAsync; + } + + pres.push({ fn: fn, isAsync: isAsync }); + + return this; +}; + +Kareem.prototype.post = function(name, fn) { + (this._posts[name] = this._posts[name] || []).push(fn); + return this; +}; + +Kareem.prototype.clone = function() { + var n = new Kareem(); + for (var key in this._pres) { + n._pres[key] = this._pres[key].slice(); + } + for (var key in this._posts) { + n._posts[key] = this._posts[key].slice(); + } + + return n; +}; + +module.exports = Kareem; diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/package.json b/5-2/service/node_modules/mongoose/node_modules/kareem/package.json new file mode 100644 index 0000000..a722688 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/package.json @@ -0,0 +1,59 @@ +{ + "name": "kareem", + "version": "1.0.1", + "description": "Next-generation take on pre/post function hooks", + "main": "index.js", + "scripts": { + "test": "./node_modules/mocha/bin/mocha ./test/*", + "test-travis": "./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/*" + }, + "repository": { + "type": "git", + "url": "git://github.com/vkarpov15/kareem.git" + }, + "devDependencies": { + "acquit": "0.0.3", + "gulp": "3.8.10", + "gulp-mocha": "2.0.0", + "gulp-jscs": "1.4.0", + "istanbul": "0.3.5", + "jscs": "1.9.0", + "mocha": "2.0.0" + }, + "jscsConfig": { + "preset": "airbnb", + "requireMultipleVarDecl": null, + "disallowMultipleVarDecl": true + }, + "author": { + "name": "Valeri Karpov", + "email": "val@karpov.io" + }, + "license": "Apache 2.0", + "gitHead": "69710887f85dee09afac690df770dd2febde7268", + "bugs": { + "url": "https://github.com/vkarpov15/kareem/issues" + }, + "homepage": "https://github.com/vkarpov15/kareem", + "_id": "kareem@1.0.1", + "_shasum": "7805d215bb53214ec3af969a1d0b1f17e3e7b95c", + "_from": "kareem@1.0.1", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + }, + "maintainers": [ + { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + } + ], + "dist": { + "shasum": "7805d215bb53214ec3af969a1d0b1f17e3e7b95c", + "tarball": "http://registry.npmjs.org/kareem/-/kareem-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/kareem/-/kareem-1.0.1.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/test/examples.test.js b/5-2/service/node_modules/mongoose/node_modules/kareem/test/examples.test.js new file mode 100644 index 0000000..96d2fb8 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/test/examples.test.js @@ -0,0 +1,339 @@ +var assert = require('assert'); +var Kareem = require('../'); + +/* Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define + * pre and post hooks: pre hooks are called before a given function executes. + * Unlike hooks, kareem stores hooks and other internal state in a separate + * object, rather than relying on inheritance. Furthermore, kareem exposes + * an `execPre()` function that allows you to execute your pre hooks when + * appropriate, giving you more fine-grained control over your function hooks. + */ +describe('pre hooks', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('runs without any hooks specified', function(done) { + hooks.execPre('cook', null, function() { + done(); + }); + }); + + /* pre hook functions take one parameter, a "done" function that you execute + * when your pre hook is finished. + */ + it('runs basic serial pre hooks', function(done) { + var count = 0; + + hooks.pre('cook', function(done) { + ++count; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count); + done(); + }); + }); + + it('can run multipe pre hooks', function(done) { + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function(done) { + ++count1; + done(); + }); + + hooks.pre('cook', function(done) { + ++count2; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + }); + + /* If your pre hook function takes no parameters, its assumed to be + * fully synchronous. + */ + it('can run fully synchronous pre hooks', function(done) { + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function() { + ++count1; + }); + + hooks.pre('cook', function() { + ++count2; + }); + + hooks.execPre('cook', null, function(error) { + assert.equal(null, error); + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + }); + + /* Pre save hook functions are bound to the second parameter to `execPre()` + */ + it('properly attaches context to pre hooks', function(done) { + hooks.pre('cook', function(done) { + this.bacon = 3; + done(); + }); + + hooks.pre('cook', function(done) { + this.eggs = 4; + done(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + // In the pre hooks, `this` will refer to `obj` + hooks.execPre('cook', obj, function(error) { + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + done(); + }); + }); + + /* Like the hooks module, you can declare "async" pre hooks - these take two + * parameters, the functions `next()` and `done()`. `next()` passes control to + * the next pre hook, but the underlying function won't be called until all + * async pre hooks have called `done()`. + */ + it('can execute parallel (async) pre hooks', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + done(); + }); + }); +}); + +describe('post hooks', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('runs without any hooks specified', function(done) { + hooks.execPost('cook', null, [1], function(error, eggs) { + assert.ifError(error); + assert.equal(1, eggs); + done(); + }); + }); + + it('executes with parameters passed in', function(done) { + hooks.post('cook', function(eggs, bacon, callback) { + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + }); + + it('can use synchronous post hooks', function(done) { + var execed = {}; + + hooks.post('cook', function(eggs, bacon) { + execed.first = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + }); + + hooks.post('cook', function(eggs, bacon, callback) { + execed.second = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + }); +}); + +describe('wrap()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('wraps pre and post calls into one call', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.ifError(error); + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj, + args); + }); +}); + +describe('createWrapper()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('wraps wrap() into a callable function', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var cook = hooks.createWrapper( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj); + + cook(obj, function(error, result) { + assert.ifError(error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + }); +}); + +describe('clone()', function() { + it('clones a Kareem object', function() { + var k1 = new Kareem(); + k1.pre('cook', function() {}); + k1.post('cook', function() {}); + + var k2 = k1.clone(); + assert.deepEqual(['cook'], Object.keys(k2._pres)); + assert.deepEqual(['cook'], Object.keys(k2._posts)); + }); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/test/post.test.js b/5-2/service/node_modules/mongoose/node_modules/kareem/test/post.test.js new file mode 100644 index 0000000..3df0ec5 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/test/post.test.js @@ -0,0 +1,46 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('execPost', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles errors', function(done) { + hooks.post('cook', function(eggs, callback) { + callback('error!'); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.equal('error!', error); + assert.ok(!eggs); + done(); + }); + }); + + it('multiple posts', function(done) { + hooks.post('cook', function(eggs, callback) { + setTimeout( + function() { + callback(); + }, + 5); + }); + + hooks.post('cook', function(eggs, callback) { + setTimeout( + function() { + callback(); + }, + 5); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.ifError(error); + assert.equal(4, eggs); + done(); + }); + }); +}); \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/test/pre.test.js b/5-2/service/node_modules/mongoose/node_modules/kareem/test/pre.test.js new file mode 100644 index 0000000..4c1a212 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/test/pre.test.js @@ -0,0 +1,226 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('execPre', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles errors with multiple pres', function(done) { + var execed = {}; + + hooks.pre('cook', function(done) { + execed.first = true; + done(); + }); + + hooks.pre('cook', function(done) { + execed.second = true; + done('error!'); + }); + + hooks.pre('cook', function(done) { + execed.third = true; + done(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + done('other error!'); + }, + 10); + + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors in next()', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 15); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + next('error!'); + done('another error!'); + }, + 5); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors in next() when already done', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + next('error!'); + done('another error!'); + }, + 25); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('other error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('returns correct error when async pre errors', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', function(next) { + execed.second = true; + setTimeout( + function() { + next('error!'); + }, + 15); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('other error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('lets async pres run when fully sync pres are done', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done(); + }, + 5); + + next(); + }); + + hooks.pre('cook', function() { + execed.second = true; + }); + + hooks.execPre('cook', null, function(err) { + assert.ifError(err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('allows passing arguments to the next pre', function(done) { + var execed = {}; + + hooks.pre('cook', function(next) { + execed.first = true; + next(null, 'test'); + }); + + hooks.pre('cook', function(next, p) { + execed.second = true; + assert.equal(p, 'test'); + next(); + }); + + hooks.pre('cook', function(next, p) { + execed.third = true; + assert.ok(!p); + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.ifError(err); + assert.equal(3, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.ok(execed.third); + done(); + }); + }); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/kareem/test/wrap.test.js b/5-2/service/node_modules/mongoose/node_modules/kareem/test/wrap.test.js new file mode 100644 index 0000000..3303961 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/kareem/test/wrap.test.js @@ -0,0 +1,277 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('wrap()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles pre errors', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal(undefined, obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + // Should never get called + assert.ok(false); + callback(null, o); + }, + obj, + args); + }); + + it('handles pre errors when no callback defined', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + + hooks.wrap( + 'cook', + function(o, callback) { + // Should never get called + assert.ok(false); + callback(null, o); + }, + obj, + args); + + setTimeout( + function() { + done(); + }, + 25); + }); + + it('handles errors in wrapped function', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal(undefined, obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + callback('error!'); + }, + obj, + args); + }); + + it('handles errors in post', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(obj, callback) { + obj.tofu = 'no'; + callback('error!'); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal('no', obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + callback(null, o); + }, + obj, + args); + }); + + it('works with no args', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(null); + }, + obj, + args); + + setTimeout( + function() { + assert.equal('no', obj.tofu); + done(); + }, + 25); + }); + + it('handles pre errors with no args', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(null); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(undefined, obj.tofu); + done(); + }, + 25); + }); + + it('handles wrapped function errors with no args', function(done) { + hooks.pre('cook', function(done) { + obj.waffles = false; + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback('error!'); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + done(); + }, + 25); + }); + + it('handles post errors with no args', function(done) { + hooks.pre('cook', function(done) { + obj.waffles = false; + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback('error!'); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + done(); + }, + 25); + }); + + it('can use legacy post behavior', function(done) { + var called = 0; + hooks.post('cook', function(callback) { + ++called; + callback(); + }); + + var args = [function(error) { + assert.equal(called, 0); + + setTimeout(function() { + assert.equal(called, 1); + done(); + }, 0); + }]; + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + null, + args, + true); + }); +}); \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/.coveralls.yml b/5-2/service/node_modules/mongoose/node_modules/mongodb/.coveralls.yml new file mode 100644 index 0000000..ad1e93c --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/.coveralls.yml @@ -0,0 +1 @@ +repo_token: GZFmqKPy7XEX0uOl9TDZFUoOQ5AHADMkU diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/HISTORY.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/HISTORY.md new file mode 100644 index 0000000..763464d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/HISTORY.md @@ -0,0 +1,1328 @@ +2.1.5 2016-02-05 +---------------- +* Updated mongodb-core to 1.3.1. + +2.1.5 2016-02-04 +---------------- +* Updated mongodb-core to 1.3.0. +* Added raw support for the command function on topologies. +* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +* NODE-638, Cannot authenticate database user with utf-8 password. +* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +* Switched to using Array.push instead of concat for use cases of a lot of documents. +* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +* Added peer optional dependencies support using require_optional module. +* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) +* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) + +2.1.4 2016-01-12 +---------------- +* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). +* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). +* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). + +2.1.3 2016-01-04 +---------------- +* Updated mongodb-core to 1.2.31. +* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +2.1.2 2015-12-23 +---------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.1.1 2015-12-13 +---------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.1.0 2015-12-06 +---------------- +* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. +* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. +* Full MongoDB 3.2 support. +* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Updated mongodb-core to 1.2.26. +* Return destination in GridStore pipe function. +* NODE-606 better error handling on destroyed topology for db.js methods. +* Added isDestroyed method to server, replset and mongos topologies. +* Upgraded test suite to run using mongodb-topology-manager. + +2.0.53 2015-12-23 +----------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.0.52 2015-12-14 +----------------- +* removed remove from Gridstore.close. + +2.0.51 2015-12-13 +----------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.0.50 2015-12-06 +----------------- +* Updated mongodb-core to 1.2.26. + +2.0.49 2015-11-20 +----------------- +* Updated mongodb-core to 1.2.24 with several fixes. + * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). + * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + * ismaster runs against admin.$cmd instead of system.$cmd. + * Fixes to handle getMore command errors for MongoDB 3.2 + * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +2.0.48 2015-11-07 +----------------- +* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. +* Updated mongodb-core to 1.2.21. +* Hardened the checking for replicaset equality checks. +* OpReplay flag correctly set on Wire protocol query. +* Mongos load balancing added, introduced localThresholdMS to control the feature. +* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +2.0.47 2015-10-28 +----------------- +* Updated mongodb-core to 1.2.20. +* Fixed bug in arbiter connection capping code. +* NODE-599 correctly handle arrays of server tags in order of priority. +* Fix for 2.6 wire protocol handler related to readPreference handling. +* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +2.0.46 2015-10-15 +----------------- +* Updated mongodb-core to 1.2.19. +* NODE-578 Order of sort fields is lost for numeric field names. +* Expose BSON Map (ES6 Map or polyfill). +* Minor fixes for APM support to pass extended APM test suite. + +2.0.45 2015-09-30 +----------------- +* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. + +2.0.44 2015-09-28 +----------------- +* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. +* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. +* Updated mongodb-core to 1.2.14. +* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. +* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) +* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. +* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. +* NODE-572 Remove examples that use the second parameter to `find()`. + +2.0.43 2015-09-14 +----------------- +* Propagate timeout event correctly to db instances. +* Application Monitoring API (APM) implemented. +* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. +* Updated mongodb-core to 1.2.12. +* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. +* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) +* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) +* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) + +2.0.42 2015-08-18 +----------------- +* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. + +2.0.41 2015-08-14 +----------------- +* Added missing Mongos.prototype.parserType function. +* Updated mongodb-core to 1.2.10. + +2.0.40 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. +* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +* NODE-518 connectTimeoutMS is doubled in 2.0.39. +* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). +* NODE-526 Unique index not throwing duplicate key error. +* NODE-528 Ignore undefined fields in Collection.find(). +* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. + +2.0.39 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.6 for NODE-505. + +2.0.38 2015-07-14 +----------------- +* NODE-505 Query fails to find records that have a 'result' property with an array value. + +2.0.37 2015-07-14 +----------------- +* NODE-504 Collection * Default options when using promiseLibrary. +* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. +* Updated mongodb-core to 1.2.5 to fix NODE-492. + +2.0.36 2015-07-07 +----------------- +* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). +* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. + +2.0.35 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. + +2.0.34 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. +* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. +* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +2.0.33 2015-05-20 +----------------- +* Bumped mongodb-core to 1.1.32. + +2.0.32 2015-05-19 +----------------- +* NODE-463 db.close immediately executes its callback. +* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). +* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. + +2.0.31 2015-05-08 +----------------- +* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +2.0.30 2015-05-07 +----------------- +* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. + +2.0.29 2015-05-07 +----------------- +* NODE-444 Possible memory leak, too many listeners added. +* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. +* Bumped mongodb-core to 1.1.26. + +2.0.28 2015-04-24 +----------------- +* Bumped mongodb-core to 1.1.25 +* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. +* NODE-430 Cursor.count() opts argument masked by var opts = {} +* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. +* NODE-438 replaceOne is not returning the result.ops property as described in the docs. +* NODE-433 _read, pipe and write all open gridstore automatically if not open. +* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. +* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. +* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). +* Minor fix in GridStore.exists for dealing with regular expressions searches. + +2.0.27 2015-04-07 +----------------- +* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. + +2.0.26 2015-04-07 +----------------- +* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. +* NODE-408 Expose GridStore.currentChunk.chunkNumber. + +2.0.25 2015-03-26 +----------------- +* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. + +2.0.24 2015-03-24 +----------------- +* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. +* Upgraded mongodb-core to 1.1.20. + +2.0.23 2015-03-21 +----------------- +* NODE-380 Correctly return MongoError from toError method. +* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. +* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. +* Upgraded mongodb-core to 1.1.19. + +2.0.22 2015-03-16 +----------------- +* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. +* Upgraded mongodb-core to 1.1.17. + +2.0.21 2015-03-06 +----------------- +* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. + +2.0.20 2015-03-04 +----------------- +* Updated mongodb-core 1.1.15 to relax pickserver method. + +2.0.19 2015-03-03 +----------------- +* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) +* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) +* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) + +2.0.18 2015-02-27 +----------------- +* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. + +2.0.17 2015-02-27 +----------------- +* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. +* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. + +2.0.16 2015-02-16 +----------------- +* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. +* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. +* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) + +2.0.15 2015-02-02 +----------------- +* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. +* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. +* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. +* Added ~1.0 mongodb-tools module for test running. +* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +2.0.14 2015-01-21 +----------------- +* Fixed some MongoClient.connect options pass through issues and added test coverage. +* Bumped mongodb-core to 1.1.9 including fixes for io.js + +2.0.13 2015-01-09 +----------------- +* Bumped mongodb-core to 1.1.8. +* Optimized query path for performance, moving Object.defineProperty outside of constructors. + +2.0.12 2014-12-22 +----------------- +* Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +2.0.11 2014-12-19 +----------------- +* listCollections filters out index namespaces on < 2.8 correctly +* Bumped mongo-client to 1.1.7 + +2.0.10 2014-12-18 +----------------- +* NODE-328 fixed db.open return when no callback available issue and added test. +* NODE-327 Refactored listCollections to return cursor to support 2.8. +* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. +* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. +* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) +* Bumped mongo-client to 1.1.6 + +2.0.9 2014-12-01 +---------------- +* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. +* All classes are now strict (Issue #1233) +* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. +* Fixed recursion issues in debug logging due to JSON.stringify() +* Documentation fixes (Issue #1232, https://github.com/wsmoak) +* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) + +2.0.8 2014-11-28 +---------------- +* NODE-322 Finished up prototype refactoring of Db class. +* NODE-322 Exposed Cursor in index.js for New Relic. + +2.0.7 2014-11-20 +---------------- +* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. +* NODE-318 collection.update error while setting a function with serializeFunctions option. +* Documentation fixes. + +2.0.6 2014-11-14 +---------------- +* Refactored code to be prototype based instead of privileged methods. +* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. +* Implemented missing aspects of the CRUD specification. +* Fixed documentation issues. +* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) +* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +2.0.5 2014-10-29 +---------------- +* Minor fixes to documentation and generation of documentation. +* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. + +2.0.4 2014-10-23 +---------------- +* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) +* Made each rewind on each call allowing for re-using the cursor. +* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. +* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. + +2.0.3 2014-10-14 +---------------- +* NODE-297 Aggregate Broken for case of pipeline with no options. + +2.0.2 2014-10-08 +---------------- +* Bumped mongodb-core to 1.0.2. +* Fixed bson module dependency issue by relying on the mongodb-core one. +* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) + +2.0.1 2014-10-07 +---------------- +* Dependency fix + +2.0.0 2014-10-07 +---------------- +* First release of 2.0 driver + +2.0.0-alpha2 2014-10-02 +----------------------- +* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) +* Cluster Management Spec compatible. + +2.0.0-alpha1 2014-09-08 +----------------------- +* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode +* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package +* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node +* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) + * Might break some application +* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove +* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) +* Removed Grid class +* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data + + seek will fail if attempt to use with w or w+ + + write will fail if attempted with w+ or r + + w+ only works for updating metadata on a file +* Cursor toArray and each resets and re-runs the cursor +* FindAndModify returns whole result document instead of just value +* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find +* Removed db.dereference method +* Removed db.cursorInfo method +* Removed db.stats method +* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections +* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. +* Added db.listCollections to replace several methods above + +1.4.10 2014-09-04 +----------------- +* Fixed BSON and Kerberos compilation issues +* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +* Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +* NODE-240 Operations on SSL connection hang on node 0.11.x +* NODE-235 writeResult is not being passed on when error occurs in insert +* NODE-229 Allow count to work with query hints +* NODE-233 collection.save() does not support fullResult +* NODE-244 Should parseError also emit a `disconnected` event? +* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +* NODE-248 Crash with X509 auth +* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +* Bumped BSON parser to 0.2.12 + + +1.4.8 2014-08-01 +---------------- +* NODE-205 correctly emit authenticate event +* NODE-210 ensure no undefined connection error when checking server state +* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +* NODE-220 don't throw error if ensureIndex errors out in Gridstore +* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +* Fixed test running filters +* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +* Fixed parsing issue for w:0 in url parser when in connection string +* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +* Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +* Removed leaking global variable (Issue #1174, https://github.com/dainis) +* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) +* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +* Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +* Correctly emit joined event when primary change +* Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +* All node exceptions will no longer be caught if on('error') is defined +* Added X509 auth support +* Fix for MongoClient connection timeout issue (NODE-97) +* Pass through error messages from parseError instead of just text (Issue #1125) +* Close db connection on error (Issue #1128, https://github.com/benighted) +* Fixed documentation generation +* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +* Insert/Update/Remove using new write commands when available +* Added support for new roles based API's in 2.6 for addUser/removeUser +* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +* Support for OP_LOG_REPLAY flag (NODE-94) +* Fixes for SSL HA ping and discovery. +* Uses createIndexes if available for ensureIndex/createIndex +* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +* Made CommandCursor behave as Readable stream. +* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +* Refactored commands to all go through command function ensuring consistent command execution. +* Fixed issues where readPreferences where not correctly passed to mongos. +* Catch error == null and make err detection more prominent (NODE-130) +* Allow reads from arbiter for single server connection (NODE-117) +* Handle error coming back with no documents (NODE-130) +* Correctly use close parameter in Gridstore.write() (NODE-125) +* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +* Ignore return commands that have no registered callback +* Made collection.count not use the db.command function +* Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +* Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +* Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +* BSON size checking now done pre serialization (Issue #1037) +* Added isConnected returns false when no connection Pool exists (Issue #1043) +* Unified command handling to ensure same handling (Issue #1041, #1042) +* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +* Fixed issue with Kerberos authentication on Windows for re-authentication. +* Fixed Mongos failover behavior to correctly throw out old servers. +* Ensure stored queries/write ops are executed correctly after connection timeout +* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +* Fixed bug with callback third parameter on some commands (Issue #1033) +* Fixed possible issue where killcursor command might leave hanging functions +* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +* Throw error if dbName or collection name contains null character (at command level and at collection level) +* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +* Add driver version to export (Issue #1021, https://github.com/aheckmann) +* Add text to readpreference obedient commands (Issue #1019) +* Drivers should check the query failure bit even on getmore response (Issue #1018) +* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +* Support SASL PLAIN authentication (Issue #1009) +* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +* Introduced write and read concerns for GridFS (Issue #996) +* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +* Fixed issue with pool size on replicaset connections (Issue #1000) +* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +* Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +* Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +* Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +* Applied auth before server instance is set as connected when single server connection +* Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +* Refactored test suite to speed up running of replicaset tests +* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +* Corrected a slaveOk setting issue (Issue #906, #905) +* Fixed HA issue where ping's would not go to correct server on HA server connection failure. +* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +* Fixed race condition in Cursor stream (NODE-31) +* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +* Added support for maxMessageSizeBytes if available (DRIVERS-1) +* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +* Fixed missing MongoErrors on some cursor methods (Issue #882) +* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +* Added limit/skip options to Collection.count (Issue #870) +* Added applySkipLimit option to Cursor.count (Issue #870) +* Enabled ping strategy as default for Replicaset if none specified (Issue #876) +* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +* Added fixes for handling type 2 binary due to PHP driver (Issue #864) +* Moved callBackStore to Base class to have single unified store (Issue #866) +* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +* Only open a new HA socket when previous one dead (Issue #859, #857) +* Minor fixes + +1.2.9 2013-01-15 +---------------- +* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +* Connection string with no db specified should default to admin db (Issue #848) +* Support port passed as string to Server class (Issue #844) +* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +* Included toError wrapper code moved to utils.js file (Issue #839, #840) +* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +* Rolled back batches as they hang in certain situations +* Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +* Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +* Fixed ssl regression, added more test coverage (Issue #800) +* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +* Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +* Fix for journal write concern not correctly being passed under some circumstances. +* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +* Fix for double callback on insert with w:0 specified (Issue #783) +* Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +* Force correct setting of read_secondary based on the read preference (Issue #741) +* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +* Mongos connection with auth not working (Issue #737) +* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + * open/close/db/connect methods implemented +* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +* Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +* Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +* fix Admin.serverStatus (Issue #723, https://github.com/Contra) +* logging on connection open/close(Issue #721, https://github.com/asiletto) +* more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +* Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +* Cleanup of non-closing connections (Issue #706) +* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +* Set keepalive on as default, override if not needed +* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +* Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +* Proper stopping of strategy on replicaset stop +* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +* Fix for eval on replicaset Issue #684 +* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +* Added exhaust option for find for feature completion (not recommended for normal use) +* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +* Fix gridfs readstream (Issue #607, https://github.com/tedeh). +* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +* Cleanup map reduce (Issue #614, https://github.com/aheckmann). +* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +* Date identification handled correctly in bson js parser when running in vm context. +* Documentation updates +* GridStore filename not set on read (Issue #621) +* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +* Added support for awaitdata for tailable cursors (Issue #624) +* Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +* Fixed auth to work better when multiple connections are involved. +* Default connection pool size increased to 5 connections. +* Fixes for the ReadStream class to work properly with 0.8 of Node.js +* Added explain function support to aggregation helper +* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +* Fixed Always emit db events (Issue #657) +* Close event not correctly resets DB openCalled variable to allow reconnect +* Added open event on connection established for replicaset, mongos and server +* Much faster BSON C++ parser thanks to Lucasfilm Singapore. +* Refactoring of replicaset connection logic to simplify the code. +* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +* Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +* Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +* Passing back getLastError object as 3rd parameter on findAndModify command. +* Fixed a bunch of performance regressions in objectId and cursor. +* Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +* Fixes to handling of failover on server error +* Only emits error messages if there are error listeners to avoid uncaught events +* Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +* _id=0 is being turned into an ObjectID (Issue #551) +* fix for error in GridStore write method (Issue #559) +* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +* Connection pools handles closing themselves down and clearing the state +* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +* Returning update status document at the end of the callback for updates, (Issue #569) +* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +* Stats not returned from map reduce with inline results (Issue #542) +* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +* Streaming large files from GridFS causes truncation (Issue #540) +* Make callback type checks agnostic to V8 context boundaries (Issue #545) +* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +* Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +* BSON parser is externalized in it's own repository, currently using git master +* Fixes for Replicaset connectivity issue (Issue #537) +* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +* Removed SimpleEmitter and replaced with standard EventEmitter +* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +* Fixed memory leak in C++ bson parser (Issue #526) +* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +* Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mongodb/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/LICENSE @@ -0,0 +1,201 @@ +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. \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/Makefile b/5-2/service/node_modules/mongoose/node_modules/mongodb/Makefile new file mode 100644 index 0000000..36e1202 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/Makefile @@ -0,0 +1,11 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + hugo -s docs/reference -d ../../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/README.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/README.md new file mode 100644 index 0000000..8ebc810 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/README.md @@ -0,0 +1,415 @@ +[![NPM](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![NPM](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) + +[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.png)](http://travis-ci.org/mongodb/node-mongodb-native) +[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) +[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +# Description + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. + +## MongoDB Node.JS Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| api-doc | http://mongodb.github.io/node-mongodb-native/2.1/api/ | +| 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) + +### 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 + +# Installation + +The recommended way to get started using the Node.js 2.0 driver is by using the `NPM` (Node Package Manager) to install the dependency in your project. + +## MongoDB Driver + +Given that you have created your own project using `npm init` we install the mongodb driver and it's dependencies by executing the following `NPM` command. + +``` +npm install mongodb --save +``` + +This will download the MongoDB driver and add a dependency entry in your `package.json` file. + +## Troubleshooting + +The MongoDB driver depends on several other packages. These are. + +* mongodb-core +* bson +* kerberos +* node-gyp + +The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build node.js itself to be able to compile and install the `kerberos` module. Furthermore the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager what libraries to install. + +{{% note class="important" %}} +Windows already contains the SSPI API used for Kerberos authentication. However you will need to install a full compiler tool chain using visual studio C++ to correctly install the kerberos extension. +{{% /note %}} + +### Diagnosing on UNIX + +If you don’t have the build essentials it won’t build. In the case of linux you will need gcc and g++, node.js with all the headers and python. The easiest way to figure out what’s missing is by trying to build the kerberos project. You can do this by performing the following steps. + +``` +git clone https://github.com/christkv/kerberos.git +cd kerberos +npm install +``` + +If all the steps complete you have the right toolchain installed. If you get node-gyp not found you need to install it globally by doing. + +``` +npm install -g node-gyp +``` + +If correctly compiles and runs the tests you are golden. We can now try to install the mongod driver by performing the following command. + +``` +cd yourproject +npm install mongodb --save +``` + +If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. + +``` +npm --loglevel verbose install mongodb +``` + +This will print out all the steps npm is performing while trying to install the module. + +### Diagnosing on Windows + +A known compiler tool chain known to work for compiling `kerberos` on windows is the following. + +* Visual Studio c++ 2010 (do not use higher versions) +* Windows 7 64bit SDK +* Python 2.7 or higher + +Open visual studio command prompt. Ensure node.exe is in your path and install node-gyp. + +``` +npm install -g node-gyp +``` + +Next you will have to build the project manually to test it. Use any tool you use with git and grab the repo. + +``` +git clone https://github.com/christkv/kerberos.git +cd kerberos +npm install +node-gyp rebuild +``` + +This should rebuild the driver successfully if you have everything set up correctly. + +### Other possible issues + +Your python installation might be hosed making gyp break. I always recommend that you test your deployment environment first by trying to build node itself on the server in question as this should unearth any issues with broken packages (and there are a lot of broken packages out there). + +Another thing is to ensure your user has write permission to wherever the node modules are being installed. + +QuickStart +========== +The quick start guide will show you how to setup a simple application using node.js and MongoDB. Its scope is only how to set up the driver and perform the simple crud operations. For more in depth coverage we encourage reading the tutorials. + +Create the package.json file +---------------------------- +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Enter the following command and answer the questions to create the initial structure for your new project + +``` +npm init +``` + +Next we need to edit the generated package.json file to add the dependency for the MongoDB driver. The package.json file below is just an example and your will look different depending on how you answered the questions after entering `npm init` + +``` +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb": "~2.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +Connecting to MongoDB +--------------------- +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server and the database **myproject**. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + db.close(); +}); +``` + +Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console. + +Let's Add some code to show the different CRUD operations available. + +Inserting a Document +-------------------- +Let's create a function that will insert some documents for us. + +```js +var insertDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.insertMany([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the document collection"); + callback(result); + }); +} +``` + +The insert command will return a results object that contains several fields that might be useful. + +* **result** Contains the result document from MongoDB +* **ops** Contains the documents inserted with added **_id** fields +* **connection** Contains the connection used to perform the insert + +Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + db.close(); + }); +}); +``` + +We can now run the update **app.js** file. + +``` +node app.js +``` + +You should see the following output after running the **app.js** file. + +``` +Connected correctly to server +Inserted 3 documents into the document collection +``` + +Updating a document +------------------- +Let's look at how to do a simple document update by adding a new field **b** to the document that has the field **a** set to **2**. + +```js +var updateDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.updateOne({ a : 2 } + , { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(result); + }); +} +``` + +The method will update the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Let's update the callback function from **MongoClient.connect** to include the update method. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + db.close(); + }); + }); +}); +``` + +Delete a document +----------------- +Next lets delete the document where the field **a** equals to **3**. + +```js +var deleteDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.deleteOne({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(result); + }); +} +``` + +This will delete the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient +.connect** callback function. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + deleteDocument(db, function() { + db.close(); + }); + }); + }); +}); +``` + +Finally let's retrieve all the documents using a simple find. + +Find All Documents +------------------ +We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query. + +```js +var findDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Find some documents + collection.find({}).toArray(function(err, docs) { + assert.equal(err, null); + assert.equal(2, docs.length); + console.log("Found the following records"); + console.dir(docs); + callback(docs); + }); +} +``` + +This query will return all the documents in the **documents** collection. Since we deleted a document the total +documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + deleteDocument(db, function() { + findDocuments(db, function() { + db.close(); + }); + }); + }); + }); +}); +``` + +This concludes the QuickStart of connecting and performing some Basic operations using the MongoDB Node.js driver. For more detailed information you can look at the tutorials covering more specific topics of interest. + +## Next Steps + + * [MongoDB Documentation](http://mongodb.org/) + * [Read about Schemas](http://learnmongodbthehardway.com/) + * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/conf.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/conf.json new file mode 100644 index 0000000..aba0b7a --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/conf.json @@ -0,0 +1,73 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/functional/operation_example_tests.js", + "test/functional/operation_promises_example_tests.js", + "test/functional/operation_generators_example_tests.js", + "test/functional/authentication_tests.js", + "test/functional/gridfs_stream_tests.js", + "lib/admin.js", + "lib/collection.js", + "lib/cursor.js", + "lib/aggregation_cursor.js", + "lib/command_cursor.js", + "lib/db.js", + "lib/mongo_client.js", + "lib/mongos.js", + "lib/read_preference.js", + "lib/replset.js", + "lib/server.js", + "lib/bulk/common.js", + "lib/bulk/ordered.js", + "lib/bulk/unordered.js", + "lib/gridfs/grid_store.js", + "node_modules/mongodb-core/lib/error.js", + "lib/gridfs-stream/index.js", + "lib/gridfs-stream/download.js", + "lib/gridfs-stream/upload.js", + "node_modules/mongodb-core/lib/connection/logger.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/index.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/index.js new file mode 100644 index 0000000..1ebe943 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/index.js @@ -0,0 +1,50 @@ +// Core module +var core = require('mongodb-core'), + Instrumentation = require('./lib/apm'); + +// Set up the connect function +var connect = require('./lib/mongo_client').connect; + +// Expose error class +connect.MongoError = core.MongoError; + +// Actual driver classes exported +connect.Admin = require('./lib/admin'); +connect.MongoClient = require('./lib/mongo_client'); +connect.Db = require('./lib/db'); +connect.Collection = require('./lib/collection'); +connect.Server = require('./lib/server'); +connect.ReplSet = require('./lib/replset'); +connect.Mongos = require('./lib/mongos'); +connect.ReadPreference = require('./lib/read_preference'); +connect.GridStore = require('./lib/gridfs/grid_store'); +connect.Chunk = require('./lib/gridfs/chunk'); +connect.Logger = core.Logger; +connect.Cursor = require('./lib/cursor'); +connect.GridFSBucket = require('./lib/gridfs-stream'); + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.Map = core.BSON.Map; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; + +// Add connect method +connect.connect = connect; + +// Set up the instrumentation method +connect.instrument = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + return new Instrumentation(core, options, callback); +} + +// Set our exports to be the connect function +module.exports = connect; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/admin.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/admin.js new file mode 100644 index 0000000..1f89512 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/admin.js @@ -0,0 +1,581 @@ +"use strict"; + +var toError = require('./utils').toError, + Define = require('./metadata'), + shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Use the admin database for the operation + * var adminDb = db.admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +var Admin = function(db, topology, promiseLibrary) { + if(!(this instanceof Admin)) return new Admin(db, topology); + var self = this; + + // Internal state + this.s = { + db: db + , topology: topology + , promiseLibrary: promiseLibrary + } +} + +var define = Admin.define = new Define('Admin', Admin, false); + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.command = function(command, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand(command, options, function(err, doc) { + return callback != null ? callback(err, doc) : null; + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand(command, options, function(err, doc) { + if(err) return reject(err); + resolve(doc); + }); + }); +} + +define.classMethod('command', {callback: true, promise:true}); + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.buildInfo = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.serverInfo(callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.serverInfo(function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('buildInfo', {callback: true, promise:true}); + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverInfo = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err != null) return callback(err, null); + callback(null, doc); + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err) return reject(err); + resolve(doc); + }); + }); +} + +define.classMethod('serverInfo', {callback: true, promise:true}); + +/** + * Retrieve this db's server status. + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverStatus = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return serverStatus(self, callback) + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + serverStatus(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var serverStatus = function(self, callback) { + self.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { + if(err == null && doc.ok === 1) { + callback(null, doc); + } else { + if(err) return callback(err, false); + return callback(toError(doc), false); + } + }); +} + +define.classMethod('serverStatus', {callback: true, promise:true}); + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.profilingLevel = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return profilingLevel(self, callback) + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + profilingLevel(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var profilingLevel = function(self, callback) { + self.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) { + doc = doc; + + 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); + } + }); +} + +define.classMethod('profilingLevel', {callback: true, promise:true}); + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.ping = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({ping: 1}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({ping: 1}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('ping', {callback: true, promise:true}); + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.authenticate = function(username, password, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options); + options.authdb = 'admin'; + + // Execute using callback + if(typeof callback == 'function') return this.s.db.authenticate(username, password, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.authenticate(username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('authenticate', {callback: true, promise:true}); + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.logout = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.s.db.logout({authdb: 'admin'}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.logout({authdb: 'admin'}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('logout', {callback: true, promise:true}); + +// Get write concern +var writeConcern = function(options, db) { + options = shallowClone(options); + + // If options already contain write concerns return it + if(options.w || options.wtimeout || options.j || options.fsync) { + return options; + } + + // Set db write concern if available + if(db.writeConcern) { + if(options.w) options.w = db.writeConcern.w; + if(options.wtimeout) options.wtimeout = db.writeConcern.wtimeout; + if(options.j) options.j = db.writeConcern.j; + if(options.fsync) options.fsync = db.writeConcern.fsync; + } + + // Return modified options + return options; +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.addUser = function(username, password, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + // Get the options + options = writeConcern(options, self.s.db) + // Set the db name to admin + options.dbName = 'admin'; + + // Execute using callback + if(typeof callback == 'function') + return self.s.db.addUser(username, password, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.addUser(username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('addUser', {callback: true, promise:true}); + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.removeUser = function(username, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + // Get the options + options = writeConcern(options, self.s.db) + // Set the db name + options.dbName = 'admin'; + + // Execute using callback + if(typeof callback == 'function') + return self.s.db.removeUser(username, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.removeUser(username, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('removeUser', {callback: true, promise:true}); + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.setProfilingLevel = function(level, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return setProfilingLevel(self, level, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + setProfilingLevel(self, level, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var setProfilingLevel = function(self, level, callback) { + 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; + + self.s.db.executeDbAdminCommand(command, function(err, doc) { + doc = doc; + + if(err == null && doc.ok === 1) + return callback(null, level); + return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + }); +} + +define.classMethod('setProfilingLevel', {callback: true, promise:true}); + +/** + * Retrive the current profiling information for MongoDB + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.profilingInfo = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return profilingInfo(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + profilingInfo(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var profilingInfo = function(self, callback) { + try { + self.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback); + } catch (err) { + return callback(err, null); + } +} + +define.classMethod('profilingLevel', {callback: true, promise:true}); + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options=null] Optional settings. + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') + return validateCollection(self, collectionName, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + validateCollection(self, collectionName, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var validateCollection = function(self, collectionName, options, callback) { + 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]]; + } + } + + self.s.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); + }); +} + +define.classMethod('validateCollection', {callback: true, promise:true}); + +/** + * List the available databases + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.listDatabases = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return self.s.db.executeDbAdminCommand({listDatabases:1}, {}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('listDatabases', {callback: true, promise:true}); + +/** + * Get ReplicaSet status + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.replSetGetStatus = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return replSetGetStatus(self, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + replSetGetStatus(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var replSetGetStatus = function(self, callback) { + self.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { + if(err == null && doc.ok === 1) + return callback(null, doc); + if(err) return callback(err, false); + callback(toError(doc), false); + }); +} + +define.classMethod('replSetGetStatus', {callback: true, promise:true}); + +module.exports = Admin; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js new file mode 100644 index 0000000..3663229 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js @@ -0,0 +1,432 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('./cursor') + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = AggregationCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + } +} + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(AggregationCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' + , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' + , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified']; + +// Extend the Cursor +for(var name in CoreCursor.prototype) { + AggregationCursor.prototype[name] = CoreCursor.prototype[name]; +} + +var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {AggregationCursor} + */ +AggregationCursor.prototype.batchSize = function(value) { + if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true }); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", drvier:true }); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.geoNear = function(document) { + this.s.cmd.pipeline.push({$geoNear: document}); + return this; +} + +define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.group = function(document) { + this.s.cmd.pipeline.push({$group: document}); + return this; +} + +define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.limit = function(value) { + this.s.cmd.pipeline.push({$limit: value}); + return this; +} + +define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.match = function(document) { + this.s.cmd.pipeline.push({$match: document}); + return this; +} + +define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.out = function(destination) { + this.s.cmd.pipeline.push({$out: destination}); + return this; +} + +define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.project = function(document) { + this.s.cmd.pipeline.push({$project: document}); + return this; +} + +define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.redact = function(document) { + this.s.cmd.pipeline.push({$redact: document}); + return this; +} + +define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.skip = function(value) { + this.s.cmd.pipeline.push({$skip: value}); + return this; +} + +define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.sort = function(document) { + this.s.cmd.pipeline.push({$sort: document}); + return this; +} + +define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.unwind = function(field) { + this.s.cmd.pipeline.push({$unwind: field}); + return this; +} + +define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]}); + +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +// Inherited methods +define.classMethod('toArray', {callback: true, promise:true}); +define.classMethod('each', {callback: true, promise:false}); +define.classMethod('forEach', {callback: true, promise:false}); +define.classMethod('next', {callback: true, promise:true}); +define.classMethod('close', {callback: true, promise:true}); +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); +define.classMethod('rewind', {callback: false, promise:false}); +define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); +define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * 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. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * 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. + * @method AggregationCursor.prototype.each + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +AggregationCursor.INIT = 0; +AggregationCursor.OPEN = 1; +AggregationCursor.CLOSED = 2; + +module.exports = AggregationCursor; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/apm.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/apm.js new file mode 100644 index 0000000..7b08012 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/apm.js @@ -0,0 +1,608 @@ +var EventEmitter = require('events').EventEmitter, + inherits = require('util').inherits; + +// Get prototypes +var AggregationCursor = require('./aggregation_cursor'), + CommandCursor = require('./command_cursor'), + OrderedBulkOperation = require('./bulk/ordered').OrderedBulkOperation, + UnorderedBulkOperation = require('./bulk/unordered').UnorderedBulkOperation, + GridStore = require('./gridfs/grid_store'), + Server = require('./server'), + ReplSet = require('./replset'), + Mongos = require('./mongos'), + Cursor = require('./cursor'), + Collection = require('./collection'), + Db = require('./db'), + Admin = require('./admin'); + +var basicOperationIdGenerator = { + operationId: 1, + + next: function() { + return this.operationId++; + } +} + +var basicTimestampGenerator = { + current: function() { + return new Date().getTime(); + }, + + duration: function(start, end) { + return end - start; + } +} + +var senstiveCommands = ['authenticate', 'saslStart', 'saslContinue', 'getnonce', + 'createUser', 'updateUser', 'copydbgetnonce', 'copydbsaslstart', 'copydb']; + +var Instrumentation = function(core, options, callback) { + options = options || {}; + + // Optional id generators + var operationIdGenerator = options.operationIdGenerator || basicOperationIdGenerator; + // Optional timestamp generator + var timestampGenerator = options.timestampGenerator || basicTimestampGenerator; + // Extend with event emitter functionality + EventEmitter.call(this); + + // Contains all the instrumentation overloads + this.overloads = []; + + // --------------------------------------------------------- + // + // Instrument prototype + // + // --------------------------------------------------------- + + var instrumentPrototype = function(callback) { + var instrumentations = [] + + // Classes to support + var classes = [GridStore, OrderedBulkOperation, UnorderedBulkOperation, + CommandCursor, AggregationCursor, Cursor, Collection, Db]; + + // Add instrumentations to the available list + for(var i = 0; i < classes.length; i++) { + if(classes[i].define) { + instrumentations.push(classes[i].define.generate()); + } + } + + // Return the list of instrumentation points + callback(null, instrumentations); + } + + // Did the user want to instrument the prototype + if(typeof callback == 'function') { + instrumentPrototype(callback); + } + + // --------------------------------------------------------- + // + // Server + // + // --------------------------------------------------------- + + // Reference + var self = this; + // Names of methods we need to wrap + var methods = ['command', 'insert', 'update', 'remove']; + // Prototype + var proto = core.Server.prototype; + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var requestId = core.Query.nextRequestId(); + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + var ns = args[0]; + var commandObj = args[1]; + var options = args[2] || {}; + var keys = Object.keys(commandObj); + var commandName = keys[0]; + var db = ns.split('.')[0]; + + // Do we have a legacy insert/update/remove command + if(x == 'insert' && !this.lastIsMaster().maxWireVersion) { + commandName = 'insert'; + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + insert: col, documents: commandObj + } + + if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { + commandObj.writeConcern = options.writeConcern; + } + + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'update' && !this.lastIsMaster().maxWireVersion) { + commandName = 'update'; + + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + update: col, updates: commandObj + } + + if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { + commandObj.writeConcern = options.writeConcern; + } + + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'remove' && !this.lastIsMaster().maxWireVersion) { + commandName = 'delete'; + + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + delete: col, deletes: commandObj + } + + if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { + commandObj.writeConcern = options.writeConcern; + } + + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'insert' || x == 'update' || x == 'remove' && this.lastIsMaster().maxWireVersion >= 2) { + // Skip the insert/update/remove commands as they are executed as actual write commands in 2.6 or higher + return func.apply(this, args); + } + + // Get the callback + var callback = args.pop(); + // Set current callback operation id from the current context or create + // a new one + var ourOpId = callback.operationId || operationIdGenerator.next(); + + // Get a connection reference for this server instance + var connection = this.s.pool.get() + + // Emit the start event for the command + var command = { + // Returns the command. + command: commandObj, + // Returns the database name. + databaseName: db, + // Returns the command name. + commandName: commandName, + // Returns the driver generated request id. + requestId: requestId, + // Returns the driver generated operation id. + // This is used to link events together such as bulk write operations. OPTIONAL. + operationId: ourOpId, + // Returns the connection id for the command. For languages that do not have this, + // this MUST return the driver equivalent which MUST include the server address and port. + // The name of this field is flexible to match the object that is returned from the driver. + connectionId: connection + }; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.commandObj = {}; + command.commandObj[commandName] = true; + } + + // Emit the started event + self.emit('started', command) + + // Start time + var startTime = timestampGenerator.current(); + + // Push our handler callback + args.push(function(err, r) { + var endTime = timestampGenerator.current(); + var command = { + duration: timestampGenerator.duration(startTime, endTime), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: connection + }; + + // If we have an error + if(err || (r && r.result && r.result.ok == 0)) { + command.failure = err || r.result.writeErrors || r.result; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.failure = {}; + } + + self.emit('failed', command); + } else if(commandObj && commandObj.writeConcern + && commandObj.writeConcern.w == 0) { + // If we have write concern 0 + command.reply = {ok:1}; + self.emit('succeeded', command); + } else { + command.reply = r && r.result ? r.result : r; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase()) != -1) { + command.reply = {}; + } + + self.emit('succeeded', command); + } + + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } + }); + + // --------------------------------------------------------- + // + // Bulk Operations + // + // --------------------------------------------------------- + + // Inject ourselves into the Bulk methods + var methods = ['execute']; + var prototypes = [ + require('./bulk/ordered').Bulk.prototype, + require('./bulk/unordered').Bulk.prototype + ] + + prototypes.forEach(function(proto) { + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var bulk = this; + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + // Set an operation Id on the bulk object + this.operationId = operationIdGenerator.next(); + + // Get the callback + var callback = args.pop(); + // If we have a callback use this + if(typeof callback == 'function') { + args.push(function(err, r) { + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } else { + return func.apply(this, args); + } + } + }); + }); + + // --------------------------------------------------------- + // + // Cursor + // + // --------------------------------------------------------- + + // Inject ourselves into the Cursor methods + var methods = ['_find', '_getmore', '_killcursor']; + var prototypes = [ + require('./cursor').prototype, + require('./command_cursor').prototype, + require('./aggregation_cursor').prototype + ] + + // Command name translation + var commandTranslation = { + '_find': 'find', '_getmore': 'getMore', '_killcursor': 'killCursors', '_explain': 'explain' + } + + prototypes.forEach(function(proto) { + + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var cursor = this; + var requestId = core.Query.nextRequestId(); + var ourOpId = operationIdGenerator.next(); + var parts = this.ns.split('.'); + var db = parts[0]; + + // Get the collection + parts.shift(); + var collection = parts.join('.'); + + // Set the command + var command = this.query; + var cmd = this.s.cmd; + + // If we have a find method, set the operationId on the cursor + if(x == '_find') { + cursor.operationId = ourOpId; + } + + // Do we have a find command rewrite it + if(x == '_getmore') { + command = { + getMore: this.cursorState.cursorId, + collection: collection, + batchSize: cmd.batchSize + } + + if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; + } else if(x == '_killcursors') { + command = { + killCursors: collection, + cursors: [this.cursorState.cursorId] + } + } else if(cmd.find) { + command = { + find: collection, filter: cmd.query + } + + if(cmd.sort) command.sort = cmd.sort; + if(cmd.fields) command.projection = cmd.fields; + if(cmd.limit && cmd.limit < 0) { + command.limit = Math.abs(cmd.limit); + command.singleBatch = true; + } else if(cmd.limit) { + command.limit = Math.abs(cmd.limit); + } + + // Options + if(cmd.skip) command.skip = cmd.skip; + if(cmd.hint) command.hint = cmd.hint; + if(cmd.batchSize) command.batchSize = cmd.batchSize; + if(typeof cmd.returnKey == 'boolean') command.returnKey = cmd.returnKey; + if(cmd.comment) command.comment = cmd.comment; + if(cmd.min) command.min = cmd.min; + if(cmd.max) command.max = cmd.max; + if(cmd.maxScan) command.maxScan = cmd.maxScan; + if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; + + // Flags + if(typeof cmd.awaitData == 'boolean') command.awaitData = cmd.awaitData; + if(typeof cmd.snapshot == 'boolean') command.snapshot = cmd.snapshot; + if(typeof cmd.tailable == 'boolean') command.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') command.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') command.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.partial == 'boolean') command.partial = cmd.partial; + if(typeof cmd.showDiskLoc == 'boolean') command.showRecordId = cmd.showDiskLoc; + + // Read Concern + if(cmd.readConcern) command.readConcern = cmd.readConcern; + + // Override method + if(cmd.explain) command.explain = cmd.explain; + if(cmd.exhaust) command.exhaust = cmd.exhaust; + + // If we have a explain flag + if(cmd.explain) { + // Create fake explain command + command = { + explain: command, + verbosity: 'allPlansExecution' + } + + // Set readConcern on the command if available + if(cmd.readConcern) command.readConcern = cmd.readConcern + + // Set up the _explain name for the command + x = '_explain'; + } + } else { + command = cmd; + } + + // Set up the connection + var connectionId = null; + + // Set local connection + if(this.connection) connectionId = this.connection; + if(!connectionId && this.server && this.server.getConnection) connectionId = this.server.getConnection(); + + // Get the command Name + var commandName = x == '_find' ? Object.keys(command)[0] : commandTranslation[x]; + + // Emit the start event for the command + var command = { + // Returns the command. + command: command, + // Returns the database name. + databaseName: db, + // Returns the command name. + commandName: commandName, + // Returns the driver generated request id. + requestId: requestId, + // Returns the driver generated operation id. + // This is used to link events together such as bulk write operations. OPTIONAL. + operationId: this.operationId, + // Returns the connection id for the command. For languages that do not have this, + // this MUST return the driver equivalent which MUST include the server address and port. + // The name of this field is flexible to match the object that is returned from the driver. + connectionId: connectionId + }; + + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + + // Get the callback + var callback = args.pop(); + + // We do not have a callback but a Promise + if(typeof callback == 'function' || command.commandName == 'killCursors') { + var startTime = timestampGenerator.current(); + // Emit the started event + self.emit('started', command) + + // Emit succeeded event with killcursor if we have a legacy protocol + if(command.commandName == 'killCursors' + && this.server.lastIsMaster() + && this.server.lastIsMaster().maxWireVersion < 4) { + // Emit the succeeded command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: [{ok:1}] + }; + + // Emit the command + return self.emit('succeeded', command) + } + + // Add our callback handler + args.push(function(err, r) { + if(err) { + // Command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: cursor.server.getConnection(), + failure: err }; + + // Emit the command + self.emit('failed', command) + } else { + + // Do we have a getMore + if(commandName.toLowerCase() == 'getmore' && r == null) { + r = { + cursor: { + id: cursor.cursorState.cursorId, + ns: cursor.ns, + nextBatch: cursor.cursorState.documents + }, ok:1 + } + } else if(commandName.toLowerCase() == 'find' && r == null) { + r = { + cursor: { + id: cursor.cursorState.cursorId, + ns: cursor.ns, + firstBatch: cursor.cursorState.documents + }, ok:1 + } + } else if(commandName.toLowerCase() == 'killcursors' && r == null) { + r = { + cursorsUnknown:[cursor.cursorState.lastCursorId], + ok:1 + } + } + + // cursor id is zero, we can issue success command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: r && r.result ? r.result : r + }; + + // Emit the command + self.emit('succeeded', command) + } + + // Return + if(!callback) return; + + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } else { + // Assume promise, push back the missing value + args.push(callback); + // Get the promise + var promise = func.apply(this, args); + // Return a new promise + return new cursor.s.promiseLibrary(function(resolve, reject) { + var startTime = timestampGenerator.current(); + // Emit the started event + self.emit('started', command) + // Execute the function + promise.then(function(r) { + // cursor id is zero, we can issue success command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: cursor.cursorState.documents + }; + + // Emit the command + self.emit('succeeded', command) + }).catch(function(err) { + // Command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: cursor.server.getConnection(), + failure: err }; + + // Emit the command + self.emit('failed', command) + // reject the promise + reject(err); + }); + }); + } + } + }); + }); +} + +inherits(Instrumentation, EventEmitter); + +Instrumentation.prototype.uninstrument = function() { + for(var i = 0; i < this.overloads.length; i++) { + var obj = this.overloads[i]; + obj.proto[obj.name] = obj.func; + } + + // Remove all listeners + this.removeAllListeners('started'); + this.removeAllListeners('succeeded'); + this.removeAllListeners('failed'); +} + +module.exports = Instrumentation; \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 0000000..d5c5f93 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,431 @@ +"use strict"; + +var utils = require('../utils'), + Long = require('mongodb-core').BSON.Long, + Timestamp = require('mongodb-core').BSON.Timestamp; + +// 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 + + +// Get write concern +var writeConcern = function(target, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + target.writeConcern = options; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } + + return target +} + +/** + * Helper function to define properties + * @ignore + */ +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 + * @ignore + */ +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 + * @ignore + */ +var LegacyOp = function(batchType, operation, index) { + this.batchType = batchType; + this.index = index; + this.operation = operation; +} + +/** + * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {boolean} ok Did bulk operation correctly execute + * @property {number} nInserted number of inserted documents + * @property {number} nUpdated number of documents updated logically + * @property {number} nUpserted Number of upserted documents + * @property {number} nModified Number of documents updated physically on disk + * @property {number} nRemoved Number of removed documents + * @return {BulkWriteResult} a BulkWriteResult instance + */ +var BulkWriteResult = 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 inserted ids + * + * @return {object[]} + */ + this.getInsertedIds = function() { + return bulkResult.insertedIds; + } + + /** + * Return an array of upserted ids + * + * @return {object[]} + */ + 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 {object} + */ + this.getUpsertedIdAt = function(index) { + return bulkResult.upserted[index]; + } + + /** + * Return raw internal result + * + * @return {object} + */ + this.getRawResponse = function() { + return bulkResult; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + this.hasWriteErrors = function() { + return bulkResult.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + this.getWriteErrorCount = function() { + return bulkResult.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @return {WriteError} + */ + this.getWriteErrorAt = function(index) { + if(index < bulkResult.writeErrors.length) { + return bulkResult.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {object[]} + */ + this.getWriteErrors = function() { + return bulkResult.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + this.getLastOp = function() { + return bulkResult.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + 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 "BulkWriteResult(" + this.toJSON(bulkResult) + ")"; + } + + this.isOk = function() { + return bulkResult.ok == 1; + } +} + +/** + * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +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 + ")"; + } +} + +/** + * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {number} index Write concern error original bulk operation index. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +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 + * @ignore + */ +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; + } else if(result && result.result) { + result = result.result; + } else if(result == null) { + return; + } + + // 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); + var writeError = { + index: 0 + , code: result.code || 0 + , errmsg: result.message + , op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if(result.ok == 0 && bulkResult.ok == 0) { + return; + } + + // Deal with opTime if available + if(result.opTime || result.lastOp) { + var opTime = result.lastOp || result.opTime; + var lastOpTS = null; + var lastOpT = null; + + // We have a time stamp + if(opTime instanceof Timestamp) { + if(bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if(opTime.greaterThan(bulkResult.lastOp)) { + bulkResult.lastOp = opTime; + } + } else { + // Existing TS + if(bulkResult.lastOp) { + lastOpTS = typeof bulkResult.lastOp.ts == 'number' + ? Long.fromNumber(bulkResult.lastOp.ts) : bulkResult.lastOp.ts; + lastOpT = typeof bulkResult.lastOp.t == 'number' + ? Long.fromNumber(bulkResult.lastOp.t) : bulkResult.lastOp.t; + } + + // Current OpTime TS + var opTimeTS = typeof opTime.ts == 'number' + ? Long.fromNumber(opTime.ts) : opTime.ts; + var opTimeT = typeof opTime.t == 'number' + ? Long.fromNumber(opTime.t) : opTime.t; + + // Compare the opTime's + if(bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if(opTimeTS.greaterThan(lastOpTS)) { + bulkResult.lastOp = opTime; + } else if(opTimeTS.equals(lastOpTS)) { + if(opTimeT.greaterThan(lastOpT)) { + bulkResult.lastOp = opTime; + } + } + } + } + + // 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)); + } +} + +// +// 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.BulkWriteResult = BulkWriteResult; +exports.WriteError = WriteError; +exports.Batch = Batch; +exports.LegacyOp = LegacyOp; +exports.mergeBatchResults = mergeBatchResults; +exports.cloneOptions = cloneOptions; +exports.writeConcern = writeConcern; +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; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 0000000..b93ec71 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,530 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , f = require('util').format + , handleCallback = require('../utils').handleCallback + , shallowClone = utils.shallowClone + , WriteError = common.WriteError + , BulkWriteResult = common.BulkWriteResult + , LegacyOp = common.LegacyOp + , ObjectID = require('mongodb-core').BSON.ObjectID + , Define = require('../metadata') + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +/** + * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance. + */ +var FindOperatorsOrdered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +FindOperatorsOrdered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.deleteOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne; + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.delete = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete; + +// Add to internal list of documents +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = _self.s.bson.calculateObjectSize(document, false); + + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatchSize + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Reset the current size trackers + _self.s.currentBatchSize = 0; + _self.s.currentBatchSizeBytes = 0; + } else { + // Update current batch size + _self.s.currentBatchSize = _self.s.currentBatchSize + 1; + _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; + } + + if(docType == common.INSERT) { + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentBatch.operations.push(document) + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Return self + return _self; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ +function OrderedBulkOperation(topology, 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 bson = topology.bson; + + // Namespace for the operation + var namespace = collection.collectionName; + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize + ? topology.isMasterDoc.maxBsonObjectSize : (1024*1025*16); + var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize + ? topology.isMasterDoc.maxWriteBatchSize : 1000; + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Current batch + var currentBatch = null; + var currentIndex = 0; + var currentBatchSize = 0; + var currentBatchSizeBytes = 0; + var batches = []; + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentBatch: null + , currentIndex: 0 + , currentBatchSize: 0 + , currentBatchSizeBytes: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + // Promise Library + , promiseLibrary: promiseLibrary + // Fundamental error + , err: null + // Bypass validation + , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false + } +} + +var define = OrderedBulkOperation.define = new Define('OrderedBulkOperation', OrderedBulkOperation, false); + +OrderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Set up the force server object id + var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' + ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + operation.upsert = op[key].upsert ? true: false; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + var operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +OrderedBulkOperation.prototype.insert = function(document) { + if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +OrderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsOrdered(this); +} + +Object.defineProperty(OrderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// +// Execute next write command in a chain +var executeCommands = function(self, callback) { + if(self.s.batches.length == 0) { + return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult)); + } + + // Ordered execution of the command + var batch = self.s.batches.shift(); + + var resultHandler = function(err, result) { + // Error is a driver related error not a bulk op error, terminate + if(err && err.driver || err && err.message) { + return handleCallback(callback, err); + } + + // If we have and error + if(err) err.ok = 0; + // Merge the results together + var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result); + if(mergeResult != null) { + return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult)); + } + + // If we are ordered and have errors and they are + // not all replication errors terminate the operation + if(self.s.bulkResult.writeErrors.length > 0) { + return handleCallback(callback, toError(self.s.bulkResult.writeErrors[0]), new BulkWriteResult(self.s.bulkResult)); + } + + // Execute the next command in line + executeCommands(self, callback); + } + + var finalOptions = {ordered: true} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + // Set an operationIf if provided + if(self.operationId) { + resultHandler.operationId = self.operationId; + } + + // Serialize functions + if(self.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true + } + + // Serialize functions + if(self.s.options.ignoreUndefined) { + finalOptions.ignoreUndefined = true + } + + // Is the bypassDocumentValidation options specific + if(self.s.bypassDocumentValidation == true) { + finalOptions.bypassDocumentValidation = true; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +/** + * The callback format for results + * @callback OrderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {OrderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +OrderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + var self = this; + if(this.s.executed) throw new toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute using callback + if(typeof callback == 'function') { + return executeCommands(this, callback); + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeCommands(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('execute', {callback: true, promise:false}); + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeOrderedBulkOp = function(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; +module.exports = initializeOrderedBulkOp; +module.exports.Bulk = OrderedBulkOperation; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 0000000..70602b9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,539 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , f = require('util').format + , handleCallback = require('../utils').handleCallback + , shallowClone = utils.shallowClone + , WriteError = common.WriteError + , BulkWriteResult = common.BulkWriteResult + , LegacyOp = common.LegacyOp + , ObjectID = require('mongodb-core').BSON.ObjectID + , Define = require('../metadata') + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +/** + * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance. + */ +var FindOperatorsUnordered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.removeOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.remove = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// +// Add to the operations list +// +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = _self.s.bson.calculateObjectSize(document, false); + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Holds the current batch + _self.s.currentBatch = null; + // Get the right type of batch + if(docType == common.INSERT) { + _self.s.currentBatch = _self.s.currentInsertBatch; + } else if(docType == common.UPDATE) { + _self.s.currentBatch = _self.s.currentUpdateBatch; + } else if(docType == common.REMOVE) { + _self.s.currentBatch = _self.s.currentRemoveBatch; + } + + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatch.size + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatch.sizeBytes + bsonSize) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.operations.push(document); + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Save back the current Batch to the right type + if(docType == common.INSERT) { + _self.s.currentInsertBatch = _self.s.currentBatch; + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } else if(docType == common.UPDATE) { + _self.s.currentUpdateBatch = _self.s.currentBatch; + } else if(docType == common.REMOVE) { + _self.s.currentRemoveBatch = _self.s.currentBatch; + } + + // Update current batch size + _self.s.currentBatch.size = _self.s.currentBatch.size + 1; + _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize; + + // Return self + return _self; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +var UnorderedBulkOperation = function(topology, 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 currentBatch = null; + 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 bson = topology.bson; + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize + ? topology.isMasterDoc.maxBsonObjectSize : (1024*1025*16); + var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize + ? topology.isMasterDoc.maxWriteBatchSize : 1000; + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentInsertBatch: null + , currentUpdateBatch: null + , currentRemoveBatch: null + , currentBatch: null + , currentIndex: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + // Promise Library + , promiseLibrary: promiseLibrary + // Bypass validation + , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false + } +} + +var define = UnorderedBulkOperation.define = new Define('UnorderedBulkOperation', UnorderedBulkOperation, false); + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +UnorderedBulkOperation.prototype.insert = function(document) { + if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsUnordered} + */ +UnorderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsUnordered(this); +} + +Object.defineProperty(UnorderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +UnorderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Set up the force server object id + var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' + ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + if(op[key].upsert) operation.upsert = true; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + var operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +// +// Execute the command +var executeBatch = function(self, batch, callback) { + var finalOptions = {ordered: false} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + var resultHandler = function(err, result) { + // Error is a driver related error not a bulk op error, terminate + if(err && err.driver || err && err.message) { + return handleCallback(callback, err); + } + + // If we have and error + if(err) err.ok = 0; + handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, result)); + } + + // Set an operationIf if provided + if(self.operationId) { + resultHandler.operationId = self.operationId; + } + + // Serialize functions + if(self.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true + } + + // Is the bypassDocumentValidation options specific + if(self.s.bypassDocumentValidation == true) { + finalOptions.bypassDocumentValidation = true; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +// +// Execute all the commands +var executeBatches = function(self, callback) { + var numberOfCommandsToExecute = self.s.batches.length; + var error = null; + // Execute over all the batches + for(var i = 0; i < self.s.batches.length; i++) { + executeBatch(self, self.s.batches[i], function(err, result) { + // Driver layer error capture it + if(err) error = err; + // Count down the number of commands left to execute + numberOfCommandsToExecute = numberOfCommandsToExecute - 1; + + // Execute + if(numberOfCommandsToExecute == 0) { + // Driver level error + if(error) return handleCallback(callback, error); + // Treat write errors + var error = self.s.bulkResult.writeErrors.length > 0 ? toError(self.s.bulkResult.writeErrors[0]) : null; + handleCallback(callback, error, new BulkWriteResult(self.s.bulkResult)); + } + }); + } +} + +/** + * The callback format for results + * @callback UnorderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +UnorderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + var self = this; + if(this.s.executed) throw toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if(this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if(this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute using callback + if(typeof callback == 'function') return executeBatches(this, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeBatches(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('execute', {callback: true, promise:false}); + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeUnorderedBulkOp = function(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; +module.exports = initializeUnorderedBulkOp; +module.exports.Bulk = UnorderedBulkOperation; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/collection.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/collection.js new file mode 100644 index 0000000..048c9c5 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/collection.js @@ -0,0 +1,3179 @@ +"use strict"; + +var checkCollectionName = require('./utils').checkCollectionName + , ObjectID = require('mongodb-core').BSON.ObjectID + , Long = require('mongodb-core').BSON.Long + , Code = require('mongodb-core').BSON.Code + , f = require('util').format + , AggregationCursor = require('./aggregation_cursor') + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone + , isObject = require('./utils').isObject + , toError = require('./utils').toError + , normalizeHintField = require('./utils').normalizeHintField + , handleCallback = require('./utils').handleCallback + , decorateCommand = require('./utils').decorateCommand + , formattedOrderClause = require('./utils').formattedOrderClause + , ReadPreference = require('./read_preference') + , CoreReadPreference = require('mongodb-core').ReadPreference + , CommandCursor = require('./command_cursor') + , Define = require('./metadata') + , Cursor = require('./cursor') + , unordered = require('./bulk/unordered') + , ordered = require('./bulk/ordered'); + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {string} collectionName Get the collection name. + * @property {string} namespace Get the full collection namespace. + * @property {object} writeConcern The current write concern values. + * @property {object} readConcern The current read concern values. + * @property {object} hint Get current index hint for collection. + * @return {Collection} a Collection instance. + */ +var Collection = function(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + var self = this; + // Unpack variables + var internalHint = null; + var opts = options != null && ('object' === typeof options) ? options : {}; + var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + var serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; + var raw = options == null || options.raw == null ? db.raw : options.raw; + var readPreference = null; + var collectionHint = null; + var namespace = f("%s.%s", dbName, name); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Assign the right collection level readPreference + if(options && options.readPreference) { + readPreference = options.readPreference; + } else if(db.options.readPreference) { + readPreference = db.options.readPreference; + } + + // Set custom primary key factory if provided + pkFactory = pkFactory == null + ? ObjectID + : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory + // Db + , db: db + // Topology + , topology: topology + // dbName + , dbName: dbName + // Options + , options: options + // Namespace + , namespace: namespace + // Read preference + , readPreference: readPreference + // Raw + , raw: raw + // SlaveOK + , slaveOk: slaveOk + // Serialize functions + , serializeFunctions: serializeFunctions + // internalHint + , internalHint: internalHint + // collectionHint + , collectionHint: collectionHint + // Name + , name: name + // Promise library + , promiseLibrary: promiseLibrary + // Read Concern + , readConcern: options.readConcern + } +} + +var define = Collection.define = new Define('Collection', Collection, false); + +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, get: function() { return this.s.name; } +}); + +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, get: function() { return this.s.namespace; } +}); + +Object.defineProperty(Collection.prototype, 'readConcern', { + enumerable: true, get: function() { return this.s.readConcern || {level: 'local'}; } +}); + +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(this.s.options.w != null) ops.w = this.s.options.w; + if(this.s.options.j != null) ops.j = this.s.options.j; + if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * @ignore + */ +Object.defineProperty(Collection.prototype, "hint", { + enumerable: true + , get: function () { return this.s.collectionHint; } + , set: function (v) { this.s.collectionHint = normalizeHintField(v); } +}); + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} query The cursor query object. + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = function() { + 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 && fields !== undefined && !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]; + } + + // Unpack options + 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.s.raw; + newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + 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.s.db.slaveOk; + + // Add read preference if needed + newOptions = getReadPreference(this, newOptions, this.s.db, this); + // Set slave ok to true if read preference different from primary + if(newOptions.readPreference != null + && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if(selector != null && typeof selector != 'object') { + throw MongoError.create({message: "query selector must be an object", driver:true }); + } + + // Build the find command + var findCommand = { + find: this.s.namespace + , limit: newOptions.limit + , skip: newOptions.skip + , query: selector + } + + // Ensure we use the right await data option + if(typeof newOptions.awaitdata == 'boolean') { + newOptions.awaitData = newOptions.awaitdata + }; + + // Translate to new command option noCursorTimeout + if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + // Merge in options to command + for(var name in newOptions) { + if(newOptions[name] != null) findCommand[name] = newOptions[name]; + } + + // Format the fields + var formatFields = function(fields) { + var object = {}; + if(Array.isArray(fields)) { + for(var i = 0; i < fields.length; i++) { + if(Array.isArray(fields[i])) { + object[fields[i][0]] = fields[i][1]; + } else { + object[fields[i][0]] = 1; + } + } + } else { + object = fields; + } + + return object; + } + + // Special treatment for the fields selector + if(fields) findCommand.fields = formatFields(fields); + + // Add db object to the new options + newOptions.db = this.s.db; + + // Add the promise library + newOptions.promiseLibrary = this.s.promiseLibrary; + + // Set raw if available at collection level + if(newOptions.raw == null && this.s.raw) newOptions.raw = this.s.raw; + + // Sort options + if(findCommand.sort) + findCommand.sort = formattedOrderClause(findCommand.sort); + + // Set the readConcern + if(this.s.readConcern) { + findCommand.readConcern = this.s.readConcern; + } + + // Create the cursor + if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions)); + return this.s.topology.cursor(this.s.namespace, findCommand, newOptions); +} + +define.classMethod('find', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object} doc Document to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertOne = function(doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + if(Array.isArray(doc)) return callback(MongoError.create({message: 'doc parameter must be an object', driver:true })); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return insertOne(self, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + insertOne(self, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var insertOne = function(self, doc, options, callback) { + insertDocuments(self, [doc], options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + // Workaround for pre 2.6 servers + if(r == null) return callback(null, {result: {ok:1}}); + // Add values to top level to ensure crud spec compatibility + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if(callback) callback(null, r); + }); +} + +var mapInserManyResults = function(docs, r) { + var ids = r.getInsertedIds(); + var keys = Object.keys(ids); + var finalIds = new Array(keys); + + for(var i = 0; i < keys.length; i++) { + if(ids[keys[i]]._id) { + finalIds[ids[keys[i]].index] = ids[keys[i]]._id; + } + } + + var finalResult = { + result: {ok: 1, n: r.insertedCount}, + ops: docs, + insertedCount: r.insertedCount, + insertedIds: finalIds + }; + + if(r.getLastOp()) { + finalResult.result.opTime = r.getLastOp(); + } + + return finalResult; +} + +define.classMethod('insertOne', {callback: true, promise:true}); + +/** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertMany = function(docs, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:true}; + if(!Array.isArray(docs)) return callback(MongoError.create({message: 'docs parameter must be an array of documents', driver:true })); + + // Get the write concern options + if(typeof options.checkKeys != 'boolean') { + options.checkKeys = true; + } + + // If keep going set unordered + options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Set up the force server object id + var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' + ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; + + // Do we want to force the server to assign the _id key + if(forceServerObjectId !== true) { + // Add _id if not specified + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + } + + // Generate the bulk write operations + var operations = [{ + insertMany: docs + }]; + + // Execute using callback + if(typeof callback == 'function') return bulkWrite(self, operations, options, function(err, r) { + if(err) return callback(err, r); + callback(null, mapInserManyResults(docs, r)); + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + bulkWrite(self, operations, options, function(err, r) { + if(err) return reject(err); + resolve(mapInserManyResults(docs, r)); + }); + }); +} + +define.classMethod('insertMany', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:true}; + + if(!Array.isArray(operations)) { + throw MongoError.create({message: "operations must be an array of documents", driver:true }); + } + + // Execute using callback + if(typeof callback == 'function') return bulkWrite(self, operations, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + bulkWrite(self, operations, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var bulkWrite = function(self, operations, options, callback) { + // Add ignoreUndfined + if(self.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = self.s.options.ignoreUndefined; + } + + // Create the bulk operation + var bulk = options.ordered == true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options); + + // for each op go through and add to the bulk + for(var i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + + // Final options for write concern + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + + // Execute the bulk + bulk.execute(writeCon, function(err, r) { + // We have connection level error + if(!r && err) return callback(err, null); + // We have single error + if(r && r.hasWriteErrors() && r.getWriteErrorCount() == 1) { + return callback(toError(r.getWriteErrorAt(0)), r); + } + + // if(err) return callback(err); + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Update the n + r.n = r.insertedCount; + + // Inserted documents + var inserted = r.getInsertedIds(); + // Map inserted ids + for(var i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + var upserted = r.getUpsertedIds(); + // Map upserted ids + for(var i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Check if we have write errors + if(r.hasWriteErrors()) { + // Get all the errors + var errors = r.getWriteErrors(); + // Return the MongoError object + return callback(toError({ + message: 'write operation failed', code: errors[0].code, writeErrors: errors + }), r); + } + + // Check if we have a writeConcern error + if(r.getWriteConcernError()) { + // Return the MongoError object + return callback(toError(r.getWriteConcernError()), r); + } + + // Return the results + callback(null, r); + }); +} + +var insertDocuments = function(self, docs, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true; + + // If keep going set unordered + if(finalOptions.keepGoing == true) finalOptions.ordered = false; + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Set up the force server object id + var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' + ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; + + // Add _id if not specified + if(forceServerObjectId !== true){ + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + } + + // File inserts + self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +define.classMethod('bulkWrite', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * @typedef {Object} Collection~insertWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId[]} insertedIds All the generated _id's for the inserted documents. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * @typedef {Object} Collection~insertOneWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * The callback format for inserts + * @callback Collection~insertWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * The callback format for inserts + * @callback Collection~insertOneWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = function(docs, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:false}; + docs = !Array.isArray(docs) ? [docs] : docs; + + if(options.keepGoing == true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); +} + +define.classMethod('insert', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~updateWriteOpResult + * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents scanned. + * @property {Number} result.nModified The total count of documents modified. + * @property {Object} connection The connection object used for the operation. + * @property {Number} matchedCount The number of documents that matched the filter. + * @property {Number} modifiedCount The number of documents that were modified. + * @property {Number} upsertedCount The number of documents upserted. + * @property {Object} upsertedId The upserted id. + * @property {ObjectId} upsertedId._id The upserted _id returned from the server. + */ + +/** + * The callback format for inserts + * @callback Collection~updateWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Update a single document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateOne(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateOne(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var updateOne = function(self, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + if(callback) callback(null, r); + }); +} + +define.classMethod('updateOne', {callback: true, promise:true}); + +/** + * Replace a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} doc The Document that replaces the matching document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.replaceOne = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return replaceOne(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + replaceOne(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var replaceOne = function(self, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.ops = [update]; + if(callback) callback(null, r); + }); +} + +define.classMethod('replaceOne', {callback: true, promise:true}); + +/** + * Update multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateMany(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateMany(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var updateMany = function(self, filter, update, options, callback) { + // Set single document update + options.multi = true; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + if(callback) callback(null, r); + }); +} + +define.classMethod('updateMany', {callback: true, promise:true}); + +var updateDocuments = function(self, selector, document, options, callback) { + if('function' === typeof options) callback = options, options = null; + if(options == null) options = {}; + if(!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object")); + if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object")); + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Execute the operation + var op = {q: selector, u: document}; + op.upsert = typeof options.upsert == 'boolean' ? options.upsert : false; + op.multi = typeof options.multi == 'boolean' ? options.multi : false; + + // Update options + self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} document The update document. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = function(selector, document, options, callback) { + var self = this; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateDocuments(self, selector, document, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateDocuments(self, selector, document, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('update', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~deleteWriteOpResult + * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents deleted. + * @property {Object} connection The connection object used for the operation. + * @property {Number} deletedCount The number of documents deleted. + */ + +/** + * The callback format for inserts + * @callback Collection~deleteWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Delete a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + var options = shallowClone(options); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return deleteOne(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + deleteOne(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var deleteOne = function(self, filter, options, callback) { + options.single = true; + removeDocuments(self, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +define.classMethod('deleteOne', {callback: true, promise:true}); + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +define.classMethod('removeOne', {callback: true, promise:true}); + +/** + * Delete multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + var options = shallowClone(options); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return deleteMany(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + deleteMany(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var deleteMany = function(self, filter, options, callback) { + options.single = false; + removeDocuments(self, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +var removeDocuments = function(self, selector, options, callback) { + if(typeof options == 'function') { + callback = options, options = {}; + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // If selector is null set empty + if(selector == null) selector = {}; + + // Build the op + var op = {q: selector, limit: 0}; + if(options.single) op.limit = 1; + + // Execute the remove + self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +define.classMethod('deleteMany', {callback: true, promise:true}); + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +define.classMethod('removeMany', {callback: true, promise:true}); + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = function(selector, options, callback) { + var self = this; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return removeDocuments(self, selector, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + removeDocuments(self, selector, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('remove', {callback: true, promise:true}); + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +Collection.prototype.save = function(doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return save(self, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + save(self, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var save = function(self, doc, options, callback) { + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + // Establish if we need to perform an insert or update + if(doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(self, {_id: doc._id}, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(self, [doc], options, function(err, r) { + if(callback == null) return; + if(doc == null) return handleCallback(callback, null, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, r); + }); +} + +define.classMethod('save', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options=null] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan=null] Limit the number of items to scan. + * @param {number} [options.min=null] Set index bounds. + * @param {number} [options.max=null] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use find().limit(1).next(function(err, doc){}) + */ +Collection.prototype.findOne = function() { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + var callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + + // Execute using callback + if(typeof callback == 'function') return findOne(self, args, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + findOne(self, args, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOne = function(self, args, callback) { + var cursor = self.find.apply(self, args).limit(-1).batchSize(1); + // Return the item + cursor.next(function(err, item) { + if(err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); +} + +define.classMethod('findOne', {callback: true, promise:true}); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Collection~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.rename = function(newName, opt, callback) { + var self = this; + if(typeof opt == 'function') callback = opt, opt = {}; + opt = opt || {}; + + // Execute using callback + if(typeof callback == 'function') return rename(self, newName, opt, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + rename(self, newName, opt, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var rename = function(self, newName, opt, callback) { + // Check the collection name + checkCollectionName(newName); + // Build the command + var renameCollection = f("%s.%s", self.s.dbName, self.s.name); + var toCollection = f("%s.%s", self.s.dbName, newName); + var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false; + var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}; + + // Execute against admin + self.s.db.admin().command(cmd, opt, function(err, doc) { + if(err) return handleCallback(callback, err, null); + // We have an error + if(doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options)); + } catch(err) { + return handleCallback(callback, toError(err), null); + } + }); +} + +define.classMethod('rename', {callback: true, promise:true}); + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.drop = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return self.s.db.dropCollection(self.s.name, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.dropCollection(self.s.name, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('drop', {callback: true, promise:true}); + +/** + * Returns the options of the collection. + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.options = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return options(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var options = function(self, callback) { + self.s.db.listCollections({name: self.s.name}).toArray(function(err, collections) { + if(err) return handleCallback(callback, err); + if(collections.length == 0) { + return handleCallback(callback, MongoError.create({message: f("collection %s not found", self.s.namespace), driver:true })); + } + + handleCallback(callback, err, collections[0].options || null); + }); +} + +define.classMethod('options', {callback: true, promise:true}); + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.isCapped = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return isCapped(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + isCapped(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var isCapped = function(self, callback) { + self.options(function(err, document) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, document && document.capped); + }); +} + +define.classMethod('isCapped', {callback: true, promise:true}); + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + + // Execute using callback + if(typeof callback == 'function') return createIndex(self, fieldOrSpec, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndex(self, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var createIndex = function(self, fieldOrSpec, options, callback) { + self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback); +} + +define.classMethod('createIndex', {callback: true, promise:true}); + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * @method + * @param {array} indexSpecs An array of index specifications to be created + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndexes = function(indexSpecs, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return createIndexes(self, indexSpecs, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndexes(self, indexSpecs, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var createIndexes = function(self, indexSpecs, callback) { + // Ensure we generate the correct name if the parameter is not set + for(var i = 0; i < indexSpecs.length; i++) { + if(indexSpecs[i].name == null) { + var keys = []; + + for(var name in indexSpecs[i].key) { + keys.push(f('%s_%s', name, indexSpecs[i].key[name])); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + // Execute the index + self.s.db.command({ + createIndexes: self.s.name, indexes: indexSpecs + }, callback); +} + +define.classMethod('createIndexes', {callback: true, promise:true}); + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + // Execute using callback + if(typeof callback == 'function') return dropIndex(self, indexName, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + dropIndex(self, indexName, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var dropIndex = function(self, indexName, options, callback) { + // Delete index command + var cmd = {'deleteIndexes':self.s.name, 'index':indexName}; + + // Execute command + self.s.db.command(cmd, options, function(err, result) { + if(typeof callback != 'function') return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +define.classMethod('dropIndex', {callback: true, promise:true}); + +/** + * Drops all indexes from this collection. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndexes = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return dropIndexes(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + dropIndexes(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var dropIndexes = function(self, callback) { + self.dropIndex('*', function (err, result) { + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); +} + +define.classMethod('dropIndexes', {callback: true, promise:true}); + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {Promise} returns Promise if no [callback] passed + */ +Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes; + +define.classMethod('dropAllIndexes', {callback: true, promise:true}); + +/** + * 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. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.reIndex = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return reIndex(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + reIndex(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var reIndex = function(self, options, callback) { + // Reindex + var cmd = {'reIndex':self.s.name}; + + // Execute the command + self.s.db.command(cmd, options, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +define.classMethod('reIndex', {callback: true, promise:true}); + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + options = options || {}; + // Clone the options + options = shallowClone(options); + // Set the CommandCursor constructor + options.cursorFactory = CommandCursor; + // Set the promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + if(!this.s.topology.capabilities()) { + throw new MongoError('cannot connect to server'); + } + + // We have a list collections command + if(this.s.topology.capabilities().hasListIndexesCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listIndexes: this.s.name, cursor: cursor }; + // Execute the cursor + var cursor = this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options); + // Do we have a readPreference, apply it + if(options.readPreference) cursor.setReadPreference(options.readPreference); + // Return the cursor + return cursor; + } + + // Get the namespace + var ns = f('%s.system.indexes', this.s.dbName); + // Get the query + var cursor = this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options); + // Do we have a readPreference, apply it + if(options.readPreference) cursor.setReadPreference(options.readPreference); + // Set the passed in batch size if one was provided + if(options.batchSize) cursor = cursor.batchSize(options.batchSize); + // Return the cursor + return cursor; +}; + +define.classMethod('listIndexes', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return ensureIndex(self, fieldOrSpec, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + ensureIndex(self, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var ensureIndex = function(self, fieldOrSpec, options, callback) { + self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback); +} + +define.classMethod('ensureIndex', {callback: true, promise:true}); + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexExists = function(indexes, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return indexExists(self, indexes, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexExists(self, indexes, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexExists = function(self, indexes, callback) { + self.indexInformation(function(err, indexInformation) { + // If we have an error return + if(err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for(var i = 0; i < indexes.length; i++) { + if(indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +define.classMethod('indexExists', {callback: true, promise:true}); + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexInformation = function(options, callback) { + var self = this; + // Unpack calls + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return indexInformation(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexInformation(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexInformation = function(self, options, callback) { + self.s.db.indexInformation(self.s.name, options, callback); +} + +define.classMethod('indexInformation', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * Count number of matching documents in the db to a query. + * @method + * @param {object} query The query for the count. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.limit=null] The limit of documents to count. + * @param {boolean} [options.skip=null] The number of documents to skip for the count. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~countCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.count = function(query, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + var queryOption = args.length ? args.shift() || {} : {}; + var optionsOption = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return count(self, queryOption, optionsOption, callback); + + // Check if query is empty + query = query || {}; + options = options || {}; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + count(self, query, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var count = function(self, query, options, callback) { + var skip = options.skip; + var limit = options.limit; + var hint = options.hint; + var maxTimeMS = options.maxTimeMS; + + // Final query + var cmd = { + 'count': self.s.name, 'query': query + }; + + // Add limit and skip if defined + if(typeof skip == 'number') cmd.skip = skip; + if(typeof limit == 'number') cmd.limit = limit; + if(hint) options.hint = hint; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + cmd.readConcern = self.s.readConcern; + } + + // Execute command + self.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.n); + }); +} + +define.classMethod('count', {callback: true, promise:true}); + +/** + * The distinct command returns returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.distinct = function(key, query, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + var queryOption = args.length ? args.shift() || {} : {}; + var optionsOption = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return distinct(self, key, queryOption, optionsOption, callback); + + // Ensure the query and options are set + query = query || {}; + options = options || {}; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + distinct(self, key, query, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var distinct = function(self, key, query, options, callback) { + // maxTimeMS option + var maxTimeMS = options.maxTimeMS; + + // Distinct command + var cmd = { + 'distinct': self.s.name, 'key': key, 'query': query + }; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + cmd.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.values); + }); +} + +define.classMethod('distinct', {callback: true, promise:true}); + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexes = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return indexes(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexes(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexes = function(self, callback) { + self.s.db.indexInformation(self.s.name, {full:true}, callback); +} + +define.classMethod('indexes', {callback: true, promise:true}); + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Collection~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.stats = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return stats(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + stats(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var stats = function(self, options, callback) { + // Build command object + var commandObject = { + collStats:self.s.name + } + + // Check if we have the scale value + if(options['scale'] != null) commandObject['scale'] = options['scale']; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Execute the command + self.s.db.command(commandObject, options, callback); +} + +define.classMethod('stats', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~findAndModifyWriteOpResult + * @property {object} value Document returned from findAndModify command. + * @property {object} lastErrorObject The raw lastErrorObject returned from the command. + * @property {Number} ok Is 1 if the command executed correctly. + */ + +/** + * The callback format for inserts + * @callback Collection~findAndModifyCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndDelete(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndDelete(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndDelete = function(self, filter, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['remove'] = true; + // Execute find and Modify + self.findAndModify( + filter + , options.sort + , null + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndDelete', {callback: true, promise:true}); + +/** + * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} replacement Document replacing the matching document. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndReplace(self, filter, replacement, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndReplace(self, filter, replacement, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndReplace = function(self, filter, replacement, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['update'] = true; + finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; + finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; + + // Execute findAndModify + self.findAndModify( + filter + , options.sort + , replacement + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndReplace', {callback: true, promise:true}); + +/** + * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} update Update operations to be performed on the document + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndUpdate(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndUpdate(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndUpdate = function(self, filter, update, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['update'] = true; + finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; + finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; + + // Execute findAndModify + self.findAndModify( + filter + , options.sort + , update + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndUpdate', {callback: true, promise:true}); + +/** + * Find and update a document. + * @method + * @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=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = function(query, sort, doc, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + var options = shallowClone(options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + // Execute using callback + if(typeof callback == 'function') return findAndModify(self, query, sort, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findAndModify(self, query, sort, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findAndModify = function(self, query, sort, doc, options, callback) { + // Create findAndModify command object + var queryObject = { + 'findandmodify': self.s.name + , 'query': query + }; + + sort = formattedOrderClause(sort); + if(sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + if(options.fields) { + queryObject.fields = options.fields; + } + + if(doc && !options.remove) { + queryObject.update = doc; + } + + // 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'] = self.s.serializeFunctions; + } + + // No check on the documents + options.checkKeys = false; + + // Get the write concern settings + var finalOptions = writeConcern(options, self.s.db, self, options); + + // Decorate the findAndModify command with the write Concern + if(finalOptions.writeConcern) { + queryObject.writeConcern = finalOptions.writeConcern; + } + + // Have we specified bypassDocumentValidation + if(typeof finalOptions.bypassDocumentValidation == 'boolean') { + queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; + } + + // Execute the command + self.s.db.command(queryObject + , options, function(err, result) { + if(err) return handleCallback(callback, err, null); + return handleCallback(callback, null, result); + }); +} + +define.classMethod('findAndModify', {callback: true, promise:true}); + +/** + * Find and remove a document. + * @method + * @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=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = function(query, sort, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return findAndRemove(self, query, sort, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + findAndRemove(self, query, sort, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findAndRemove = function(self, query, sort, options, callback) { + // Add the remove option + options['remove'] = true; + // Execute the callback + self.findAndModify(query, sort, null, options, callback); +} + +define.classMethod('findAndRemove', {callback: true, promise:true}); + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} pipeline Array containing all the aggregation framework commands for the execution. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~resultCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + var self = this; + if(Array.isArray(pipeline)) { + // Set up callback if one is provided + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if(options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + var args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + var opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = opts && (opts.readPreference + || opts.explain || opts.cursor || opts.out + || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + // Ignore readConcern option + var ignoreReadConcern = false; + + // If out was specified + if(typeof options.out == 'string') { + pipeline.push({$out: options.out}); + ignoreReadConcern = true; + } else if(pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { + ignoreReadConcern = true; + } + + // Build the command + var command = { aggregate : this.s.name, pipeline : pipeline}; + + // If we have bypassDocumentValidation set + if(typeof options.bypassDocumentValidation == 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Do we have a readConcern specified + if(!ignoreReadConcern && this.s.readConcern) { + command.readConcern = this.s.readConcern; + } + + // If we have allowDiskUse defined + if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // If explain has been specified add it + if(options.explain) command.explain = options.explain; + + // Validate that cursor options is valid + if(options.cursor != null && typeof options.cursor != 'object') { + throw toError('cursor options must be an object'); + } + + // promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Set the AggregationCursor constructor + options.cursorFactory = AggregationCursor; + if(typeof callback != 'function') { + if(!this.s.topology.capabilities()) { + throw new MongoError('cannot connect to server'); + } + + if(this.s.topology.capabilities().hasAggregationCursor) { + options.cursor = options.cursor || { batchSize : 1000 }; + command.cursor = options.cursor; + } + + // Allow disk usage command + if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Execute the cursor + return this.s.topology.cursor(this.s.namespace, command, options); + } + + var cursor = null; + // We do not allow cursor + if(options.cursor) { + return this.s.topology.cursor(this.s.namespace, command, options); + } + + // Execute the command + this.s.db.command(command, options, function(err, result) { + if(err) { + handleCallback(callback, err); + } else if(result['err'] || result['errmsg']) { + handleCallback(callback, toError(result)); + } else if(typeof result == 'object' && result['serverPipeline']) { + handleCallback(callback, null, result['serverPipeline']); + } else if(typeof result == 'object' && result['stages']) { + handleCallback(callback, null, result['stages']); + } else { + handleCallback(callback, null, result.result); + } + }); +} + +define.classMethod('aggregate', {callback: true, promise:false}); + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.parallelCollectionScan = function(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; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Add a promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Execute using callback + if(typeof callback == 'function') return parallelCollectionScan(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + parallelCollectionScan(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var parallelCollectionScan = function(self, options, callback) { + // Create command object + var commandObject = { + parallelCollectionScan: self.s.name + , numCursors: options.numCursors + } + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Store the raw value + var raw = options.raw; + delete options['raw']; + + // Execute the command + self.s.db.command(commandObject, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null); + + var cursors = []; + // Add the raw back to the option + if(raw) options.raw = raw; + // 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 cmd = { + batchSize: options.batchSize + , cursorId: cursorId + , items: result.cursors[i].cursor.firstBatch + } + + // Add a command cursor + cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +define.classMethod('parallelCollectionScan', {callback: true, promise:true}); + +/** + * Execute the geoNear command to search for items in the collection + * + * @method + * @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 {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.num=null] Max number of results to return. + * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher) + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions. + * @param {object} [options.query=null] Filter the results by a query. + * @param {boolean} [options.spherical=false] Perform query using a spherical model. + * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X. + * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoNear = function(x, y, options, callback) { + var self = this; + var point = typeof(x) == 'object' && x + , args = Array.prototype.slice.call(arguments, point?1:2); + + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return geoNear(self, x, y, point, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + geoNear(self, x, y, point, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var geoNear = function(self, x, y, point, options, callback) { + // Build command object + var commandObject = { + geoNear:self.s.name, + near: point || [x, y] + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Exclude readPreference and existing options to prevent user from + // shooting themselves in the foot + var exclude = { + readPreference: true, + geoNear: true, + near: true + }; + + // Filter out any excluded objects + commandObject = decorateCommand(commandObject, options, exclude); + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) return handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +define.classMethod('geoNear', {callback: true, promise:true}); + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @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 {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {object} [options.search=null] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return geoHaystackSearch(self, x, y, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + geoHaystackSearch(self, x, y, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var geoHaystackSearch = function(self, x, y, options, callback) { + // Build command object + var commandObject = { + geoSearch: self.s.name, + near: [x, y] + } + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, {readPreference: true}); + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) handleCallback(callback, utils.toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +define.classMethod('geoHaystackSearch', {callback: true, promise:true}); + +/** + * 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(); + +/** + * Run a group command across a collection + * + * @method + * @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=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 3); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // 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 callback + if(typeof callback == 'function') return group(self, keys, condition, initial, reduce, finalize, command, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + group(self, keys, condition, initial, reduce, finalize, command, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) { + // Execute using the command + if(command) { + var reduceFunction = reduce instanceof Code + ? reduce + : new Code(reduce); + + var selector = { + group: { + 'ns': self.s.name + , '$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; + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + selector.readConcern = self.s.readConcern; + } + + // Execute command + self.s.db.command(selector, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + var scope = reduce != null && reduce instanceof Code + ? reduce.scope + : {}; + + scope.ns = self.s.name; + 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() + ';'); + + self.s.db.eval(new Code(groupfn, scope), function (err, results) { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +define.classMethod('group', {callback: true, promise:true}); + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope (scope) { + if(!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; +} + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query=null] Query filter object. + * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit=null] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize=null] Finalize function. + * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~resultCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + var self = this; + 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(); + } + + // Execute using callback + if(typeof callback == 'function') return mapReduce(self, map, reduce, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + mapReduce(self, map, reduce, options, function(err, r, r1) { + if(err) return reject(err); + if(r instanceof Collection) return resolve(r); + resolve({results: r, stats: r1}); + }); + }); +} + +var mapReduce = function(self, map, reduce, options, callback) { + var mapCommandHash = { + mapreduce: self.s.name + , map: map + , reduce: reduce + }; + + // Add any other options passed in + for(var n in options) { + if('scope' == n) { + mapCommandHash[n] = processScope(options[n]); + } else { + mapCommandHash[n] = options[n]; + } + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // If we have a read preference and inline is not set as output fail hard + if((options.readPreference != false && options.readPreference != 'primary') + && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { + options.readPreference = 'primary'; + } else if(self.s.readConcern) { + mapCommandHash.readConcern = self.s.readConcern; + } + + // Is bypassDocumentValidation specified + if(typeof options.bypassDocumentValidation == 'boolean') { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Execute command + self.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) { + if(err) return handleCallback(callback, err); + // Check if we have an error + if(1 != result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + var stats = {}; + if(result.timeMillis) stats['processtime'] = result.timeMillis; + if(result.counts) stats['counts'] = result.counts; + if(result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if(result.results) { + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, result.results, stats); + } + + // The returned collection + var collection = null; + + // If we have an object it's a different db + if(result.result != null && typeof result.result == 'object') { + var doc = result.result; + collection = self.s.db.db(doc.db).collection(doc.collection); + } else { + // Create a collection object that wraps the result collection + collection = self.s.db.collection(result.result) + } + + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, collection, stats); + }); +} + +define.classMethod('mapReduce', {callback: true, promise:true}); + +/** + * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @return {UnorderedBulkOperation} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return unordered(this.s.topology, this, options); +} + +define.classMethod('initializeUnorderedBulkOp', {callback: false, promise:false, returns: [ordered.UnorderedBulkOperation]}); + +/** + * 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. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return ordered(this.s.topology, this, options); +} + +define.classMethod('initializeOrderedBulkOp', {callback: false, promise:false, returns: [ordered.OrderedBulkOperation]}); + +// Get write concern +var writeConcern = function(target, db, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w != null) opts.w = options.w; + if(options.wtimeout != null) opts.wtimeout = options.wtimeout; + if(options.j != null) opts.j = options.j; + if(options.fsync != null) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Figure out the read preference +var getReadPreference = function(self, options, db, coll) { + var r = null + if(options.readPreference) { + r = options.readPreference + } else if(self.s.readPreference) { + r = self.s.readPreference + } else if(db.readPreference) { + r = db.readPreference; + } + + if(r instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else if(typeof r == 'string') { + options.readPreference = new CoreReadPreference(r); + } else if(r && !(r instanceof ReadPreference) && typeof r == 'object') { + var mode = r.mode || r.preference; + if (mode && typeof mode == 'string') { + options.readPreference = new CoreReadPreference(mode, r.tags); + } + } + + return options; +} + +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, 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 +} + +module.exports = Collection; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js new file mode 100644 index 0000000..94c5234 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js @@ -0,0 +1,320 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('./cursor') + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = CommandCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + } +} + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(CommandCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' + , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' + , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled']; + +// Only inherit the types we need +for(var i = 0; i < methodsToInherit.length; i++) { + CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; +} + +var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true); + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +CommandCursor.prototype.setReadPreference = function(r) { + if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(this.s.state != CommandCursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); + + if(r instanceof ReadPreference) { + this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else if(typeof r == 'string') { + this.s.options.readPreference = new CoreReadPreference(r); + } else if(r instanceof CoreReadPreference) { + this.s.options.readPreference = r; + } + + return this; +} + +define.classMethod('setReadPreference', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {CommandCursor} + */ +CommandCursor.prototype.batchSize = function(value) { + if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ +CommandCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]}); + +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +define.classMethod('get', {callback: true, promise:false}); + +// Inherited methods +define.classMethod('toArray', {callback: true, promise:true}); +define.classMethod('each', {callback: true, promise:false}); +define.classMethod('forEach', {callback: true, promise:false}); +define.classMethod('next', {callback: true, promise:true}); +define.classMethod('close', {callback: true, promise:true}); +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); +define.classMethod('rewind', {callback: false, promise:false}); +define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); +define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * 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. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * 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. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +CommandCursor.INIT = 0; +CommandCursor.OPEN = 1; +CommandCursor.CLOSED = 2; + +module.exports = CommandCursor; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/cursor.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/cursor.js new file mode 100644 index 0000000..c2d0deb --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/cursor.js @@ -0,0 +1,1199 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('mongodb-core').Cursor + , Map = require('mongodb-core').BSON.Map + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the mongodb-core and node.js + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +var fields = ['numberOfRetries', 'tailableRetryInterval']; +var push = Array.prototype.push; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Cursor cursor options. + * + * collection.find({}).project({a:1}) // Create a projection of field a + * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 + * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 + * collection.find({}).filter({a:1}) // Set query on the cursor + * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries + * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable + * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay + * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout + * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData + * collection.find({}).addCursorFlag('exhaust', true) // Set cursor as exhaust + * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial + * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} + * collection.find({}).max(10) // Set the cursor maxScan + * collection.find({}).maxScan(10) // Set the cursor maxScan + * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS + * collection.find({}).min(100) // Set the cursor min + * collection.find({}).returnKey(10) // Set the cursor returnKey + * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference + * collection.find({}).showRecordId(true) // Set the cursor showRecordId + * collection.find({}).snapshot(true) // Set the cursor snapshot + * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query + * collection.find({}).hint('a_1') // Set the cursor hint + * + * All options are chainable, so one can do the following. + * + * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = Cursor.INIT; + var streamOptions = {}; + + // Tailable cursor options + var numberOfRetries = options.numberOfRetries || 5; + var tailableRetryInterval = options.tailableRetryInterval || 500; + var currentNumberOfRetries = numberOfRetries; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries + , tailableRetryInterval: tailableRetryInterval + , currentNumberOfRetries: currentNumberOfRetries + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespace + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + // Current doc + , currentDoc: null + } + + // Legacy fields + this.timeout = self.s.options.noCursorTimeout == true; + this.sortValue = self.s.cmd.sort; +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(Cursor, Readable); + +// Map core cursor _next method so we can apply mapping +CoreCursor.prototype._next = CoreCursor.prototype.next; + +for(var name in CoreCursor.prototype) { + Cursor.prototype[name] = CoreCursor.prototype[name]; +} + +var define = Cursor.define = new Define('Cursor', Cursor, true); + +/** + * Check if there is any document still available in the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.hasNext = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') { + if(self.s.currentDoc){ + return callback(null, true); + } else { + return nextObject(self, function(err, doc) { + if(!doc) return callback(null, false); + self.s.currentDoc = doc; + callback(null, true); + }); + } + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + if(self.s.currentDoc){ + resolve(true); + } else { + nextObject(self, function(err, doc) { + if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false); + if(err) return reject(err); + if(!doc) return resolve(false); + self.s.currentDoc = doc; + resolve(true); + }); + } + }); +} + +define.classMethod('hasNext', {callback: true, promise:true}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.next = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') { + // Return the currentDoc if someone called hasNext first + if(self.s.currentDoc) { + var doc = self.s.currentDoc; + self.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + return nextObject(self, callback) + }; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + // Return the currentDoc if someone called hasNext first + if(self.s.currentDoc) { + var doc = self.s.currentDoc; + self.s.currentDoc = null; + return resolve(doc); + } + + nextObject(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('next', {callback: true, promise:true}); + +/** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ +Cursor.prototype.filter = function(filter) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.query = filter; + return this; +} + +define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor maxScan + * @method + * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query + * @return {Cursor} + */ +Cursor.prototype.maxScan = function(maxScan) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxScan = maxScan; + return this; +} + +define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor hint + * @method + * @param {object} hint If specified, then the query system will only consider plans using the hinted index. + * @return {Cursor} + */ +Cursor.prototype.hint = function(hint) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.hint = hint; + return this; +} + +define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor min + * @method + * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.min = function(min) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.min = min; + return this; +} + +define.classMethod('min', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor max + * @method + * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.max = function(max) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.max = max; + return this; +} + +define.classMethod('max', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor returnKey + * @method + * @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms: + * @return {Cursor} + */ +Cursor.prototype.returnKey = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.returnKey = value; + return this; +} + +define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor showRecordId + * @method + * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + * @return {Cursor} + */ +Cursor.prototype.showRecordId = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.showDiskLoc = value; + return this; +} + +define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor snapshot + * @method + * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. + * @return {Cursor} + */ +Cursor.prototype.snapshot = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.snapshot = value; + return this; +} + +define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setCursorOption = function(field, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true }); + this.s[field] = value; + if(field == 'numberOfRetries') + this.s.currentNumberOfRetries = value; + return this; +} + +define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addCursorFlag = function(flag, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true }); + if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true}); + this.s.cmd[flag] = value; + return this; +} + +define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addQueryModifier = function(name, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true}); + // Strip of the $ + var field = name.substr(1); + // Set on the command + this.s.cmd[field] = value; + // Deal with the special case for sort + if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field]; + return this; +} + +define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.comment = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.comment = value; + return this; +} + +define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * @method + * @param {number} value Number of milliseconds to wait before aborting the tailed query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxAwaitTimeMS = function(value) { + if(typeof value != 'number') throw MongoError.create({message: "maxAwaitTimeMS must be a number", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxAwaitTimeMS = value; + return this; +} + +define.classMethod('maxAwaitTimeMS', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxTimeMS = function(value) { + if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxTimeMS = value; + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]}); + +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.project = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.fields = value; + return this; +} + +define.classMethod('project', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.sort = function(keyOrList, direction) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + var order = keyOrList; + + // We have an array of arrays, we need to preserve the order of the sort + // so we will us a Map + if(Array.isArray(order) && Array.isArray(order[0])) { + order = new Map(order.map(function(x) { + var value = [x[0], null]; + if(x[1] == 'asc') { + value[1] = 1; + } else if(x[1] == 'desc') { + value[1] = -1; + } else if(x[1] == 1 || x[1] == -1) { + value[1] = x[1]; + } else { + throw new MongoError("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); + } + + return value; + })); + } + + if(direction != null) { + order = [[keyOrList, direction]]; + } + + this.s.cmd.sort = order; + this.sortValue = order; + return this; +} + +define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.batchSize = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true}); + if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); + this.s.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.limit = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true}); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true}); + this.s.cmd.limit = value; + // this.cursorLimit = value; + this.setCursorLimit(value); + return this; +} + +define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.skip = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true}); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true}); + this.s.cmd.skip = value; + this.setCursorSkip(value); + return this; +} + +define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]}); + +/** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null|boolean)} result The result object if the command was executed successfully. + */ + +/** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + +/** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @deprecated + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.nextObject = Cursor.prototype.next; + +var nextObject = function(self, callback) { + if(self.s.state == Cursor.CLOSED || self.isDead && self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); + if(self.s.state == Cursor.INIT && self.s.cmd.sort) { + try { + self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort); + } catch(err) { + return handleCallback(callback, err); + } + } + + // Get the next object + self._next(function(err, doc) { + if(err && err.tailable && self.s.currentNumberOfRetries == 0) return callback(err); + if(err && err.tailable && self.s.currentNumberOfRetries > 0) { + self.s.currentNumberOfRetries = self.s.currentNumberOfRetries - 1; + + return setTimeout(function() { + // Rewind the cursor only when it has not actually read any documents yet + if(self.cursorState.currentLimit == 0) self.rewind(); + // Read the next document, forcing a re-issue of query if no cursorId exists + self.nextObject(callback); + }, self.s.tailableRetryInterval); + } + + self.s.state = Cursor.OPEN; + if(err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +define.classMethod('nextObject', {callback: true, promise:true}); + +// 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.bufferedCount() == 0) return; + // Get the next document + self._next(callback); + // Loop + return loop; +} + +Cursor.prototype.next = Cursor.prototype.nextObject; + +define.classMethod('next', {callback: true, promise:true}); + +/** + * 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. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.each = function(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = Cursor.INIT; + // Run the query + _each(this, callback); +}; + +define.classMethod('each', {callback: true, promise:false}); + +// Run the each loop +var _each = function(self, callback) { + if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true}); + if(self.isNotified()) return; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); + } + + if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN; + + // Define function to avoid global scope escape + var fn = null; + // Trampoline all the entries + if(self.bufferedCount() > 0) { + while(fn = loop(self, callback)) fn(self, callback); + _each(self, callback); + } else { + self.next(function(err, item) { + if(err) return handleCallback(callback, err); + if(item == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, null); + } + + if(handleCallback(callback, null, item) == false) return; + _each(self, callback); + }) + } +} + +/** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.forEach = function(iterator, callback) { + this.each(function(err, doc){ + if(err) { callback(err); return false; } + if(doc != null) { iterator(doc); return true; } + if(doc == null && callback) { + var internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); +} + +define.classMethod('forEach', {callback: true, promise:false}); + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setReadPreference = function(r) { + if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); + if(r instanceof ReadPreference) { + this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else if(typeof r == 'string'){ + this.s.options.readPreference = new CoreReadPreference(r); + } else if(r instanceof CoreReadPreference) { + this.s.options.readPreference = r; + } + + return this; +} + +define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]}); + +/** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * 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. + * @method + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.toArray = function(callback) { + var self = this; + if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true}); + + // Execute using callback + if(typeof callback == 'function') return toArray(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + toArray(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var toArray = function(self, callback) { + var items = []; + + // Reset cursor + self.rewind(); + self.s.state = Cursor.INIT; + + // Fetch all the documents + var fetchDocs = function() { + self._next(function(err, doc) { + if(err) return handleCallback(callback, err); + if(doc == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, items); + } + + // Add doc to items + items.push(doc) + + // Get all buffered objects + if(self.bufferedCount() > 0) { + var docs = self.readBufferedDocuments(self.bufferedCount()) + + // Transform the doc if transform method added + if(self.s.transforms && typeof self.s.transforms.doc == 'function') { + docs = docs.map(self.s.transforms.doc); + } + + push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }) + } + + fetchDocs(); +} + +define.classMethod('toArray', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + +/** + * Get the count of documents for this cursor + * @method + * @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options=null] Optional settings. + * @param {number} [options.skip=null] The number of documents to skip. + * @param {number} [options.limit=null] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.count = function(applySkipLimit, opts, callback) { + var self = this; + if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true}); + if(typeof opts == 'function') callback = opts, opts = {}; + opts = opts || {}; + + // Execute using callback + if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + count(self, applySkipLimit, opts, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var count = function(self, applySkipLimit, opts, callback) { + if(typeof applySkipLimit == 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if(applySkipLimit) { + if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip(); + if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit(); + } + + // Command + var delimiter = self.s.ns.indexOf('.'); + + var command = { + 'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query + } + + if(typeof opts.maxTimeMS == 'number') { + command.maxTimeMS = opts.maxTimeMS; + } else if(self.s.cmd && typeof self.s.cmd.maxTimeMS == 'number') { + command.maxTimeMS = self.s.cmd.maxTimeMS; + } + + // Get a server + var server = self.s.topology.getServer(opts); + // Get a connection + var connection = self.s.topology.getConnection(opts); + // Get the callbacks + var callbacks = server.getCallbacks(); + + // Merge in any options + if(opts.skip) command.skip = opts.skip; + if(opts.limit) command.limit = opts.limit; + if(self.s.options.hint) command.hint = self.s.options.hint; + + // Build Query object + var query = new Query(self.s.bson, f("%s.$cmd", self.s.ns.substr(0, delimiter)), command, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false + }); + + // Set up callback + callbacks.register(query.requestId, function(err, result) { + if(err) return handleCallback(callback, err); + if(result.documents.length == 1 + && (result.documents[0].errmsg + || result.documents[0].err + || result.documents[0]['$err'])) { + return handleCallback(callback, MongoError.create(result.documents[0])); + } + handleCallback(callback, null, result.documents[0].n); + }); + + // Write the initial command out + connection.write(query.toBin()); +} + +define.classMethod('count', {callback: true, promise:true}); + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.close = function(callback) { + this.s.state = Cursor.CLOSED; + // Kill the cursor + this.kill(); + // Emit the close event for the cursor + this.emit('close'); + // Callback if provided + if(typeof callback == 'function') return handleCallback(callback, null, this); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + resolve(); + }); +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {null} + */ +Cursor.prototype.map = function(transform) { + this.cursorState.transforms = { doc: transform }; + return this; +} + +define.classMethod('map', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Is the cursor closed + * @method + * @return {boolean} + */ +Cursor.prototype.isClosed = function() { + return this.isDead(); +} + +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); + +Cursor.prototype.destroy = function(err) { + if(err) this.emit('error', err); + this.pause(); + this.close(); +} + +define.classMethod('destroy', {callback: false, promise:false}); + +/** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options=null] Optional settings. + * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ +Cursor.prototype.stream = function(options) { + this.s.streamOptions = options || {}; + return this; +} + +define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.explain = function(callback) { + var self = this; + this.s.cmd.explain = true; + + // Do we have a readConcern + if(this.s.cmd.readConcern) { + delete this.s.cmd['readConcern']; + } + + // Execute using callback + if(typeof callback == 'function') return this._next(callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self._next(function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('explain', {callback: true, promise:true}); + +Cursor.prototype._read = function(n) { + var self = this; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return self.push(null); + } + + // Get the next item + self.nextObject(function(err, result) { + if(err) { + if(self.listeners('error') && self.listeners('error').length > 0) { + self.emit('error', err); + } + if(!self.isDead()) self.close(); + + // Emit end event + self.emit('end'); + return self.emit('finish'); + } + + // If we provided a transformation method + if(typeof self.s.streamOptions.transform == 'function' && result != null) { + return self.push(self.s.streamOptions.transform(result)); + } + + // If we provided a map function + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) { + return self.push(self.cursorState.transforms.doc(result)); + } + + // Return the result + self.push(result); + }); +} + +Object.defineProperty(Cursor.prototype, 'readPreference', { + enumerable:true, + get: function() { + if (!this || !this.s) { + return null; + } + + return this.s.options.readPreference; + } +}); + +Object.defineProperty(Cursor.prototype, 'namespace', { + enumerable: true, + get: function() { + if (!this || !this.s) { + return null; + } + + // TODO: refactor this logic into core + var ns = this.s.ns || ''; + var firstDot = ns.indexOf('.'); + if (firstDot < 0) { + return { + database: this.s.ns, + collection: '' + }; + } + return { + database: ns.substr(0, firstDot), + collection: ns.substr(firstDot + 1) + }; + } +}); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +Cursor.INIT = 0; +Cursor.OPEN = 1; +Cursor.CLOSED = 2; +Cursor.GET_MORE = 3; + +module.exports = Cursor; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/db.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/db.js new file mode 100644 index 0000000..c253231 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/db.js @@ -0,0 +1,1807 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , getSingleProperty = require('./utils').getSingleProperty + , shallowClone = require('./utils').shallowClone + , parseIndexOptions = require('./utils').parseIndexOptions + , debugOptions = require('./utils').debugOptions + , CommandCursor = require('./command_cursor') + , handleCallback = require('./utils').handleCallback + , toError = require('./utils').toError + , ReadPreference = require('./read_preference') + , f = require('util').format + , Admin = require('./admin') + , Code = require('mongodb-core').BSON.Code + , CoreReadPreference = require('mongodb-core').ReadPreference + , MongoError = require('mongodb-core').MongoError + , ObjectID = require('mongodb-core').ObjectID + , Define = require('./metadata') + , Logger = require('mongodb-core').Logger + , Collection = require('./collection') + , crypto = require('crypto'); + +var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId' + , 'serializeFunctions', 'raw', 'promoteLongs', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds' + , 'readPreference', 'pkFactory']; + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * var testDb = db.db('test'); + * db.close(); + * }); + */ + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.native_parser=true] Select C++ bson parser instead of JavaScript parser. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {number} [options.bufferMaxEntries=-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. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @fires Db#close + * @fires Db#authenticated + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +var Db = function(databaseName, topology, options) { + options = options || {}; + if(!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + var self = this; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Ensure we put the promiseLib in the options + options.promiseLibrary = promiseLibrary; + + // var self = this; // Internal state of the db object + this.s = { + // Database name + databaseName: databaseName + // DbCache + , dbCache: {} + // Children db's + , children: [] + // Topology + , topology: topology + // Options + , options: options + // Logger instance + , logger: Logger('Db', options) + // Get the bson parser + , bson: topology ? topology.bson : null + // Authsource if any + , authSource: options.authSource + // Unpack read preference + , readPreference: options.readPreference + // Set buffermaxEntries + , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1 + // Parent db (if chained) + , parentDb: options.parentDb || null + // Set up the primary key factory or fallback to ObjectID + , pkFactory: options.pkFactory || ObjectID + // Get native parser + , nativeParser: options.nativeParser || options.native_parser + // Promise library + , promiseLibrary: promiseLibrary + // No listener + , noListener: typeof options.noListener == 'boolean' ? options.noListener : false + // ReadConcern + , readConcern: options.readConcern + } + + // Ensure we have a valid db name + validateDatabaseName(self.s.databaseName); + + // If we have specified the type of parser + if(typeof self.s.nativeParser == 'boolean') { + if(self.s.nativeParser) { + topology.setBSONParserType("c++"); + } else { + topology.setBSONParserType("js"); + } + } + + // Add a read Only property + getSingleProperty(this, 'serverConfig', self.s.topology); + getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', self.s.databaseName); + + // Last ismaster + Object.defineProperty(this, 'options', { + enumerable:true, + get: function() { return self.s.options; } + }); + + // Last ismaster + Object.defineProperty(this, 'native_parser', { + enumerable:true, + get: function() { return self.s.topology.parserType() == 'c++'; } + }); + + // Last ismaster + Object.defineProperty(this, 'slaveOk', { + enumerable:true, + get: function() { + if(self.s.options.readPreference != null + && (self.s.options.readPreference != 'primary' || self.s.options.readPreference.mode != 'primary')) { + return true; + } + return false; + } + }); + + Object.defineProperty(this, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(self.s.options.w != null) ops.w = self.s.options.w; + if(self.s.options.j != null) ops.j = self.s.options.j; + if(self.s.options.fsync != null) ops.fsync = self.s.options.fsync; + if(self.s.options.wtimeout != null) ops.wtimeout = self.s.options.wtimeout; + return ops; + } + }); + + // This is a child db, do not register any listeners + if(options.parentDb) return; + if(this.s.noListener) return; + + // Add listeners + topology.on('error', createListener(self, 'error', self)); + topology.on('timeout', createListener(self, 'timeout', self)); + topology.on('close', createListener(self, 'close', self)); + topology.on('parseError', createListener(self, 'parseError', self)); + topology.once('open', createListener(self, 'open', self)); + topology.once('fullsetup', createListener(self, 'fullsetup', self)); + topology.once('all', createListener(self, 'all', self)); + topology.on('reconnect', createListener(self, 'reconnect', self)); +} + +inherits(Db, EventEmitter); + +var define = Db.define = new Define('Db', Db, false); + +/** + * The callback format for the Db.open method + * @callback Db~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The Db instance if the open method was successful. + */ + +// Internal method +var open = function(self, callback) { + self.s.topology.connect(self, self.s.options, function(err, topology) { + if(callback == null) return; + var internalCallback = callback; + callback == null; + + if(err) { + self.close(); + return internalCallback(err); + } + + internalCallback(null, self); + }); +} + +/** + * Open the database + * @method + * @param {Db~openCallback} [callback] Callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.open = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return open(self, callback); + // Return promise + return new self.s.promiseLibrary(function(resolve, reject) { + open(self, function(err, db) { + if(err) return reject(err); + resolve(db); + }) + }); +} + +define.classMethod('open', {callback: true, promise:true}); + +/** + * Converts provided read preference to CoreReadPreference + * @param {(ReadPreference|string|object)} readPreference the user provided read preference + * @return {CoreReadPreference} + */ +var convertReadPreference = function(readPreference) { + if(readPreference && typeof readPreference == 'string') { + return new CoreReadPreference(readPreference); + } else if(readPreference instanceof ReadPreference) { + return new CoreReadPreference(readPreference.mode, readPreference.tags); + } else if(readPreference && typeof readPreference == 'object') { + var mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode == 'string') { + readPreference = new CoreReadPreference(mode, readPreference.tags); + } + } + return readPreference; +} + +/** + * The callback format for results + * @callback Db~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +var executeCommand = function(self, command, options, callback) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // Get the db name we are executing against + var dbName = options.dbName || options.authdb || self.s.databaseName; + // If we have a readPreference set + if(options.readPreference == null && self.s.readPreference) { + options.readPreference = self.s.readPreference; + } + + // Convert the readPreference + if(options.readPreference) { + options.readPreference = convertReadPreference(options.readPreference); + } + + // Debug information + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]' + , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options)))); + + // Execute command + self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) { + if(err) return handleCallback(callback, err); + if(options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); +} + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.command = function(command, options, callback) { + var self = this; + // Change the callback + if(typeof options == 'function') callback = options, options = {}; + // Clone the options + options = shallowClone(options); + + // Do we have a callback + if(typeof callback == 'function') return executeCommand(self, command, options, callback); + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeCommand(self, command, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('command', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Db~noResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {null} result Is not set to a value + */ + +/** + * Close the db and it's underlying connections + * @method + * @param {boolean} force Force close, emitting no events + * @param {Db~noResultCallback} [callback] The result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.close = function(force, callback) { + if(typeof force == 'function') callback = force, force = false; + this.s.topology.close(force); + var self = this; + + // Fire close event if any listeners + if(this.listeners('close').length > 0) { + this.emit('close'); + + // If it's the top level db emit close on all children + if(this.parentDb == null) { + // Fire close on all children + for(var i = 0; i < this.s.children.length; i++) { + this.s.children[i].emit('close'); + } + } + + // Remove listeners after emit + self.removeAllListeners('close'); + } + + // Close parent db if set + if(this.s.parentDb) this.s.parentDb.close(); + // Callback after next event loop tick + if(typeof callback == 'function') return process.nextTick(function() { + handleCallback(callback, null); + }) + + // Return dummy promise + return new this.s.promiseLibrary(function(resolve, reject) { + resolve(); + }); +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + return new Admin(this, this.s.topology, this.s.promiseLibrary); +}; + +define.classMethod('admin', {callback: false, promise:false, returns: [Admin]}); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * 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'); + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {Db~collectionResultCallback} callback The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + options = shallowClone(options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // If we have not set a collection level readConcern set the db level one + options.readConcern = options.readConcern || this.s.readConcern; + + // Do we have ignoreUndefined set + if(this.s.options.ignoreUndefined) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute + if(options == null || !options.strict) { + try { + var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.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 toError(f("A callback is required in strict mode. While getting collection %s.", name)); + } + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + // Strict mode + this.listCollections({name:name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null); + + try { + return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + } catch(err) { + return handleCallback(callback, err, null); + } + }); +} + +define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); + +var createCollection = function(self, name, options, callback) { + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self, options); + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // Check if we have the name + self.listCollections({name: name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length > 0 && finalOptions.strict) { + return handleCallback(callback, MongoError.create({message: f("Collection %s already exists. Currently in strict mode.", name), driver:true}), null); + } else if (collections.length > 0) { + try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); } + catch(err) { return handleCallback(callback, err); } + } + + // Create collection command + var cmd = {'create':name}; + + // Add all optional parameters + for(var n in options) { + if(options[n] != null && typeof options[n] != 'function') + cmd[n] = options[n]; + } + + // Execute command + self.command(cmd, finalOptions, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + }); + }); +} + +/** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {number} [options.size=null] The size of the capped collection in bytes. + * @param {number} [options.max=null] The maximum number of documents in the capped collection. + * @param {boolean} [options.autoIndexId=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. + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createCollection = function(name, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + name = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Do we have a promisesLibrary + options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; + + // Check if the callback is in fact a string + if(typeof callback == 'string') name = callback; + + // Execute the fallback callback + if(typeof callback == 'function') return createCollection(self, name, options, callback); + return new this.s.promiseLibrary(function(resolve, reject) { + createCollection(self, name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('createCollection', {callback: true, promise:true}); + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Db~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.stats = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // 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 + return this.command(commandObject, options, callback); +} + +define.classMethod('stats', {callback: true, promise:true}); + +// Transformation methods for cursor results +var listCollectionsTranforms = function(databaseName) { + var matching = f('%s.', databaseName); + + return { + doc: function(doc) { + var index = doc.name.indexOf(matching); + // Remove database name if available + if(doc.name && index == 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + } +} + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} filter Query to filter collections by + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + // Shallow clone the object + options = shallowClone(options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // Ensure valid readPreference + if(options.readPreference) { + options.readPreference = convertReadPreference(options.readPreference); + } + + // We have a list collections command + if(this.serverConfig.capabilities().hasListCollectionsCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listCollections : true, filter: filter, cursor: cursor }; + // Set the AggregationCursor constructor + options.cursorFactory = CommandCursor; + // Create the cursor + var cursor = this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options); + // Do we have a readPreference, apply it + if(options.readPreference) { + cursor.setReadPreference(options.readPreference); + } + // Return the cursor + return cursor; + } + + // We cannot use the listCollectionsCommand + if(!this.serverConfig.capabilities().hasListCollectionsCommand) { + // If we have legacy mode and have not provided a full db name filter it + if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) { + filter = shallowClone(filter); + filter.name = f('%s.%s', this.s.databaseName, filter.name); + } + } + + // No filter, filter by current database + if(filter == null) { + filter.name = f('/%s/', this.s.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: listCollectionsTranforms(this.s.databaseName)} + // Get the cursor + var cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options); + // Do we have a readPreference, apply it + if(options.readPreference) cursor.setReadPreference(options.readPreference); + // 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; +}; + +define.classMethod('listCollections', {callback: false, promise:false, returns: [CommandCursor]}); + +var evaluate = function(self, code, parameters, options, callback) { + var finalCode = code; + var finalParameters = []; + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // If not a code object translate to one + if(!(finalCode instanceof Code)) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if(parameters != null && Array.isArray(parameters) && 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 = new CoreReadPreference(ReadPreference.PRIMARY); + + // Execute the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result && result.ok == 1) return handleCallback(callback, null, result.retval); + if(result) return handleCallback(callback, MongoError.create({message: f("eval failed: %s", result.errmsg), driver:true}), null); + handleCallback(callback, err, result); + }); +} + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.eval = function(code, parameters, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + // Check if the callback is in fact a string + if(typeof callback == 'function') return evaluate(self, code, parameters, options, callback); + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + evaluate(self, code, parameters, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('eval', {callback: true, promise:true}); + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Add return new collection + options.new_collection = true; + + // Check if the callback is in fact a string + if(typeof callback == 'function') { + return this.collection(fromCollection).rename(toCollection, options, callback); + } + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.collection(fromCollection).rename(toCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('renameCollection', {callback: true, promise:true}); + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropCollection = function(name, callback) { + var self = this; + + // Command to execute + var cmd = {'drop':name} + + // Check if the callback is in fact a string + if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(err) return handleCallback(callback, err); + if(result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); + + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + // Execute command + self.command(cmd, self.s.options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + if(result.ok) return resolve(true); + resolve(false); + }); + }); +}; + +define.classMethod('dropCollection', {callback: true, promise:true}); + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropDatabase = function(callback) { + var self = this; + // Drop database command + var cmd = {'dropDatabase':1}; + + // Check if the callback is in fact a string + if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); + + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + // Execute command + self.command(cmd, self.s.options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + if(result.ok) return resolve(true); + resolve(false); + }); + }); +} + +define.classMethod('dropDatabase', {callback: true, promise:true}); + +/** + * The callback format for the collections method. + * @callback Db~collectionsResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection[]} collections An array of all the collections objects for the db instance. + */ +var collections = function(self, callback) { + // Let's get the collection names + self.listCollections().toArray(function(err, documents) { + if(err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(function(doc) { + return doc.name.indexOf('$') == -1; + }); + + // Return the collection objects + handleCallback(callback, null, documents.map(function(d) { + return new Collection(self, self.s.topology, self.s.databaseName, d.name.replace(self.s.databaseName + ".", ''), self.s.pkFactory, self.s.options); + })); + }); +} + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.collections = function(callback) { + var self = this; + + // Return the callback + if(typeof callback == 'function') return collections(self, callback); + // Return the promise + return new self.s.promiseLibrary(function(resolve, reject) { + collections(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('collections', {callback: true, promise:true}); + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Ensure valid readPreference + if(options.readPreference + && !(options.readPreference instanceof ReadPreference) + && typeof options.readPreference == 'object') { + var mode = options.readPreference.mode || options.readPreference.preference; + if (mode && typeof mode == 'string') { + options.readPreference = new ReadPreference(mode, readPreference.tags); + } + } + + // Return the callback + if(typeof callback == 'function') return self.s.topology.command('admin.$cmd', selector, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); + + // Return promise + return new self.s.promiseLibrary(function(resolve, reject) { + self.s.topology.command('admin.$cmd', selector, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + resolve(result.result); + }); + }); +}; + +define.classMethod('executeDbAdminCommand', {callback: true, promise:true}); + +/** + * Creates an index on the db and collection collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + // Shallow clone the options + options = shallowClone(options); + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + // If we have a callback fallback + if(typeof callback == 'function') return createIndex(self, name, fieldOrSpec, options, callback); + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndex(self, name, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var createIndex = function(self, name, fieldOrSpec, options, callback) { + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Ensure we have a callback + if(finalOptions.writeConcern && typeof callback != 'function') { + throw MongoError.create({message: "Cannot use a writeConcern without a provided callback", driver:true}); + } + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) { + if(err == null) return handleCallback(callback, err, result); + // Create command + var doc = createCreateIndexCommand(self, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + }); + }); +} + +define.classMethod('createIndex', {callback: true, promise:true}); + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // If we have a callback fallback + if(typeof callback == 'function') return ensureIndex(self, name, fieldOrSpec, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + ensureIndex(self, name, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var ensureIndex = function(self, name, fieldOrSpec, options, callback) { + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Create command + var selector = createCreateIndexCommand(self, name, fieldOrSpec, options); + var index_name = selector.name; + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // Default command options + var commandOptions = {}; + // Check if the index allready exists + self.indexInformation(name, finalOptions, function(err, indexInformation) { + if(err != null && err.code != 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if(indexInformation == null || !indexInformation[index_name]) { + self.createIndex(name, fieldOrSpec, options, callback); + } else { + if(typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +} + +define.classMethod('ensureIndex', {callback: true, promise:true}); + +Db.prototype.addChild = function(db) { + if(this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +} + +/** + * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are + * related in a parent-child relationship to the original instance so that events are correctly emitted on child + * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. + * You can control these behaviors with the options noListener and returnNonCachedInstance. + * + * @method + * @param {string} name The name of the database we want to use. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {Db} + */ +Db.prototype.db = function(dbName, options) { + options = options || {}; + // Copy the options and add out internal override of the not shared flag + for(var key in this.options) { + options[key] = this.options[key]; + } + + // Do we have the db in the cache already + if(this.s.dbCache[dbName] && options.returnNonCachedInstance !== true) { + return this.s.dbCache[dbName]; + } + + // Add current db as parentDb + if(options.noListener == null || options.noListener == false) { + options.parentDb = this; + } + + // Add promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Return the db object + var db = new Db(dbName, this.s.topology, options) + + // Add as child + if(options.noListener == null || options.noListener == false) { + this.addChild(db); + } + + // Add the db to the cache + this.s.dbCache[dbName] = db; + // Return the database + return db; +}; + +define.classMethod('db', {callback: false, promise:false, returns: [Db]}); + +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') { + 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 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 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 + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // 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; + } + + // Force write using primary + commandOptions.readPreference = CoreReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, !result.ok ? toError(result) : null + , result.ok ? [{user: username, pwd: ''}] : null); + }) +} + +var addUser = function(self, username, password, options, callback) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // Attempt to execute auth command + _executeAuthCreateUserCommand(self, username, password, options, function(err, r) { + // We need to perform the backward compatible insert operation + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var userPassword = md5.digest('hex'); + + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.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 handleCallback(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 handleCallback(callback, err, null); + // Add command keys + finalOptions.upsert = true; + + // We have a user, let's update the password or upsert if not + collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err, results, full) { + if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]); + if(err) return handleCallback(callback, err, null) + handleCallback(callback, null, [{user:username, pwd:userPassword}]); + }); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, r); + }); +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.addUser = function(username, password, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // If we have a callback fallback + if(typeof callback == 'function') return addUser(self, username, password, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + addUser(self, username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('addUser', {callback: true, promise:true}); + +var _executeAuthRemoveUserCommand = function(self, username, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // Get the error 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 + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // Force write using primary + commandOptions.readPreference = CoreReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000}); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }) +} + +var removeUser = function(self, username, options, callback) { + // Attempt to execute command + _executeAuthRemoveUserCommand(self, username, options, function(err, result) { + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.SYSTEM_USER_COLLECTION); + + // Locate the user + collection.findOne({user: username}, {}, function(err, user) { + if(user == null) return handleCallback(callback, err, false); + collection.remove({user: username}, finalOptions, function(err, result) { + handleCallback(callback, err, true); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, result); + }); +} + +define.classMethod('removeUser', {callback: true, promise:true}); + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.removeUser = function(username, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // If we have a callback fallback + if(typeof callback == 'function') return removeUser(self, username, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + removeUser(self, username, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var authenticate = function(self, username, password, options, callback) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // the default db to authenticate against is 'self' + // if authententicate is called from a retry context, it may be another one, like admin + var authdb = options.authdb ? options.authdb : options.dbName; + authdb = options.authSource ? options.authSource : authdb; + authdb = authdb ? authdb : self.databaseName; + + // Callback + var _callback = function(err, result) { + if(self.listeners('authenticated').length > 0) { + self.emit('authenticated', err, result); + } + + // Return to caller + handleCallback(callback, err, result); + } + + // authMechanism + var authMechanism = options.authMechanism || ''; + authMechanism = authMechanism.toUpperCase(); + + // If classic auth delegate to auth command + if(authMechanism == 'MONGODB-CR') { + self.s.topology.auth('mongocr', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'PLAIN') { + self.s.topology.auth('plain', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'MONGODB-X509') { + self.s.topology.auth('x509', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'SCRAM-SHA-1') { + self.s.topology.auth('scram-sha-1', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'GSSAPI') { + if(process.platform == 'win32') { + self.s.topology.auth('sspi', authdb, username, password, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + self.s.topology.auth('gssapi', authdb, username, password, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } + } else if(authMechanism == 'DEFAULT') { + self.s.topology.auth('default', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + handleCallback(callback, MongoError.create({message: f("authentication mechanism %s not supported", options.authMechanism), driver:true})); + } +} + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.authenticate = function(username, password, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + // Shallow copy the options + options = shallowClone(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 handleCallback(callback, MongoError.create({message: "only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism", driver:true})); + } + + // If we have a callback fallback + if(typeof callback == 'function') return authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; + // Reject error + if(err) return callback(err, r); + callback(null, r); + }); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; + // Reject error + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('authenticate', {callback: true, promise:true}); + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {object} [options=null] Optional settings. + * @param {string} [options.dbName=null] Logout against different database than current. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.logout = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // logout command + var cmd = {'logout':1}; + + // Add onAll to login to ensure all connection are logged out + options.onAll = true; + + // We authenticated against a different db use that + if(this.s.authSource) options.dbName = this.s.authSource; + + // Execute the command + if(typeof callback == 'function') return this.command(cmd, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true) + }); + + // Return promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.command(cmd, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + resolve(true); + }); + }); +} + +define.classMethod('logout', {callback: true, promise:true}); + +// Figure out the read preference +var getReadPreference = function(options, db) { + if(options.readPreference) return options; + if(db.readPreference) options.readPreference = db.readPreference; + return options; +} + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.indexInformation = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // If we have a callback fallback + if(typeof callback == 'function') return indexInformation(self, name, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexInformation(self, name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var indexInformation = function(self, name, options, callback) { + // If we specified full information + var full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // 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 + self.collection(name).listIndexes().toArray(function(err, indexes) { + if(err) return callback(toError(err)); + if(!Array.isArray(indexes)) return handleCallback(callback, null, []); + if(full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +define.classMethod('indexInformation', {callback: true, promise:true}); + +var createCreateIndexCommand = function(db, name, fieldOrSpec, options) { + var indexParameters = 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 + "." + name, '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; + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) { + // Build the index + var indexParameters = 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]; + } + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete indexes[0][removeKeys[i]]; + } + } + + // Create command + var cmd = {createIndexes: name, indexes: indexes}; + + // Apply write concern to command + cmd = writeConcern(cmd, self, options); + + // Build the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result.ok == 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +// Validate the database name +var validateDatabaseName = function(databaseName) { + if(typeof databaseName !== 'string') throw MongoError.create({message: "database name must be a string", driver:true}); + if(databaseName.length === 0) throw MongoError.create({message: "database name cannot be the empty string", driver:true}); + if(databaseName == '$external') return; + + var invalidChars = [" ", ".", "$", "/", "\\"]; + for(var i = 0; i < invalidChars.length; i++) { + if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true}); + } +} + +// Get write concern +var writeConcern = function(target, db, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w) opts.w = options.w; + if(options.wtimeout) opts.wtimeout = options.wtimeout; + if(options.j) opts.j = options.j; + if(options.fsync) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Add listeners to topology +var createListener = function(self, e, object) { + var listener = function(err) { + if(e != 'error') { + object.emit(e, err, self); + + // Emit on all associated db's if available + for(var i = 0; i < self.s.children.length; i++) { + self.s.children[i].emit(e, err, self.s.children[i]); + } + } + } + return listener; +} + +/** + * Db close event + * + * Emitted after a socket closed against a single server or mongos proxy. + * + * @event Db#close + * @type {MongoError} + */ + +/** + * Db authenticated event + * + * Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated. + * + * @event Db#authenticated + * @type {object} + */ + +/** + * Db reconnect event + * + * * Server: Emitted when the driver has reconnected and re-authenticated. + * * ReplicaSet: N/A + * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * Emitted after an error occurred against a single server or mongos proxy. + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * Emitted after a socket timeout occurred against a single server or mongos proxy. + * + * @event Db#timeout + * @type {MongoError} + */ + +/** + * Db parseError event + * + * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. + * + * @event Db#parseError + * @type {MongoError} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. + * + * * Server: Emitted when the driver has connected to the single server and has authenticated. + * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. + * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; +Db.SYSTEM_INDEX_COLLECTION = "system.indexes"; +Db.SYSTEM_PROFILE_COLLECTION = "system.profile"; +Db.SYSTEM_USER_COLLECTION = "system.users"; +Db.SYSTEM_COMMAND_COLLECTION = "$cmd"; +Db.SYSTEM_JS_COLLECTION = "system.js"; + +module.exports = Db; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js new file mode 100644 index 0000000..3c9d64b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js @@ -0,0 +1,310 @@ +var shallowClone = require('../utils').shallowClone; +var stream = require('stream'); +var util = require('util'); + +module.exports = GridFSBucketReadStream; + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * + * @class + * @param {Collection} chunks Handle for chunks collection + * @param {Collection} files Handle for files collection + * @param {Object} readPreference The read preference to use + * @param {Object} filter The query to use to find the file document + * @param {Object} [options=null] Optional settings. + * @param {Number} [options.sort=null] Optional sort for the file find query + * @param {Number} [options.skip=null] Optional skip for the file find query + * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before + * @fires GridFSBucketReadStream#error + * @fires GridFSBucketReadStream#file + * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. + */ + +function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { + var _this = this; + this.s = { + bytesRead: 0, + chunks: chunks, + cursor: null, + expected: 0, + files: files, + filter: filter, + init: false, + expectedEnd: 0, + file: null, + options: options, + readPreference: readPreference + }; + + stream.Readable.call(this); +} + +util.inherits(GridFSBucketReadStream, stream.Readable); + +/** + * An error occurred + * + * @event GridFSBucketReadStream#error + * @type {Error} + */ + +/** + * Fires when the stream loaded the file document corresponding to the + * provided id. + * + * @event GridFSBucketReadStream#file + * @type {object} + */ + +/** + * Reads from the cursor and pushes to the stream. + * @method + */ + +GridFSBucketReadStream.prototype._read = function() { + var _this = this; + waitForFile(_this, function() { + doRead(_this); + }); +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} start Offset in bytes to start reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.start = function(start) { + throwIfInitialized(this); + this.s.options.start = start; + return this; +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} end Offset in bytes to stop reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.end = function(end) { + throwIfInitialized(this); + this.s.options.end = end; + return this; +}; + +/** + * @ignore + */ + +function throwIfInitialized(self) { + if (self.s.init) { + throw new Error('You cannot change options after the stream has entered' + + 'flowing mode!'); + } +} + +/** + * @ignore + */ + +function doRead(_this) { + _this.s.cursor.next(function(error, doc) { + if (error) { + return __handleError(_this, error); + } + if (!doc) { + return _this.push(null); + } + + var bytesRemaining = _this.s.file.length - _this.s.bytesRead; + var expectedN = _this.s.expected++; + var expectedLength = Math.min(_this.s.file.chunkSize, + bytesRemaining); + if (doc.n > expectedN) { + var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + if (doc.n < expectedN) { + var errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + if (doc.data.length() !== expectedLength) { + if (bytesRemaining <= 0) { + var errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; + return __handleError(_this, new Error(errmsg)); + } + var errmsg = 'ChunkIsWrongSize: Got unexpected length: ' + + doc.data.length() + ', expected: ' + expectedLength; + return __handleError(_this, new Error(errmsg)); + } + + _this.s.bytesRead += doc.data.length(); + + if (doc.data.buffer.length === 0) { + return _this.push(null); + } + + var sliceStart = null; + var sliceEnd = null; + var buf = doc.data.buffer; + if (_this.s.bytesToSkip != null) { + sliceStart = _this.s.bytesToSkip; + _this.s.bytesToSkip = 0; + } + + if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) { + sliceEnd = _this.s.bytesToTrim; + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); + } + + _this.push(buf); + }); +}; + +/** + * @ignore + */ + +function init(self) { + var findOneOptions = {}; + if (self.s.readPreference) { + findOneOptions.readPreference = self.s.readPreference; + } + if (self.s.options && self.s.options.sort) { + findOneOptions.sort = self.s.options.sort; + } + if (self.s.options && self.s.options.skip) { + findOneOptions.skip = self.s.options.skip; + } + + self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { + if (error) { + return __handleError(self, error); + } + if (!doc) { + var identifier = self.s.filter._id ? + self.s.filter._id.toString() : self.s.filter.filename; + var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; + return __handleError(self, new Error(errmsg)); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + self.push(null); + return; + } + + self.s.cursor = self.s.chunks.find({ files_id: doc._id }).sort({ n: 1 }); + if (self.s.readPreference) { + self.s.cursor.setReadPreference(self.s.readPreference); + } + + self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + self.s.file = doc; + self.s.bytesToSkip = handleStartOption(self, doc, self.s.cursor, + self.s.options); + self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, + self.s.options); + self.emit('file', doc); + }); +} + +/** + * @ignore + */ + +function waitForFile(_this, callback) { + if (_this.s.file) { + return callback(); + } + + if (!_this.s.init) { + init(_this); + _this.s.init = true; + } + + _this.once('file', function() { + callback(); + }); +}; + +/** + * @ignore + */ + +function handleStartOption(stream, doc, cursor, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new Error('Stream start (' + options.start + ') must not be ' + + 'more than the length of the file (' + doc.length +')') + } + if (options.start < 0) { + throw new Error('Stream start (' + options.start + ') must not be ' + + 'negative'); + } + if (options.end != null && options.end < options.start) { + throw new Error('Stream start (' + options.start + ') must not be ' + + 'greater than stream end (' + options.end + ')'); + } + + cursor.skip(Math.floor(options.start / doc.chunkSize)); + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * + doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } +} + +/** + * @ignore + */ + +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new Error('Stream end (' + options.end + ') must not be ' + + 'more than the length of the file (' + doc.length +')') + } + if (options.start < 0) { + throw new Error('Stream end (' + options.end + ') must not be ' + + 'negative'); + } + + var start = options.start != null ? + Math.floor(options.start / doc.chunkSize) : + 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return (Math.ceil(options.end / doc.chunkSize) * doc.chunkSize) - + options.end; + } +} + +/** + * @ignore + */ + +function __handleError(_this, error) { + _this.emit('error', error); +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js new file mode 100644 index 0000000..8d330ed --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js @@ -0,0 +1,335 @@ +var Emitter = require('events').EventEmitter; +var GridFSBucketReadStream = require('./download'); +var GridFSBucketWriteStream = require('./upload'); +var shallowClone = require('../utils').shallowClone; +var toError = require('../utils').toError; +var util = require('util'); + +var DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +module.exports = GridFSBucket; + +/** + * Constructor for a streaming GridFS interface + * @class + * @param {Db} db A db handle + * @param {object} [options=null] Optional settings. + * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. + * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB + * @param {object} [options.writeConcern=null] Optional write concern to be passed to write operations, for instance `{ w: 1 }` + * @param {object} [options.readPreference=null] Optional read preference to be passed to read operations + * @fires GridFSBucketWriteStream#index + * @return {GridFSBucket} + */ + +function GridFSBucket(db, options) { + Emitter.apply(this); + this.setMaxListeners(0); + + if (options && typeof options === 'object') { + options = shallowClone(options); + var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); + for (var i = 0; i < keys.length; ++i) { + if (!options[keys[i]]) { + options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; + } + } + } else { + options = DEFAULT_GRIDFS_BUCKET_OPTIONS; + } + + this.s = { + db: db, + options: options, + _chunksCollection: db.collection(options.bucketName + '.chunks'), + _filesCollection: db.collection(options.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false, + promiseLibrary: db.s.promiseLibrary || + (typeof global.Promise == 'function' ? global.Promise : require('es6-promise').Promise) + }; +}; + +util.inherits(GridFSBucket, Emitter); + +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * + * @event GridFSBucket#index + * @type {Error} + */ + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options=null] Optional settings. + * @param {number} [options.chunkSizeBytes=null] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata=null] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType=null] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases=null] Optional array of strings to store in the file document's `aliases` field + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStream = function(filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming file + * data from GridFS. + * @method + * @param {ObjectId} id The id of the file doc + * @param {Object} [options=null] Optional settings. + * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStream = function(id, options) { + var filter = { _id: id }; + var options = { + start: options && options.start, + end: options && options.end + }; + return new GridFSBucketReadStream(this.s._chunksCollection, + this.s._filesCollection, this.s.options.readPreference, filter, options); +}; + +/** + * Deletes a file with the given id + * @method + * @param {ObjectId} id The id of the file doc + * @param {Function} callback + */ + +GridFSBucket.prototype.delete = function(id, callback) { + if (typeof callback === 'function') { + return _delete(this, id, callback); + } + + var _this = this; + return new this.s.promiseLibrary(function(resolve, reject) { + _delete(_this, id, function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * @ignore + */ + +function _delete(_this, id, callback) { + _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { + if (error) { + return callback(error); + } + + _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { + if (error) { + return callback(error); + } + + // Delete orphaned chunks before returning FileNotFound + if (!res.result.n) { + var errmsg = 'FileNotFound: no file with id ' + id + ' found'; + return callback(new Error(errmsg)); + } + + callback(); + }); + }); +} + +/** + * Convenience wrapper around find on the files collection + * @method + * @param {Object} filter + * @param {Object} [options=null] Optional settings for cursor + * @param {number} [options.batchSize=null] Optional batch size for cursor + * @param {number} [options.limit=null] Optional limit for cursor + * @param {number} [options.maxTimeMS=null] Optional maxTimeMS for cursor + * @param {boolean} [options.noCursorTimeout=null] Optionally set cursor's `noCursorTimeout` flag + * @param {number} [options.skip=null] Optional skip for cursor + * @param {object} [options.sort=null] Optional sort for cursor + * @return {Cursor} + */ + +GridFSBucket.prototype.find = function(filter, options) { + filter = filter || {}; + options = options || {}; + + var cursor = this.s._filesCollection.find(filter); + + if (options.batchSize != null) { + cursor.batchSize(options.batchSize); + } + if (options.limit != null) { + cursor.limit(options.limit); + } + if (options.maxTimeMS != null) { + cursor.maxTimeMS(options.maxTimeMS); + } + if (options.noCursorTimeout != null) { + cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); + } + if (options.skip != null) { + cursor.skip(options.skip); + } + if (options.sort != null) { + cursor.sort(options.sort); + } + + return cursor; +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadedDate` field). You can set the `revision` + * option to change this behavior. + * @method + * @param {String} filename The name of the file to stream + * @param {Object} [options=null] Optional settings + * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. + * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { + var sort = { uploadedDate: -1 }; + var skip = null; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadedDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + + var filter = { filename: filename }; + var options = { + sort: sort, + skip: skip, + start: options && options.start, + end: options && options.end + }; + return new GridFSBucketReadStream(this.s._chunksCollection, + this.s._filesCollection, this.s.options.readPreference, filter, options); +}; + +/** + * Renames the file with the given _id to the given string + * @method + * @param {ObjectId} id the id of the file to rename + * @param {String} filename new name for the file + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.rename = function(id, filename, callback) { + if (typeof callback === 'function') { + return _rename(this, id, filename, callback); + } + + var _this = this; + return new this.s.promiseLibrary(function(resolve, reject) { + _rename(_this, id, filename, function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * @ignore + */ + +function _rename(_this, id, filename, callback) { + var filter = { _id: id }; + var update = { $set: { filename: filename } }; + _this.s._filesCollection.updateOne(filter, update, function(error, res) { + if (error) { + return callback(error); + } + if (!res.result.n) { + return callback(toError('File with id ' + id + ' not found')); + } + callback(); + }); +} + +/** + * Removes this bucket's files collection, followed by its chunks collection. + * @method + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.drop = function(callback) { + if (typeof callback === 'function') { + return _drop(this, callback); + } + + var _this = this; + return new this.s.promiseLibrary(function(resolve, reject) { + _drop(_this, function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * @ignore + */ + +function _drop(_this, callback) { + _this.s._filesCollection.drop(function(error) { + if (error) { + return callback(error); + } + _this.s._chunksCollection.drop(function(error) { + if (error) { + return callback(error); + } + + return callback(); + }); + }); +} + +/** + * Callback format for all GridFSBucket methods that can accept a callback. + * @callback GridFSBucket~errorCallback + * @param {MongoError} error An error instance representing any errors that occurred + */ diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js new file mode 100644 index 0000000..5395c6a --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js @@ -0,0 +1,449 @@ +var core = require('mongodb-core'); +var crypto = require('crypto'); +var shallowClone = require('../utils').shallowClone; +var stream = require('stream'); +var util = require('util'); + +var ERROR_NAMESPACE_NOT_FOUND = 26; + +module.exports = GridFSBucketWriteStream; + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * + * @class + * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options=null] Optional settings. + * @param {number} [options.chunkSizeBytes=null] The chunk size to use, in bytes + * @param {number} [options.w=null] The write concern + * @param {number} [options.wtimeout=null] The write concern timeout + * @param {number} [options.j=null] The journal write concern + * @fires GridFSBucketWriteStream#error + * @fires GridFSBucketWriteStream#finish + * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. + */ + +function GridFSBucketWriteStream(bucket, filename, options) { + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + + this.id = core.BSON.ObjectId(); + this.chunkSizeBytes = this.options.chunkSizeBytes; + this.bufToStore = new Buffer(this.chunkSizeBytes); + this.length = 0; + this.md5 = crypto.createHash('md5'); + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + var _this = this; + checkIndexes(this, function() { + _this.bucket.s.checkedIndexes = true; + _this.bucket.emit('index'); + }); + } +} + +util.inherits(GridFSBucketWriteStream, stream.Writable); + +/** + * An error occurred + * + * @event GridFSBucketWriteStream#error + * @type {Error} + */ + +/** + * end() was called and the write stream successfully wrote all chunks to + * MongoDB. + * + * @event GridFSBucketWriteStream#finish + * @type {object} + */ + +/** + * Write a buffer to the stream. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. + */ + +GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { + var _this = this; + return waitForIndexes(this, function() { + return doWrite(_this, chunk, encoding, callback); + }); +}; + +/** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB + */ + +GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { + var _this = this; + this.state.streamEnd = true; + + if (callback) { + this.once('finish', callback); + } + + if (!chunk) { + waitForIndexes(this, function() { + writeRemnant(_this); + }); + return; + } + + var _this = this; + var inputBuf = (Buffer.isBuffer(chunk)) ? + chunk : new Buffer(chunk, encoding); + + this.write(chunk, encoding, function() { + writeRemnant(_this); + }); +}; + +/** + * @ignore + */ + +function __handleError(_this, error, callback) { + if (_this.state.errored) { + return; + } + _this.state.errored = true; + if (callback) { + return callback(error); + } + _this.emit('error', error); +} + +/** + * @ignore + */ + +function createChunkDoc(filesId, n, data) { + return { + _id: core.BSON.ObjectId(), + files_id: filesId, + n: n, + data: data + }; +} + +/** + * @ignore + */ + +function checkChunksIndex(_this, callback) { + _this.chunks.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { files_id: 1, n: 1 }; + _this.chunks.createIndex(index, { background: false }, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + return; + } + return callback(error); + } + + var hasChunksIndex = false; + indexes.forEach(function(index) { + if (index.key) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && + index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + + if (hasChunksIndex) { + callback(); + } else { + var index = { files_id: 1, n: 1 }; + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + indexOptions.unique = true; + + _this.chunks.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + } + }); +} + +/** + * @ignore + */ + +function checkDone(_this, callback) { + if (_this.state.streamEnd && + _this.state.outstandingRequests === 0 && + !_this.state.errored) { + var filesDoc = createFilesDoc(_this.id, _this.length, _this.chunkSizeBytes, + _this.md5.digest('hex'), _this.filename, _this.options.contentType, + _this.options.aliases, _this.options.metadata); + + _this.files.insert(filesDoc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error, callback); + } + _this.emit('finish', filesDoc); + }); + + return true; + } + + return false; +} + +/** + * @ignore + */ + +function checkIndexes(_this, callback) { + _this.files.findOne({}, { _id: 1 }, function(error, doc) { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + + _this.files.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { filename: 1, uploadDate: 1 }; + _this.files.createIndex(index, { background: false }, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + return; + } + return callback(error); + } + + var hasFileIndex = false; + indexes.forEach(function(index) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && + index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + + if (hasFileIndex) { + checkChunksIndex(_this, callback); + } else { + var index = { filename: 1, uploadDate: 1 }; + + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + + _this.files.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + } + }); + }); +} + +/** + * @ignore + */ + +function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, + aliases, metadata) { + var ret = { + _id: _id, + length: length, + chunkSize: chunkSize, + uploadDate: new Date(), + md5: md5, + filename: filename + }; + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +/** + * @ignore + */ + +function doWrite(_this, chunk, encoding, callback) { + var inputBuf = (Buffer.isBuffer(chunk)) ? + chunk : new Buffer(chunk, encoding); + + _this.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { + inputBuf.copy(_this.bufToStore, _this.pos); + _this.pos += inputBuf.length; + + callback && callback(); + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + var inputBufRemaining = inputBuf.length; + var spaceRemaining = _this.chunkSizeBytes - _this.pos; + var numToCopy = Math.min(spaceRemaining, inputBuf.length); + var outstandingRequests = 0; + while (inputBufRemaining > 0) { + var inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(_this.bufToStore, _this.pos, + inputBufPos, inputBufPos + numToCopy); + _this.pos += numToCopy; + spaceRemaining -= numToCopy; + if (spaceRemaining === 0) { + _this.md5.update(_this.bufToStore); + var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); + ++_this.state.outstandingRequests; + ++outstandingRequests; + + _this.chunks.insert(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + --outstandingRequests; + if (!outstandingRequests) { + _this.emit('drain', doc); + callback && callback(); + checkDone(_this); + } + }); + + spaceRemaining = _this.chunkSizeBytes; + _this.pos = 0; + ++_this.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} + +/** + * @ignore + */ + +function getWriteOptions(_this) { + var obj = {}; + if (_this.options.writeConcern) { + obj.w = concern.w; + obj.wtimeout = concern.wtimeout; + obj.j = concern.j; + } + return obj; +} + +/** + * @ignore + */ + +function waitForIndexes(_this, callback) { + if (_this.bucket.s.checkedIndexes) { + return callback(false); + } + + _this.bucket.once('index', function() { + callback(true); + }); + + return true; +} + +/** + * @ignore + */ + +function writeRemnant(_this, callback) { + // Buffer is empty, so don't bother to insert + if (_this.pos === 0) { + return checkDone(_this, callback); + } + + ++_this.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + var remnant = new Buffer(_this.pos); + _this.bufToStore.copy(remnant, 0, 0, _this.pos); + _this.md5.update(remnant); + var doc = createChunkDoc(_this.id, _this.n, remnant); + + _this.chunks.insert(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + checkDone(_this); + }); +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js new file mode 100644 index 0000000..cbd3ee8 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js @@ -0,0 +1,233 @@ +"use strict"; + +var Binary = require('mongodb-core').BSON.Binary, + ObjectID = require('mongodb-core').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 = 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, 0, mongoObjectFinal.data.length, 'binary'); + this.data = new Binary(buffer); + } else if(Array.isArray(mongoObjectFinal.data)) { + var buffer = new Buffer(mongoObjectFinal.data.length); + var data = mongoObjectFinal.data.join(''); + buffer.write(data, 0, data.length, 'binary'); + this.data = new Binary(buffer); + } else if(mongoObjectFinal.data._bsontype === '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, data.length, 'binary'); + 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 = { upsert: true }; + for(var name in options) writeOptions[name] = options[name]; + for(var name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + 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.replaceOne({'_id':self.objectId}, 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; + +module.exports = Chunk; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js new file mode 100644 index 0000000..93afa50 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js @@ -0,0 +1,1956 @@ +"use strict"; + +/** + * @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. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * GridStore = require('mongodb').GridStore, + * ObjectID = require('mongodb').ObjectID, + * test = require('assert'); + * + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * var gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * db.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +var Chunk = require('./chunk'), + ObjectID = require('mongodb-core').BSON.ObjectID, + ReadPreference = require('../read_preference'), + Buffer = require('buffer').Buffer, + Collection = require('../collection'), + fs = require('fs'), + timers = require('timers'), + f = require('util').format, + util = require('util'), + Define = require('../metadata'), + MongoError = require('mongodb-core').MongoError, + inherits = util.inherits, + Duplex = require('stream').Duplex || require('readable-stream').Duplex, + shallowClone = require('../utils').shallowClone; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +/** + * Namespace provided by the mongodb-core and node.js + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwriten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [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=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata=null] Arbitrary data the user wants to store. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + * @deprecated Use GridFSBucket API instead + */ +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; + + // 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 || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = this.options.readPreference || db.options.readPreference || 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']; + + // Get the promiseLibrary + var promiseLibrary = this.options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set the promiseLibrary + this.promiseLibrary = promiseLibrary; + + Object.defineProperty(this, "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; + } + } + }); + + Object.defineProperty(this, "md5", { enumerable: true + , get: function () { + return this.internalMd5; + } + }); + + Object.defineProperty(this, "chunkNumber", { enumerable: true + , get: function () { + return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null; + } + }); +} + +var define = GridStore.define = new Define('Gridstore', GridStore, true); + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {GridStore~openCallback} [callback] this will be called after executing this method + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.open = function(callback) { + var self = this; + if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ + throw MongoError.create({message: "Illegal mode " + this.mode, driver:true}); + } + + // We provided a callback leg + if(typeof callback == 'function') return open(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + open(self, function(err, store) { + if(err) return reject(err); + resolve(store); + }) + }); +}; + +var open = function(self, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(self.db, self.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) { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Make an unique index for compatibility with mongo-cxx-driver:legacy + var chunkIndexOptions = shallowClone(writeConcern); + chunkIndexOptions.unique = true; + // Ensure index on chunk collection + chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function(err, index) { + // Open the connection + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + }); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +} + +// Push the definition for open +define.classMethod('open', {callback: true, promise:true}); + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.eof = function() { + return this.position == this.length ? true : false; +} + +define.classMethod('eof', {callback: false, promise:false, returns: [Boolean]}); + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.getc = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return eof(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + eof(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var eof = function(self, callback) { + 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()); + } +} + +define.classMethod('getc', {callback: true, promise:true}); + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.puts = function(string, callback) { + var self = this; + var finalString = string.match(/\n$/) == null ? string + "\n" : string; + // We provided a callback leg + if(typeof callback == 'function') return this.write(finalString, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + self.write(finalString, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +define.classMethod('puts', {callback: true, promise:true}); + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +} + +define.classMethod('stream', {callback: false, promise:false, returns: [GridStoreStream]}); + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.write = function write(data, close, callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return _writeNormal(this, data, close, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + _writeNormal(self, data, close, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +define.classMethod('write', {callback: true, promise:true}); + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + * @deprecated Use GridFSBucket API instead + */ +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'); + } +} + +define.classMethod('destroy', {callback: false, promise:false}); + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.writeFile = function (file, callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return writeFile(self, file, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + writeFile(self, file, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var writeFile = function(self, file, callback) { + 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 process.nextTick(writeChunk); + } + }); + }); + }); + } + + // Process the first write + process.nextTick(writeChunk); + }); + }); +} + +define.classMethod('writeFile', {callback: true, promise:true}); + +/** + * 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+". + * + * @method + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.close = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return close(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + close(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var close = function(self, callback) { + 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) { + 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(MongoError.create({message: f("Illegal mode %s", self.mode), driver:true})); + } +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.chunkCollection = function(callback) { + if(typeof callback == 'function') + return this.db.collection((this.root + ".chunks"), callback); + return this.db.collection((this.root + ".chunks")); +}; + +define.classMethod('chunkCollection', {callback: true, promise:false, returns: [Collection]}); + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.unlink = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return unlink(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + unlink(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var unlink = function(self, callback) { + deleteChunks(self, 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); + }); + }); + }); +} + +define.classMethod('unlink', {callback: true, promise:true}); + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.collection = function(callback) { + if(typeof callback == 'function') + this.db.collection(this.root + ".files", callback); + return this.db.collection(this.root + ".files"); +}; + +define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.readlines = function(separator, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + separator = args.length ? args.shift() : "\n"; + separator = separator || "\n"; + + // We provided a callback leg + if(typeof callback == 'function') return readlines(self, separator, callback); + + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + readlines(self, separator, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readlines = function(self, separator, callback) { + self.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); + }); +} + +define.classMethod('readlines', {callback: true, promise:true}); + +/** + * 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. + * + * @method + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.rewind = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return rewind(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + rewind(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var rewind = function(self, callback) { + if(self.currentChunk.chunkNumber != 0) { + if(self.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); + } +} + +define.classMethod('rewind', {callback: true, promise:true}); + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * 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) + * + * @method + * @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 {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.read = function(length, buffer, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + // We provided a callback leg + if(typeof callback == 'function') return read(self, length, buffer, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + read(self, length, buffer, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var read = function(self, length, buffer, callback) { + // 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(MongoError.create({message: "File does not exist", driver:true}), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + 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(MongoError.create({message: "no chunks found for file, possibly corrupt", driver:true}), null); + } + } + }); +} + +define.classMethod('read', {callback: true, promise:true}); + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @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 {GridStore~tellCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.tell = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return callback(null, this.position); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + resolve(self.position); + }); +}; + +define.classMethod('tell', {callback: true, promise:true}); + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * 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. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {GridStore~gridStoreCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.seek = function(position, seekLocation, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + seekLocation = args.length ? args.shift() : null; + + // We provided a callback leg + if(typeof callback == 'function') return seek(self, position, seekLocation, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + seek(self, position, seekLocation, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var seek = function(self, position, seekLocation, callback) { + // Seek only supports read mode + if(self.mode != 'r') { + return callback(MongoError.create({message: "seek is only supported for mode r", driver:true})) + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if(seekLocationFinal == GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if(seekLocationFinal == GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition/self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + if(err) return callback(err, null); + if(chunk == null) return callback(new Error('no chunk found')); + + // Set the current chunk + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = (self.position % self.chunkSize); + callback(err, self); + }); + }; + + seekChunk(); +} + +define.classMethod('seek', {callback: true, promise:true}); + +/** + * @ignore + */ +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 = 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(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename)), driver:true}), 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" && doc) { + // 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") { + 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 = 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); + } +}; + +/** + * @ignore + */ +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 != "w") { + callback(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? self.referenceBy : self.filename)), driver:true}), 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. + * + *

+ *        {
+ *          '_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 + */ +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); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +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 + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +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); + } +}; + +/** +* 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. + * + * @method + * @static + * @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 {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return exists(db, fileIdObject, rootCollection, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + exists(db, fileIdObject, rootCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var exists = function(db, fileIdObject, rootCollection, options, callback) { + // Establish read preference + var readPreference = options.readPreference || 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 + + // We have a specific query + if(fileIdObject != null + && typeof fileIdObject == 'object' + && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, {readPreference:readPreference}, function(err, item) { + if(err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +} + +define.staticMethod('exist', {callback: true, promise:true}); + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @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 {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return list(db, rootCollection, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + list(db, rootCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var list = function(db, rootCollection, options, callback) { + // Ensure we have correct values + if(rootCollection != null && typeof rootCollection == 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || 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); + } + }); + }); + }); +} + +define.staticMethod('list', {callback: true, promise:true}); + +/** + * 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) + * + * @method + * @static + * @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=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options ? options.promiseLibrary : null; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return readStatic(db, name, length, offset, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + readStatic(db, name, length, offset, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readStatic = function(db, name, length, offset, options, callback) { + 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); + } + }); +} + +define.staticMethod('read', {callback: true, promise:true}); + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options ? options.promiseLibrary : null; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return readlinesStatic(db, name, separator, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + readlinesStatic(db, name, separator, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readlinesStatic = function(db, name, separator, options, callback) { + 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); + }); +} + +define.staticMethod('readlines', {callback: true, promise:true}); + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options=null] Optional settings. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.unlink = function(db, names, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return unlinkStatic(self, db, names, options, callback); + + // Return promise + return new promiseLibrary(function(resolve, reject) { + unlinkStatic(self, db, names, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var unlinkStatic = function(self, db, names, options, callback) { + // 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); + }); + }); + }); + }); + } +} + +define.staticMethod('unlink', {callback: true, promise:true}); + +/** + * @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); + } +} + +/** + * @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 && (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 MongoError.create({message: "No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true", driver:true}); + + // Return the options + return finalOptions; +} + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStoreStream = function(gs) { + var self = this; + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +} + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if(!self.gs.isOpen) { + self.gs.open(function(err) { + if(err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } + + return destination; +} + +// Called by stream +GridStoreStream.prototype._read = function(n) { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if(err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if(self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if(buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if(buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if(self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + } + + // Set read length + var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if(!self.gs.isOpen) { + self.gs.open(function(err, gs) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if(err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +} + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +} + +GridStoreStream.prototype.write = function(chunk, encoding, callback) { + var self = this; + if(self.endCalled) return self.emit('error', MongoError.create({message: 'attempting to write to stream after end called', driver:true})) + // Do we have to open the gridstore + if(!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +} + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if(chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); + }); + } + + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); +} + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/metadata.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/metadata.js new file mode 100644 index 0000000..7dae562 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/metadata.js @@ -0,0 +1,64 @@ +var f = require('util').format; + +var Define = function(name, object, stream) { + this.name = name; + this.object = object; + this.stream = typeof stream == 'boolean' ? stream : false; + this.instrumentations = {}; +} + +Define.prototype.classMethod = function(name, options) { + var keys = Object.keys(options).sort(); + var key = generateKey(keys, options); + + // Add a list of instrumentations + if(this.instrumentations[key] == null) { + this.instrumentations[key] = { + methods: [], options: options + } + } + + // Push to list of method for this instrumentation + this.instrumentations[key].methods.push(name); +} + +var generateKey = function(keys, options) { + var parts = []; + for(var i = 0; i < keys.length; i++) { + parts.push(f('%s=%s', keys[i], options[keys[i]])); + } + + return parts.join(); +} + +Define.prototype.staticMethod = function(name, options) { + options.static = true; + var keys = Object.keys(options).sort(); + var key = generateKey(keys, options); + + // Add a list of instrumentations + if(this.instrumentations[key] == null) { + this.instrumentations[key] = { + methods: [], options: options + } + } + + // Push to list of method for this instrumentation + this.instrumentations[key].methods.push(name); +} + +Define.prototype.generate = function(keys, options) { + // Generate the return object + var object = { + name: this.name, obj: this.object, stream: this.stream, + instrumentations: [] + } + + for(var name in this.instrumentations) { + object.instrumentations.push(this.instrumentations[name]); + } + + return object; +} + +module.exports = Define; \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 0000000..aac1342 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,472 @@ +"use strict"; + +var parse = require('./url_parser') + , Server = require('./server') + , Mongos = require('./mongos') + , ReplSet = require('./replset') + , Define = require('./metadata') + , ReadPreference = require('./read_preference') + , Db = require('./db'); + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new MongoClient instance + * @class + * @return {MongoClient} a MongoClient instance. + */ +function MongoClient() { + /** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The connected database. + */ + + /** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ + this.connect = MongoClient.connect; +} + +var define = MongoClient.define = new Define('MongoClient', MongoClient, false); + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +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 || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Return a promise + if(typeof callback != 'function') { + return new promiseLibrary(function(resolve, reject) { + connect(url, options, function(err, db) { + if(err) return reject(err); + resolve(db); + }); + }); + } + + // Fallback to callback based connect + connect(url, options, callback); +} + +define.staticMethod('connect', {callback: true, promise:true}); + +var connect = function(url, options, callback) { + 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]; + } + + if(replSetServersOptions.ssl + || replSetServersOptions.sslValidate + || replSetServersOptions.checkServerIdentity + || replSetServersOptions.sslCA + || replSetServersOptions.sslCert + || replSetServersOptions.sslKey + || replSetServersOptions.sslPass) { + object.server_options.ssl = replSetServersOptions.ssl; + object.server_options.sslValidate = replSetServersOptions.sslValidate; + object.server_options.checkServerIdentity = replSetServersOptions.checkServerIdentity; + object.server_options.sslCA = replSetServersOptions.sslCA; + object.server_options.sslCert = replSetServersOptions.sslCert; + object.server_options.sslKey = replSetServersOptions.sslKey; + object.server_options.sslPass = replSetServersOptions.sslPass; + } + + // Merge in any replicaset server options + if(mongosOptions) { + for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; + } + + if(typeof object.server_options.poolSize == 'number') { + if(!object.mongos_options.poolSize) object.mongos_options.poolSize = object.server_options.poolSize; + if(!object.rs_options.poolSize) object.rs_options.poolSize = object.server_options.poolSize; + } + + if(mongosOptions.ssl + || mongosOptions.sslValidate + || mongosOptions.checkServerIdentity + || mongosOptions.sslCA + || mongosOptions.sslCert + || mongosOptions.sslKey + || mongosOptions.sslPass) { + object.server_options.ssl = mongosOptions.ssl; + object.server_options.sslValidate = mongosOptions.sslValidate; + object.server_options.checkServerIdentity = mongosOptions.checkServerIdentity; + object.server_options.sslCA = mongosOptions.sslCA; + object.server_options.sslCert = mongosOptions.sslCert; + object.server_options.sslKey = mongosOptions.sslKey; + object.server_options.sslPass = mongosOptions.sslPass; + } + + // Set the promise library + object.db_options.promiseLibrary = options.promiseLibrary; + + // 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; + } + + // 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 providedSocketOptions = object.server_options.socketOptions || {}; + + var _server_options = { + poolSize:1 + , socketOptions: { + connectTimeoutMS: providedSocketOptions.connectTimeoutMS || (1000 * 120) + , socketTimeoutMS: providedSocketOptions.socketTimeoutMS || (1000 * 120) + } + , auto_reconnect:false}; + + // Ensure we have ssl setup for the servers + if(object.server_options.ssl) { + _server_options.ssl = object.server_options.ssl; + _server_options.sslValidate = object.server_options.sslValidate; + _server_options.checkServerIdentity = object.server_options.checkServerIdentity; + _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; + } else if(object.rs_options.ssl) { + _server_options.ssl = object.rs_options.ssl; + _server_options.sslValidate = object.rs_options.sslValidate; + _server_options.checkServerIdentity = object.rs_options.checkServerIdentity; + _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; + } + + // Error + var error = null; + // 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, promiseLibrary:options.promiseLibrary}).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(); + // Get the last ismaster document + var isMasterDoc = db.serverConfig.isMasterDoc; + + // Check what type of server we have + if(isMasterDoc.setName) { + totalNumberOfMongodServers++; + } + + if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; + } else { + error = err; + errorServers[__server.host + ":" + __server.port] = __server; + } + + if(totalNumberOfServers == 0) { + // Error out + if(totalNumberOfMongodServers == 0 && totalNumberOfMongosServers == 0 && error) { + return callback(error, null); + } + + // If we have a mix of mongod and mongos, throw an error + if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { + if(db) db.close(); + return process.nextTick(function() { + try { + callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); + } catch (err) { + throw err + } + }) + } + + if(totalNumberOfMongodServers == 0 + && totalNumberOfMongosServers == 0 + && object.servers.length == 1 + && (!object.rs_options.replicaSet || !object.rs_options.rs_name)) { + + 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 + || object.rs_options.replicaSet || object.rs_options.rs_name) { + + var finalServers = object.servers + .filter(function(serverObj) { + return errorServers[serverObj.host + ":" + serverObj.port] == null; + }) + .map(function(serverObj) { + return serverObj.domain_socket ? + new Server(serverObj.domain_socket, 27017, object.server_options) + : new Server(serverObj.host, serverObj.port, object.server_options); + }); + + // Clean out any error servers + errorServers = {}; + + // Set up the final configuration + if(totalNumberOfMongodServers > 0) { + try { + + // If no replicaset name was provided, we wish to perform a + // direct connection + if(totalNumberOfMongodServers == 1 + && (!object.rs_options.replicaSet && !object.rs_options.rs_name)) { + serverConfig = finalServers[0]; + } else if(totalNumberOfMongodServers == 1) { + object.rs_options.replicaSet = object.rs_options.replicaSet || object.rs_options.rs_name; + serverConfig = new ReplSet(finalServers, object.rs_options); + } else { + serverConfig = new ReplSet(finalServers, object.rs_options); + } + + } catch(err) { + return callback(err, null); + } + } 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 of 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('mongodb-core').BSON.BSONNative.BSON; + return true; + } catch(err) { + return false; + } +} + +var _finishConnecting = function(serverConfig, object, options, callback) { + // If we have a readPreference passed in by the db options + if(typeof object.db_options.readPreference == 'string') { + object.db_options.readPreference = new ReadPreference(object.db_options.readPreference); + } else if(typeof object.db_options.read_preference == 'string') { + object.db_options.readPreference = new ReadPreference(object.db_options.read_preference); + } + + // Do we have readPreference tags + if(object.db_options.readPreference && object.db_options.readPreferenceTags) { + object.db_options.readPreference.tags = object.db_options.readPreferenceTags; + } else if(object.db_options.readPreference && object.db_options.read_preference_tags) { + object.db_options.readPreference.tags = object.db_options.read_preference_tags; + } + + // Get the socketTimeoutMS + var socketTimeoutMS = object.server_options.socketOptions.socketTimeoutMS || 0; + + // 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 the same as the connectTimeoutMS or 30 sec + serverConfig.connectTimeoutMS = serverConfig.connectTimeoutMS || 30000; + serverConfig.socketTimeoutMS = serverConfig.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 + } + }); + } + + // Reset the socket timeout + serverConfig.socketTimeoutMS = socketTimeoutMS || 0; + + // Return object + 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){ + 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 { + process.nextTick(function() { + try { + callback(err, db); + } catch (err) { + if(db) db.close(); + throw err + } + }) + } + }); +} + +module.exports = MongoClient diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/mongos.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/mongos.js new file mode 100644 index 0000000..c3b7c96 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/mongos.js @@ -0,0 +1,499 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , MongoCR = require('mongodb-core').MongoCR + , MongoError = require('mongodb-core').MongoError + , CMongos = require('mongodb-core').Mongos + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , Define = require('./metadata') + , Server = require('./server') + , Store = require('./topology_base').Store + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Mongos = require('mongodb').Mongos, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using Mongos + * var server = new Server('localhost', 27017); + * var db = new Db('test', new Mongos([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=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) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @return {Mongos} a Mongos instance. + */ +var Mongos = function(servers, options) { + if(!(this instanceof Mongos)) return new Mongos(servers, options); + options = options || {}; + var self = this; + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); + } + } + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Debug tag + var tag = options.tag; + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Final options + var finalOptions = shallowClone(options); + + // Default values + finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; + finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + finalOptions.cursorFactory = Cursor; + + // Add the store + finalOptions.disconnectHandler = store; + + // Ensure we change the sslCA option to ca if available + if(options.sslCA) finalOptions.ca = options.sslCA; + if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; + if(options.sslKey) finalOptions.key = options.sslKey; + if(options.sslCert) finalOptions.cert = options.sslCert; + if(options.sslPass) finalOptions.passphrase = options.sslPass; + if(options.checkServerIdentity) finalOptions.checkServerIdentity = options.checkServerIdentity; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + if(options.socketOptions.socketTimeoutMS) + finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + + // Are we running in debug mode + var debug = typeof options.debug == 'boolean' ? options.debug : false; + if(debug) { + finalOptions.debug = debug; + } + + // Map keep alive setting + if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAlive = true; + if(typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + } + } + + // Connection timeout + if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { + finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; + } + + // Socket timeout + if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { + finalOptions.socketTimeout = options.socketOptions.socketTimeout; + } + + // noDelay + if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { + finalOptions.noDelay = options.socketOptions.noDelay; + } + + if(typeof options.secondaryAcceptableLatencyMS == 'number') { + finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; + } + + // Add the non connection store + finalOptions.disconnectHandler = store; + + // Create the Mongos + var mongos = new CMongos(seedlist, finalOptions) + // Server capabilities + var sCapabilities = null; + // Add auth prbufferMaxEntriesoviders + mongos.addAuthProvider('mongocr', new MongoCR()); + + // Internal state + this.s = { + // Create the Mongos + mongos: mongos + // Server capabilities + , sCapabilities: sCapabilities + // Debug turned on + , debug: debug + // Store option defaults + , storeOptions: storeOptions + // Cloned options + , clonedOptions: finalOptions + // Actual store of callbacks + , store: store + // Options + , options: options + } + + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { return self.s.mongos.lastIsMaster(); } + }); + + // Last ismaster + Object.defineProperty(this, 'numberOfConnectedServers', { + enumerable:true, get: function() { + return self.s.mongos.s.mongosState.connectedServers().length; + } + }); + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return self.s.mongos.bson; + } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.mongos.haInterval; } + }); +} + +/** + * @ignore + */ +inherits(Mongos, EventEmitter); + +var define = Mongos.define = new Define('Mongos', Mongos, false); + +// Connect +Mongos.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.mongos.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function(err) { + self.emit('reconnect'); + self.s.store.execute(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.mongos.removeAllListeners(e); + }); + + // Set up listeners + self.s.mongos.once('timeout', errorHandler('timeout')); + self.s.mongos.once('error', errorHandler('error')); + self.s.mongos.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Set up serverConfig listeners + self.s.mongos.on('joined', relay('joined')); + self.s.mongos.on('left', relay('left')); + self.s.mongos.on('fullsetup', relay('fullsetup')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + self.s.mongos.once('timeout', connectErrorHandler('timeout')); + self.s.mongos.once('error', connectErrorHandler('error')); + self.s.mongos.once('close', connectErrorHandler('close')); + self.s.mongos.once('connect', connectHandler); + // Reconnect server + self.s.mongos.on('reconnect', reconnectHandler); + + // Start connection + self.s.mongos.connect(_options); +} + +Mongos.prototype.parserType = function() { + return this.s.mongos.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Server capabilities +Mongos.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.mongos.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.mongos.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +Mongos.prototype.command = function(ns, cmd, options, callback) { + this.s.mongos.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +Mongos.prototype.insert = function(ns, ops, options, callback) { + this.s.mongos.insert(ns, ops, options, function(e, m) { + callback(e, m) + }); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +Mongos.prototype.update = function(ns, ops, options, callback) { + this.s.mongos.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +Mongos.prototype.remove = function(ns, ops, options, callback) { + this.s.mongos.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// Destroyed +Mongos.prototype.isDestroyed = function() { + return this.s.mongos.isDestroyed(); +} + +// IsConnected +Mongos.prototype.isConnected = function() { + return this.s.mongos.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +Mongos.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.mongos.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +Mongos.prototype.setBSONParserType = function(type) { + return this.s.mongos.setBSONParserType(type); +} + +Mongos.prototype.lastIsMaster = function() { + return this.s.mongos.lastIsMaster(); +} + +Mongos.prototype.close = function(forceClosed) { + this.s.mongos.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +define.classMethod('close', {callback: false, promise:false}); + +Mongos.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.mongos.auth.apply(this.s.mongos, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +Mongos.prototype.connections = function() { + return this.s.mongos.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +module.exports = Mongos; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/read_preference.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/read_preference.js new file mode 100644 index 0000000..73b253a --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/read_preference.js @@ -0,0 +1,104 @@ +"use strict"; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * ReadPreference = require('mongodb').ReadPreference, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * test.equal(null, err); + * // Perform a read + * var cursor = db.collection('t').find({}); + * cursor.setReadPreference(ReadPreference.PRIMARY); + * cursor.toArray(function(err, docs) { + * test.equal(null, err); + * db.close(); + * }); + * }); + */ + +/** + * Creates a new ReadPreference instance + * + * 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 + * @param {string} mode The ReadPreference mode as listed above. + * @param {object} tags An object representing read preference tags. + * @property {string} mode The ReadPreference mode. + * @property {object} tags The ReadPreference tags. + * @return {ReadPreference} a ReadPreference instance. + */ +var ReadPreference = function(mode, tags) { + if(!(this instanceof ReadPreference)) + return new ReadPreference(mode, tags); + this._type = 'ReadPreference'; + this.mode = mode; + this.tags = tags; +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +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); +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +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 + */ +module.exports = ReadPreference; \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/replset.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/replset.js new file mode 100644 index 0000000..bc04047 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/replset.js @@ -0,0 +1,560 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , Server = require('./server') + , Mongos = require('./mongos') + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , ReadPreference = require('./read_preference') + , MongoCR = require('mongodb-core').MongoCR + , MongoError = require('mongodb-core').MongoError + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , Define = require('./metadata') + , CServer = require('mongodb-core').Server + , CReplSet = require('mongodb-core').ReplSet + , CoreReadPreference = require('mongodb-core').ReadPreference + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {string} options.replicaSet The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=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) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=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) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @return {ReplSet} a ReplSet instance. + */ +var ReplSet = function(servers, options) { + if(!(this instanceof ReplSet)) return new ReplSet(servers, options); + options = options || {}; + var self = this; + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); + } + } + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Debug tag + var tag = options.tag; + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Final options + var finalOptions = shallowClone(options); + + // Default values + finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; + finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + finalOptions.cursorFactory = Cursor; + + // Add the store + finalOptions.disconnectHandler = store; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + + if(options.socketOptions.socketTimeoutMS) { + finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + } + + // Get the name + var replicaSet = options.replicaSet || options.rs_name; + + // Set up options + finalOptions.setName = replicaSet; + + // Are we running in debug mode + var debug = typeof options.debug == 'boolean' ? options.debug : false; + if(debug) { + finalOptions.debug = debug; + } + + // Map keep alive setting + if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAlive = true; + if(typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + } + } + + // Connection timeout + if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { + finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; + } + + // Socket timeout + if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { + finalOptions.socketTimeout = options.socketOptions.socketTimeout; + } + + // noDelay + if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { + finalOptions.noDelay = options.socketOptions.noDelay; + } + + if(typeof options.secondaryAcceptableLatencyMS == 'number') { + finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; + } + + if(options.connectWithNoPrimary == true) { + finalOptions.secondaryOnlyConnectionAllowed = true; + } + + // Add the non connection store + finalOptions.disconnectHandler = store; + + // Translate the options + if(options.sslCA) finalOptions.ca = options.sslCA; + if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; + if(options.sslKey) finalOptions.key = options.sslKey; + if(options.sslCert) finalOptions.cert = options.sslCert; + if(options.sslPass) finalOptions.passphrase = options.sslPass; + if(options.checkServerIdentity) finalOptions.checkServerIdentity = options.checkServerIdentity; + + // Create the ReplSet + var replset = new CReplSet(seedlist, finalOptions) + // Server capabilities + var sCapabilities = null; + + // Listen to reconnect event + replset.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + replset: replset + // Server capabilities + , sCapabilities: null + // Debug tag + , tag: options.tag + // Store options + , storeOptions: storeOptions + // Cloned options + , clonedOptions: finalOptions + // Store + , store: store + // Options + , options: options + } + + // Debug + if(debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable:true, get: function() { return replset; } + }); + } + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { return replset.lastIsMaster(); } + }); + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return replset.bson; + } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return replset.haInterval; } + }); +} + +/** + * @ignore + */ +inherits(ReplSet, EventEmitter); + +var define = ReplSet.define = new Define('ReplSet', ReplSet, false); + +// Ensure the right read Preference object +var translateReadPreference = function(options) { + if(typeof options.readPreference == 'string') { + options.readPreference = new CoreReadPreference(options.readPreference); + } else if(options.readPreference instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(options.readPreference.mode + , options.readPreference.tags); + } + + return options; +} + +ReplSet.prototype.parserType = function() { + return this.s.replset.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Connect method +ReplSet.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.replset.removeAllListeners(e); + }); + + // Set up listeners + self.s.replset.once('timeout', errorHandler('timeout')); + self.s.replset.once('error', errorHandler('error')); + self.s.replset.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + } + } + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if(t == 'start') { + self.emit('ha_connect', t, state); + } else if(t == 'end') { + self.emit('ha_ismaster', t, state); + } + } + + // Set up serverConfig listeners + self.s.replset.on('joined', replsetRelay('joined')); + self.s.replset.on('left', relay('left')); + self.s.replset.on('ping', relay('ping')); + self.s.replset.on('ha', relayHa); + + self.s.replset.on('fullsetup', function(topology) { + self.emit('fullsetup', null, self); + }); + + self.s.replset.on('all', function(topology) { + self.emit('all', null, self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.replset.removeListener(e, connectErrorHandler); + }); + + self.s.replset.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.replset.destroy(); + + // Try to callback + try { + callback(err); + } catch(err) { + if(!self.s.replset.isConnected()) + process.nextTick(function() { throw err; }) + } + } + } + + // Set up listeners + self.s.replset.once('timeout', connectErrorHandler('timeout')); + self.s.replset.once('error', connectErrorHandler('error')); + self.s.replset.once('close', connectErrorHandler('close')); + self.s.replset.once('connect', connectHandler); + + // Start connection + self.s.replset.connect(_options); +} + +// Server capabilities +ReplSet.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.replset.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.replset.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +ReplSet.prototype.command = function(ns, cmd, options, callback) { + options = translateReadPreference(options); + this.s.replset.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +ReplSet.prototype.insert = function(ns, ops, options, callback) { + this.s.replset.insert(ns, ops, options, callback); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +ReplSet.prototype.update = function(ns, ops, options, callback) { + this.s.replset.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +ReplSet.prototype.remove = function(ns, ops, options, callback) { + this.s.replset.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// Destroyed +ReplSet.prototype.isDestroyed = function() { + return this.s.replset.isDestroyed(); +} + +// IsConnected +ReplSet.prototype.isConnected = function() { + return this.s.replset.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +ReplSet.prototype.setBSONParserType = function(type) { + return this.s.replset.setBSONParserType(type); +} + +// Insert +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = translateReadPreference(options); + options.disconnectHandler = this.s.store; + return this.s.replset.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +ReplSet.prototype.lastIsMaster = function() { + return this.s.replset.lastIsMaster(); +} + +ReplSet.prototype.close = function(forceClosed) { + var self = this; + this.s.replset.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); +} + +define.classMethod('close', {callback: false, promise:false}); + +ReplSet.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.replset.auth.apply(this.s.replset, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +ReplSet.prototype.connections = function() { + return this.s.replset.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +module.exports = ReplSet; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/server.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/server.js new file mode 100644 index 0000000..76a708d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/server.js @@ -0,0 +1,442 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , CServer = require('mongodb-core').Server + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , Define = require('./metadata') + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using single Server + * var db = new Db('test', new Server('localhost', 27017);); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options=null] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=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) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=false] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @return {Server} a Server instance. + */ +var Server = function(host, port, options) { + options = options || {}; + if(!(this instanceof Server)) return new Server(host, port, options); + EventEmitter.call(this); + var self = this; + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if(host.indexOf('\/') != -1) { + if(port != null && typeof port == 'object') { + options = port; + port = null; + } + } else if(port == null) { + throw MongoError.create({message: 'port must be specified', driver:true}); + } + + // Clone options + var clonedOptions = shallowClone(options); + clonedOptions.host = host; + clonedOptions.port = port; + + // Reconnect + var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; + var emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + var poolSize = typeof options.poolSize == 'number' ? options.poolSize : 5; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + clonedOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + + if(options.socketOptions.socketTimeoutMS) { + clonedOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + + if(typeof options.socketOptions.keepAlive == 'number') { + clonedOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + clonedOptions.keepAlive = true; + } + + if(typeof options.socketOptions.noDelay == 'boolean') { + clonedOptions.noDelay = options.socketOptions.noDelay; + } + } + + // Add the cursor factory function + clonedOptions.cursorFactory = Cursor; + clonedOptions.reconnect = reconnect; + clonedOptions.emitError = emitError; + clonedOptions.size = poolSize; + + // Translate the options + if(clonedOptions.sslCA) clonedOptions.ca = clonedOptions.sslCA; + if(typeof clonedOptions.sslValidate == 'boolean') clonedOptions.rejectUnauthorized = clonedOptions.sslValidate; + if(clonedOptions.sslKey) clonedOptions.key = clonedOptions.sslKey; + if(clonedOptions.sslCert) clonedOptions.cert = clonedOptions.sslCert; + if(clonedOptions.sslPass) clonedOptions.passphrase = clonedOptions.sslPass; + + // Add the non connection store + clonedOptions.disconnectHandler = store; + + // Create an instance of a server instance from mongodb-core + var server = new CServer(clonedOptions); + // Server capabilities + var sCapabilities = null; + + // Define the internal properties + this.s = { + // Create an instance of a server instance from mongodb-core + server: server + // Server capabilities + , sCapabilities: null + // Cloned options + , clonedOptions: clonedOptions + // Reconnect + , reconnect: reconnect + // Emit error + , emitError: emitError + // Pool size + , poolSize: poolSize + // Store Options + , storeOptions: storeOptions + // Store + , store: store + // Host + , host: host + // Port + , port: port + // Options + , options: options + } + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return self.s.server.bson; + } + }); + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { + return self.s.server.lastIsMaster(); + } + }); + + // Last ismaster + Object.defineProperty(this, 'poolSize', { + enumerable:true, get: function() { return self.s.server.connections().length; } + }); + + Object.defineProperty(this, 'autoReconnect', { + enumerable:true, get: function() { return self.s.reconnect; } + }); + + Object.defineProperty(this, 'host', { + enumerable:true, get: function() { return self.s.host; } + }); + + Object.defineProperty(this, 'port', { + enumerable:true, get: function() { return self.s.port; } + }); +} + +inherits(Server, EventEmitter); + +var define = Server.define = new Define('Server', Server, false); + +Server.prototype.parserType = function() { + return this.s.server.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Connect +Server.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.server.removeListener(e, connectHandlers[e]); + }); + + self.s.server.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function(err) { + self.emit('reconnect', self); + self.s.store.execute(); + } + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.server.removeAllListeners(e); + }); + + // Set up listeners + self.s.server.once('timeout', errorHandler('timeout')); + self.s.server.once('error', errorHandler('error')); + self.s.server.on('close', errorHandler('close')); + // Only called on destroy + self.s.server.once('destroy', destroyHandler); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + console.log(err.stack) + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Add the event handlers + self.s.server.once('timeout', connectHandlers.timeout); + self.s.server.once('error', connectHandlers.error); + self.s.server.once('close', connectHandlers.close); + self.s.server.once('connect', connectHandler); + // Reconnect server + self.s.server.on('reconnect', reconnectHandler); + + // Start connection + self.s.server.connect(_options); +} + +// Server capabilities +Server.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.server.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +Server.prototype.command = function(ns, cmd, options, callback) { + this.s.server.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +Server.prototype.insert = function(ns, ops, options, callback) { + this.s.server.insert(ns, ops, options, callback); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +Server.prototype.update = function(ns, ops, options, callback) { + this.s.server.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +Server.prototype.remove = function(ns, ops, options, callback) { + this.s.server.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// IsConnected +Server.prototype.isConnected = function() { + return this.s.server.isConnected(); +} + +Server.prototype.isDestroyed = function() { + return this.s.server.isDestroyed(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +Server.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.server.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +Server.prototype.setBSONParserType = function(type) { + return this.s.server.setBSONParserType(type); +} + +Server.prototype.lastIsMaster = function() { + return this.s.server.lastIsMaster(); +} + +Server.prototype.close = function(forceClosed) { + this.s.server.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +define.classMethod('close', {callback: false, promise:false}); + +Server.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.server.auth.apply(this.s.server, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +Server.prototype.connections = function() { + return this.s.server.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +module.exports = Server; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/topology_base.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/topology_base.js new file mode 100644 index 0000000..000f7ec --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/topology_base.js @@ -0,0 +1,152 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError + , f = require('util').format; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || {force:false, bufferMaxEntries: -1} + + // Internal state + this.s = { + storedOps: storedOps + , storeOptions: storeOptions + , topology: topology + } + + Object.defineProperty(this, 'length', { + enumerable:true, get: function() { return self.s.storedOps.length; } + }); +} + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if(this.s.storeOptions.force) { + return callback(MongoError.create({message: "db closed by application", driver:true})); + } + + if(this.s.storeOptions.bufferMaxEntries == 0) { + return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + return; + } + + this.s.storedOps.push({t: opType, n: ns, o: ops, op: options, c: callback}) +} + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if(this.s.storeOptions.force) { + return callback(MongoError.create({message: "db closed by application", driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries == 0) { + return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + return; + } + + this.s.storedOps.push({t: opType, m: method, o: object, p: params, c: callback}) +} + +Store.prototype.flush = function() { + while(this.s.storedOps.length > 0) { + this.s.storedOps.shift().c(MongoError.create({message: f("no connection available for operation"), driver:true })); + } +} + +Store.prototype.execute = function() { + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Execute all the stored ops + while(ops.length > 0) { + var op = ops.shift(); + + if(op.t == 'cursor') { + op.o[op.m].apply(op.o, op.p); + } else { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } +} + +Store.prototype.all = function() { + return this.s.storedOps; +} + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true + , get: function () { return value; } + }); + } + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + + if(ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if(ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if(ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if(ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + // If no min or max wire version set to 0 + if(ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if(ismaster.maxWireVersion == null) { + ismaster.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", ismaster.minWireVersion); + setup_get_property(this, "maxWireVersion", ismaster.maxWireVersion); + setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); +} + +exports.Store = Store; +exports.ServerCapabilities = ServerCapabilities; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js new file mode 100644 index 0000000..a86bd5f --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js @@ -0,0 +1,393 @@ +"use strict"; + +var ReadPreference = require('./read_preference'), + parser = require('url'), + f = require('util').format; + +module.exports = 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'; + + // Url parser result + var result = parser.parse(url, true); + + if(result.protocol != 'mongodb:') { + throw new Error('invalid schema, expected mongodb'); + } + + if((result.hostname == null || result.hostname == '') && url.indexOf('.sock') == -1) { + throw new Error('no hostname or hostnames provided in connection string'); + } + + if(result.port == '0') { + throw new Error('invalid port (zero) with hostname'); + } + + if(!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { + throw new Error('invalid port (larger than 65535) with hostname'); + } + + if(result.path + && result.path.length > 0 + && result.path[0] != '/' + && url.indexOf('.sock') == -1) { + throw new Error('missing delimiting slash between hosts and options'); + } + + if(result.query) { + for(var name in result.query) { + if(name.indexOf(':') != -1) { + throw new Error('double colon in host identifier'); + } + + if(result.query[name] == '') { + throw new Error('query parameter ' + name + ' is an incomplete value pair'); + } + } + } + + if(result.auth) { + var parts = result.auth.split(':'); + if(url.indexOf(result.auth) != -1 && parts.length > 2) { + throw new Error('Username with password containing an unescaped colon'); + } + + if(url.indexOf(result.auth) != -1 && result.auth.indexOf('@') != -1) { + throw new Error('Username containing an unescaped at-sign'); + } + } + + // Remove query + var clean = url.split('?').shift(); + + // Extract the list of hosts + var strings = clean.split(','); + var hosts = []; + + for(var i = 0; i < strings.length; i++) { + var hostString = strings[i]; + + if(hostString.indexOf('mongodb') != -1) { + if(hostString.indexOf('@') != -1) { + hosts.push(hostString.split('@').pop()) + } else { + hosts.push(hostString.substr('mongodb://'.length)); + } + } else if(hostString.indexOf('/') != -1) { + hosts.push(hostString.split('/').shift()); + } else if(hostString.indexOf('/') == -1) { + hosts.push(hostString.trim()); + } + } + + for(var i = 0; i < hosts.length; i++) { + var r = parser.parse(f('mongodb://%s', hosts[i].trim())); + if(r.path && r.path.indexOf(':') != -1) { + throw new Error('double colon in host identifier'); + } + } + + // 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]; + // Check if multiple database names provided, or just an illegal trailing backslash + if (dbName.indexOf("/") != -1) { + if (dbName.split("/").length == 2 && dbName.split("/")[1].length == 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); + } + } else if(connection_part.indexOf("/") != -1) { + // Check if multiple database names provided, or just an illegal trailing backslash + if (connection_part.split("/").length > 2) { + if (connection_part.split("/")[2].length == 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + 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); + + // Decode the URI components + 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; + // Deduplicate servers + var deduplicatedServers = {}; + + // 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]; + } + + // No entry returned for duplicate servr + if(deduplicatedServers[_host + "_" + _port]) return null; + deduplicatedServers[_host + "_" + _port] = 1; + + // Return the mapped object + return {host: _host, port: _port}; + }).filter(function(x) { + return x != null; + }); + } + + // 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 'sslValidate': + serverOptions.sslValidate = (value == 'true'); + replSetServerOptions.sslValidate = (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.j = (value == 'true'); + break; + case 'safe': + dbOptions.safe = (value == 'true'); + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = (value == 'true'); + break; + case 'readConcernLevel': + dbOptions.readConcern = {level: value}; + 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 != 'MONGODB-CR' + && value != 'DEFAULT' + && value != 'SCRAM-SHA-1' + && value != 'PLAIN') + throw new Error("only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + // Split up into key, value pairs + var values = value.split(','); + var o = {}; + // For each value split into key, value + values.forEach(function(x) { + var v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if(typeof o.SERVICE_NAME == 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + 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.readPreference = 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.readPreference) { + dbOptions.readPreference = 'primary'; + } + + // Add servers to result + object.servers = servers; + // Returned parsed object + return object; +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/utils.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/utils.js new file mode 100644 index 0000000..cb20e67 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/lib/utils.js @@ -0,0 +1,234 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError, + f = require('util').format; + +var shallowClone = function(obj) { + var copy = {}; + for(var name in obj) copy[name] = obj[name]; + return copy; +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +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; +}; + +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"); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if(callback == null) return; + if(value2) return callback(err, value1, value2); + return callback(err, value1); + } catch(err) { + process.nextTick(function() { throw err; }); + return false; + } + + return true; +} + +/** + * 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; + var e = MongoError.create({message: msg, driver:true}); + + // 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; +} + +/** + * @ignore + */ +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; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var 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 + } +} + +var isObject = exports.isObject = function (arg) { + return '[object Object]' == toString.call(arg) +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +var decorateCommand = function(command, options, exclude) { + for(var name in options) { + if(exclude[name] == null) command[name] = options[name]; + } + + return command; +} + +exports.shallowClone = shallowClone; +exports.getSingleProperty = getSingleProperty; +exports.checkCollectionName = checkCollectionName; +exports.toError = toError; +exports.formattedOrderClause = formattedOrderClause; +exports.parseIndexOptions = parseIndexOptions; +exports.normalizeHintField = normalizeHintField; +exports.handleCallback = handleCallback; +exports.decorateCommand = decorateCommand; +exports.isObject = isObject; +exports.debugOptions = debugOptions; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md new file mode 100644 index 0000000..fbe4053 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md @@ -0,0 +1,29 @@ +# Master + +# 3.0.2 + +* correctly bump both bower and package.json versions + +# 3.0.1 + +* no longer include dist/test in npm releases + +# 3.0.0 + +* use nextTick() instead of setImmediate() to schedule microtasks with node 0.10. Later versions of + nodes are not affected as they were already using nextTick(). Note that using nextTick() might + trigger a depreciation warning on 0.10 as described at https://github.com/cujojs/when/issues/410. + The reason why nextTick() is preferred is that is setImmediate() would schedule a macrotask + instead of a microtask and might result in a different scheduling. + If needed you can revert to the former behavior as follow: + + var Promise = require('es6-promise').Promise; + Promise._setScheduler(setImmediate); + +# 2.0.0 + +* re-sync with RSVP. Many large performance improvements and bugfixes. + +# 1.0.0 + +* first subset of RSVP diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/LICENSE new file mode 100644 index 0000000..954ec59 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/README.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/README.md new file mode 100644 index 0000000..d952fa7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/README.md @@ -0,0 +1,61 @@ +# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) + +This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js), if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js). + +For API details and how to use promises, see the JavaScript Promises HTML5Rocks article. + +## Downloads + +* [es6-promise](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise.js) +* [es6-promise-min](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise.min.js) + +## Node.js + +To install: + +```sh +npm install es6-promise +``` + +To use: + +```js +var Promise = require('es6-promise').Promise; +``` + +## Usage in IE<9 + +`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example. + +However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production: + +```js +promise['catch'](function(err) { + // ... +}); +``` + +Or use `.then` instead: + +```js +promise.then(undefined, function(err) { + // ... +}); +``` + +## Auto-polyfill + +To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet: + +```js +require('es6-promise').polyfill(); +``` + +Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called. + +## Building & Testing + +* `npm run build` to build +* `npm test` to run tests +* `npm start` to run a build watcher, and webserver to test +* `npm run test:server` for a testem test runner and watching builder diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js new file mode 100644 index 0000000..88144c9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js @@ -0,0 +1,967 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.0.2 + */ + +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$toString = {}.toString; + var lib$es6$promise$asap$$vertxNext; + var lib$es6$promise$asap$$customSchedulerFn; + + var lib$es6$promise$asap$$asap = function asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (lib$es6$promise$asap$$customSchedulerFn) { + lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); + } else { + lib$es6$promise$asap$$scheduleFlush(); + } + } + } + + function lib$es6$promise$asap$$setScheduler(scheduleFn) { + lib$es6$promise$asap$$customSchedulerFn = scheduleFn; + } + + function lib$es6$promise$asap$$setAsap(asapFn) { + lib$es6$promise$asap$$asap = asapFn; + } + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + process.nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$asap(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + var then = lib$es6$promise$$internal$$getThen(maybeThenable); + + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + } + } else { + lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); + } + } + + lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { + return lib$es6$promise$utils$$isArray(input); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { + this._result = new Array(this.length); + }; + + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (lib$es6$promise$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + enumerator._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, enumerator._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + var lib$es6$promise$promise$$counter = 0; + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + if (!lib$es6$promise$utils$$isFunction(resolver)) { + lib$es6$promise$promise$$needsResolver(); + } + + if (!(this instanceof lib$es6$promise$promise$$Promise)) { + lib$es6$promise$promise$$needsNew(); + } + + lib$es6$promise$$internal$$initializePromise(this, resolver); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; + lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; + lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$asap(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js new file mode 100644 index 0000000..2d48351 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js @@ -0,0 +1,9 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.0.2 + */ + +(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;var lib$es6$promise$asap$$customSchedulerFn;var lib$es6$promise$asap$$asap=function asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){if(lib$es6$promise$asap$$customSchedulerFn){lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush)}else{lib$es6$promise$asap$$scheduleFlush()}}};function lib$es6$promise$asap$$setScheduler(scheduleFn){lib$es6$promise$asap$$customSchedulerFn=scheduleFn}function lib$es6$promise$asap$$setAsap(asapFn){lib$es6$promise$asap$$asap=asapFn}var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){return function(){process.nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ +function Promise(resolver) { + this._id = counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (noop !== resolver) { + if (!isFunction(resolver)) { + needsResolver(); + } + + if (!(this instanceof Promise)) { + needsNew(); + } + + initializePromise(this, resolver); + } +} + +Promise.all = all; +Promise.race = race; +Promise.resolve = Resolve; +Promise.reject = Reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; + +Promise.prototype = { + constructor: Promise, + +/** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} +*/ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + asap(function(){ + invokeCallback(state, child, callback, result); + }); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + +/** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} +*/ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js new file mode 100644 index 0000000..03033f0 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js @@ -0,0 +1,52 @@ +import Enumerator from '../enumerator'; + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = resolve(2); + var promise3 = resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = reject(new Error("2")); + var promise3 = reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +export default function all(entries) { + return new Enumerator(this, entries).promise; +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js new file mode 100644 index 0000000..0d7ff13 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js @@ -0,0 +1,104 @@ +import { + isArray +} from "../utils"; + +import { + noop, + resolve, + reject, + subscribe, + PENDING +} from '../-internal'; + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +export default function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(noop); + + if (!isArray(entries)) { + reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + resolve(promise, value); + } + + function onRejection(reason) { + reject(promise, reason); + } + + for (var i = 0; promise._state === PENDING && i < length; i++) { + subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js new file mode 100644 index 0000000..63b86cb --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js @@ -0,0 +1,46 @@ +import { + noop, + reject as _reject +} from '../-internal'; + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +export default function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js new file mode 100644 index 0000000..201a545 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js @@ -0,0 +1,48 @@ +import { + noop, + resolve as _resolve +} from '../-internal'; + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +export default function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js new file mode 100644 index 0000000..31ec6f9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js @@ -0,0 +1,22 @@ +export function objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); +} + +export function isFunction(x) { + return typeof x === 'function'; +} + +export function isMaybeThenable(x) { + return typeof x === 'object' && x !== null; +} + +var _isArray; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +export var isArray = _isArray; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/package.json new file mode 100644 index 0000000..29333a9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/package.json @@ -0,0 +1,93 @@ +{ + "name": "es6-promise", + "namespace": "es6-promise", + "version": "3.0.2", + "description": "A lightweight library that provides tools for organizing asynchronous code", + "main": "dist/es6-promise.js", + "directories": { + "lib": "lib" + }, + "files": [ + "dist", + "lib", + "!dist/test" + ], + "devDependencies": { + "bower": "^1.3.9", + "brfs": "0.0.8", + "broccoli-es3-safe-recast": "0.0.8", + "broccoli-es6-module-transpiler": "^0.5.0", + "broccoli-jshint": "^0.5.1", + "broccoli-merge-trees": "^0.1.4", + "broccoli-replace": "^0.2.0", + "broccoli-stew": "0.0.6", + "broccoli-uglify-js": "^0.1.3", + "broccoli-watchify": "^0.2.0", + "ember-cli": "0.2.3", + "ember-publisher": "0.0.7", + "git-repo-version": "0.0.2", + "json3": "^3.3.2", + "minimatch": "^2.0.1", + "mocha": "^1.20.1", + "promises-aplus-tests-phantom": "^2.1.0-revise", + "release-it": "0.0.10" + }, + "scripts": { + "build": "ember build", + "start": "ember s", + "test": "ember test", + "test:server": "ember test --server", + "test:node": "ember build && mocha ./dist/test/browserify", + "lint": "jshint lib", + "prepublish": "ember build --environment production", + "dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive" + }, + "repository": { + "type": "git", + "url": "git://github.com/jakearchibald/ES6-Promises.git" + }, + "bugs": { + "url": "https://github.com/jakearchibald/ES6-Promises/issues" + }, + "browser": { + "vertx": false + }, + "keywords": [ + "promises", + "futures" + ], + "author": { + "name": "Yehuda Katz, Tom Dale, Stefan Penner and contributors", + "url": "Conversion to ES6 API by Jake Archibald" + }, + "license": "MIT", + "spm": { + "main": "dist/es6-promise.js" + }, + "gitHead": "6c49ef79609737bac2b496d508806a3d5e37303e", + "homepage": "https://github.com/jakearchibald/ES6-Promises#readme", + "_id": "es6-promise@3.0.2", + "_shasum": "010d5858423a5f118979665f46486a95c6ee2bb6", + "_from": "es6-promise@3.0.2", + "_npmVersion": "2.13.4", + "_nodeVersion": "2.2.1", + "_npmUser": { + "name": "stefanpenner", + "email": "stefan.penner@gmail.com" + }, + "maintainers": [ + { + "name": "jaffathecake", + "email": "jaffathecake@gmail.com" + }, + { + "name": "stefanpenner", + "email": "stefan.penner@gmail.com" + } + ], + "dist": { + "shasum": "010d5858423a5f118979665f46486a95c6ee2bb6", + "tarball": "http://registry.npmjs.org/es6-promise/-/es6-promise-3.0.2.tgz" + }, + "_resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.0.2.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/.coveralls.yml b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/.coveralls.yml new file mode 100644 index 0000000..a0b4fb6 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/.coveralls.yml @@ -0,0 +1 @@ +repo_token: 47iIZ0B3llo2Wc4dxWRltvgdImqcrVDTi diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md new file mode 100644 index 0000000..e0f93d7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md @@ -0,0 +1,351 @@ +1.3.1 2016-02-05 +---------------- +- Removed annoying missing Kerberos error (NODE-654). + +1.3.0 2016-02-03 +---------------- +- Added raw support for the command function on topologies. +- Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +- Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +- Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +- NODE-638, Cannot authenticate database user with utf-8 password. +- Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +- Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +- Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +- Switched to using Array.push instead of concat for use cases of a lot of documents. +- Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +- Added peer optional dependencies support using require_optional module. + +1.2.32 2016-01-12 +----------------- +- Bumped bson to V0.4.21 to allow using minor optimizations. + +1.2.31 2016-01-04 +----------------- +- Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +1.2.30 2015-12-23 +----------------- +- Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +- Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +1.2.29 2015-12-17 +----------------- +- Correctly emit close event when calling destroy on server topology. + +1.2.28 2015-12-13 +----------------- +- Backed out Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous) as it breaks node 0.10.x support. + +1.2.27 2015-12-13 +----------------- +- Added [options.checkServerIdentity=true] {boolean|function}. Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function, (Issue #29). +- Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous). +- State is not defined in mongos, (Issue #63, https://github.com/flyingfisher). +- Fixed corner case issue on exhaust cursors on pre 3.0.x MongoDB. + +1.2.26 2015-11-23 +----------------- +- Converted test suite to use mongodb-topology-manager. +- Upgraded bson library to V0.4.20. +- Minor fixes for 3.2 readPreferences. + +1.2.25 2015-11-23 +----------------- +- Correctly error out when passed a seedlist of non-valid server members. + +1.2.24 2015-11-20 +----------------- +- Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). +- $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + +1.2.23 2015-11-16 +----------------- +- ismaster runs against admin.$cmd instead of system.$cmd. + +1.2.22 2015-11-16 +----------------- +- Fixes to handle getMore command errors for MongoDB 3.2 +- Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +1.2.21 2015-11-07 +----------------- +- Hardened the checking for replicaset equality checks. +- OpReplay flag correctly set on Wire protocol query. +- Mongos load balancing added, introduced localThresholdMS to control the feature. +- Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +1.2.20 2015-10-28 +----------------- +- Fixed bug in arbiter connection capping code. +- NODE-599 correctly handle arrays of server tags in order of priority. +- Fix for 2.6 wire protocol handler related to readPreference handling. +- Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +- Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +1.2.19 2015-10-15 +----------------- +- Make batchSize always be > 0 for 3.2 wire protocol to make it work consistently with pre 3.2 servers. +- Locked to bson 0.4.19. + +1.2.18 2015-10-15 +----------------- +- Minor 3.2 fix for handling readPreferences on sharded commands. +- Minor fixes to correctly pass APM specification test suite. + +1.2.17 2015-10-08 +----------------- +- Connections to arbiters only maintain a single connection. + +1.2.15 2015-10-06 +----------------- +- Set slaveOk to true for getMore and killCursors commands. +- Don't swallow callback errors for 2.4 single server (Issue #49, https://github.com/vkarpov15). +- Apply toString('hex') to each buffer in an array when logging (Issue #48, https://github.com/nbrachet). + +1.2.14 2015-09-28 +----------------- +- NODE-547 only emit error if there are any listeners. +- Fixed APM issue with issuing readConcern. + +1.2.13 2015-09-18 +----------------- +- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. + +1.2.12 2015-09-08 +----------------- +- NODE-541 Added initial support for readConcern. + +1.2.11 2015-08-31 +----------------- +- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. +- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. +- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). + +1.2.10 2015-08-14 +----------------- +- Added missing Mongos.prototype.parserType function. + +1.2.9 2015-08-05 +---------------- +- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +- NODE-518 connectTimeoutMS is doubled in 2.0.39. + +1.2.8 2015-07-24 +----------------- +- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. + +1.2.7 2015-07-16 +----------------- +- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. + +1.2.6 2015-07-14 +----------------- +- NODE-505 Query fails to find records that have a 'result' property with an array value. + +1.2.5 2015-07-14 +----------------- +- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. + +1.2.4 2015-07-07 +----------------- +- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. + +1.2.3 2015-06-26 +----------------- +- Minor bug fixes. + +1.2.2 2015-06-22 +----------------- +- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). + +1.2.1 2015-06-17 +----------------- +- Ensure serializeFunctions passed down correctly to wire protocol. + +1.2.0 2015-06-17 +----------------- +- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. +- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. +- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +1.1.33 2015-05-31 +----------------- +- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. + +1.1.32 2015-05-20 +----------------- +- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) + +1.1.31 2015-05-19 +----------------- +- Minor fixes for issues with re-authentication of mongos. + +1.1.30 2015-05-18 +----------------- +- Correctly emit 'all' event when primary + all secondaries have connected. + +1.1.29 2015-05-17 +----------------- +- NODE-464 Only use a single socket against arbiters and hidden servers. +- Ensure we filter out hidden servers from any server queries. + +1.1.28 2015-05-12 +----------------- +- Fixed buffer compare for electionId for < node 12.0.2 + +1.1.27 2015-05-12 +----------------- +- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. + +1.1.26 2015-05-06 +----------------- +- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. +- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. + +1.1.25 2015-04-24 +----------------- +- Handle lack of callback in crud operations when returning error on application closed. + +1.1.24 2015-04-22 +----------------- +- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. + +1.1.23 2015-04-15 +----------------- +- Standardizing mongoErrors and its API (Issue #14) +- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) +- remove mkdirp and rimraf dependencies (Issue #12) +- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) +- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) +- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) + +1.1.22 2015-04-10 +----------------- +- Minor refactorings in cursor code to make extending the cursor simpler. +- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. + +1.1.21 2015-03-26 +----------------- +- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. + +1.1.20 2015-03-24 +----------------- +- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. + +1.1.19 2015-03-21 +----------------- +- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. + +1.1.18 2015-03-17 +----------------- +- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. + +1.1.17 2015-03-16 +----------------- +- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. + +1.1.16 2015-03-06 +----------------- +- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. + +1.1.15 2015-03-04 +----------------- +- Removed check for type in replset pickserver function. + +1.1.14 2015-02-26 +----------------- +- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads + +1.1.13 2015-02-24 +----------------- +- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) + +1.1.12 2015-02-16 +----------------- +- Fixed cursor transforms for buffered document reads from cursor. + +1.1.11 2015-02-02 +----------------- +- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +1.1.10 2015-31-01 +----------------- +- Added tranforms.doc option to cursor to allow for pr. document transformations. + +1.1.9 2015-21-01 +---------------- +- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. +- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. +- Don't treat findOne() as a command cursor. +- Refactored out state changes into methods to simplify read the next method. + +1.1.8 2015-09-12 +---------------- +- Stripped out Object.defineProperty for performance reasons +- Applied more performance optimizations. +- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit + +1.1.7 2014-18-12 +---------------- +- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. + +1.1.6 2014-18-12 +---------------- +- Server manager fixed to support 2.2.X servers for travis test matrix. + +1.1.5 2014-17-12 +---------------- +- Fall back to errmsg when creating MongoError for command errors + +1.1.4 2014-17-12 +---------------- +- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. +- Fixed variable leak in scram. +- Fixed server manager to deal better with killing processes. +- Bumped bson to 0.2.16. + +1.1.3 2014-01-12 +---------------- +- Fixed error handling issue with nonce generation in mongocr. +- Fixed issues with restarting servers when using ssl. +- Using strict for all classes. +- Cleaned up any escaping global variables. + +1.1.2 2014-20-11 +---------------- +- Correctly encoding UTF8 collection names on wire protocol messages. +- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. + +1.1.1 2014-14-11 +---------------- +- Refactored code to use prototype instead of privileged methods. +- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. +- Several deopt optimizations for v8 to improve performance and reduce GC pauses. + +1.0.5 2014-29-10 +---------------- +- Fixed issue with wrong namespace being created for command cursors. + +1.0.4 2014-24-10 +---------------- +- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. + +1.0.3 2014-21-10 +---------------- +- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. + +1.0.2 2014-07-10 +---------------- +- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. +- fixed issue with replset_state logging. + +1.0.1 2014-07-10 +---------------- +- Dependency issue solved + +1.0.0 2014-07-10 +---------------- +- Initial release of mongodb-core diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/LICENSE @@ -0,0 +1,201 @@ +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. \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/Makefile b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/Makefile new file mode 100644 index 0000000..36e1202 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/Makefile @@ -0,0 +1,11 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + hugo -s docs/reference -d ../../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/README.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/README.md new file mode 100644 index 0000000..433dd88 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/README.md @@ -0,0 +1,228 @@ +[![Build Status](https://secure.travis-ci.org/christkv/mongodb-core.png)](http://travis-ci.org/christkv/mongodb-core) +[![Coverage Status](https://coveralls.io/repos/github/christkv/mongodb-core/badge.svg?branch=1.3)](https://coveralls.io/github/christkv/mongodb-core?branch=1.3) + +# Description + +The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. + +## MongoDB Node.JS Core Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| apidoc | http://mongodb.github.io/node-mongodb-native/ | +| source | https://github.com/christkv/mongodb-core | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) + +### 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 + +# QuickStart + +The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. + +## Create the package.json file + +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Create a **package.json** using your favorite text editor and fill it in. + +```json +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb-core": "~1.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +## Connecting to MongoDB + +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + test.done(); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + + // Execute the ismaster command + _server.command('system.$cmd', {ismaster: true}, function(err, result) { + + // Perform a document insert + _server.insert('myproject.inserts1', [{a:1}, {a:2}], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(2, results.result.n); + + // Perform a document update + _server.update('myproject.inserts1', [{ + q: {a: 1}, u: {'$set': {b:1}} + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Remove a document + _server.remove('myproject.inserts1', [{ + q: {a: 1}, limit: 1 + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Get a document + var cursor = _server.cursor('integration_tests.inserts_example4', { + find: 'integration_tests.example4' + , query: {a:1} + }); + + // Get the first document + cursor.next(function(err, doc) { + assert.equal(null, err); + assert.equal(2, doc.a); + + // Execute the ismaster command + _server.command("system.$cmd" + , {ismaster: true}, function(err, result) { + assert.equal(null, err) + _server.destroy(); + }); + }); + }); + }); + + test.done(); + }); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. + +* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. +* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. +* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. +* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. +* `command`, Executes a command against MongoDB and returns the result. +* `auth`, Authenticates the current topology using a supported authentication scheme. + +The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. + +## Next steps + +The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/TESTING.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/TESTING.md new file mode 100644 index 0000000..fe03ea0 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/TESTING.md @@ -0,0 +1,18 @@ +Testing setup +============= + +Single Server +------------- +mongod --dbpath=./db + +Replicaset +---------- +mongo --nodb +var x = new ReplSetTest({"useHostName":"false", "nodes" : {node0 : {}, node1 : {}, node2 : {}}}) +x.startSet(); +var config = x.getReplSetConfig() +x.initiate(config); + +Mongos +------ +var s = new ShardingTest( "auth1", 1 , 0 , 2 , {rs: true, noChunkSize : true}); \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/conf.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/conf.json new file mode 100644 index 0000000..c5eca92 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/conf.json @@ -0,0 +1,60 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/tests/functional/operation_example_tests.js", + "lib/topologies/mongos.js", + "lib/topologies/command_result.js", + "lib/topologies/read_preference.js", + "lib/topologies/replset.js", + "lib/topologies/server.js", + "lib/topologies/session.js", + "lib/topologies/replset_state.js", + "lib/connection/logger.js", + "lib/connection/connection.js", + "lib/cursor.js", + "lib/error.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/index.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/index.js new file mode 100644 index 0000000..8f10860 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/index.js @@ -0,0 +1,18 @@ +module.exports = { + MongoError: require('./lib/error') + , Server: require('./lib/topologies/server') + , ReplSet: require('./lib/topologies/replset') + , Mongos: require('./lib/topologies/mongos') + , Logger: require('./lib/connection/logger') + , Cursor: require('./lib/cursor') + , ReadPreference: require('./lib/topologies/read_preference') + , BSON: require('bson') + // Raw operations + , Query: require('./lib/connection/commands').Query + // Auth mechanisms + , MongoCR: require('./lib/auth/mongocr') + , X509: require('./lib/auth/x509') + , Plain: require('./lib/auth/plain') + , GSSAPI: require('./lib/auth/gssapi') + , ScramSHA1: require('./lib/auth/scram') +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js new file mode 100644 index 0000000..dc7b546 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js @@ -0,0 +1,246 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , require_optional = require('require_optional') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require_optional('kerberos').Kerberos; + // Authentication process for Mongo + MongoAuthProcess = require_optional('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new GSSAPI authentication mechanism + * @class + * @return {GSSAPI} A cursor instance + */ +var GSSAPI = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.auth = function(server, connections, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // 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 execute = function(connection) { + // Start Auth process for a connection + GSSAPIInitialize(db, username, password, db, gssapiServiceName, server, connection, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// +// Initialize step +var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, server, connection, callback) { + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.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, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback) { + // Build the sasl start command + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: payload + , autoAuthorize: 1 + }; + + // Execute first sasl step + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // Execute mongodb transition + mongo_auth_process.transition(r.result.payload, function(err, payload) { + if(err) return callback(err, false); + + // MongoDB API Second Step + MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // 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, server, connection, callback); + }); + }); +} + +var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build final command + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + mongo_auth_process.transition(null, function(err, payload) { + if(err) return callback(err, null); + callback(null, r); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var err = null; + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, authStore[i].options, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = GSSAPI; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js new file mode 100644 index 0000000..a23bcb9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js @@ -0,0 +1,161 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new MongoCR authentication mechanism + * @class + * @return {MongoCR} A cursor instance + */ +var MongoCR = function() { + this.authStore = []; +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // 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 executeMongoCR = function(connection) { + // Let's start the process + server.command(f("%s.$cmd", db) + , { getnonce: 1 } + , { connection: connection }, function(err, r) { + var nonce = null; + var key = null; + + // Adjust the number of connections left + // Get nonce + if(err == null) { + nonce = r.result.nonce; + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password, 'utf8'); + var hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + + // Execute command + server.command(f("%s.$cmd", db) + , { authenticate: 1, user: username, nonce: nonce, key:key} + , { connection: connection }, function(err, r) { + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + }); + } + + // Get the connection + executeMongoCR(connections.shift()); + } +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var err = null; + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = MongoCR; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js new file mode 100644 index 0000000..83eb3d3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js @@ -0,0 +1,151 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Binary = require('bson').Binary + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new Plain authentication mechanism + * @class + * @return {Plain} A cursor instance + */ +var Plain = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // 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 execute = function(connection) { + // Create payload + var payload = new Binary(f("\x00%s\x00%s", username, password)); + + // Let's start the sasl process + var command = { + saslStart: 1 + , mechanism: 'PLAIN' + , payload: payload + , autoAuthorize: 1 + }; + + // Let's start the process + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var err = null; + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = Plain; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js new file mode 100644 index 0000000..7f8e60b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js @@ -0,0 +1,322 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Binary = require('bson').Binary + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +var id = 0; + +/** + * Creates a new ScramSHA1 authentication mechanism + * @class + * @return {ScramSHA1} A cursor instance + */ +var ScramSHA1 = function() { + this.authStore = []; + this.id = id++; +} + +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 new MongoError("username must be a string"); + if(typeof password != 'string') throw new MongoError("password must be a string"); + if(password.length == 0) throw new MongoError("password cannot be empty"); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password, 'utf8'); + 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); + return new Buffer(hmac.digest('base64'), 'base64'); + } + + // 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; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // 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) { + numberOfValidConnections = numberOfValidConnections - 1; + errorObject = err; return false; + } else if(r.result['$err']) { + errorObject = r.result; return false; + } else if(r.result['errmsg']) { + errorObject = r.result; return false; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + return true + } + + // Finish up + var finish = function(_count, _numberOfValidConnections) { + if(_count == 0 && _numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(_count == 0) { + if(errorObject == null) errorObject = new MongoError(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 + server.command(f("%s.$cmd", db) + , 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(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); + return callback(errorObject, false); + } + + return; + } + + // Get the dictionary + var dict = parsePayload(r.result.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 = new Buffer(hmac.digest('base64'), 'base64'); + + // Create the stored key + var hash = crypto.createHash('sha1'); + hash.update(clientKey); + var storedKey = new Buffer(hash.digest('base64'), 'base64'); + + // Create the authentication message + var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join(','); + + // Create client signature + var hmac = crypto.createHmac('sha1', storedKey); + hmac.update(new Buffer(authMsg)); + var clientSig = new Buffer(hmac.digest('base64'), 'base64'); + + // 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 = new Buffer(hmac.digest('base64'), 'base64'); + + // Generate server signature + var hmac = crypto.createHmac('sha1', serverKey); + hmac.update(new Buffer(authMsg)) + var serverSig = new Buffer(hmac.digest('base64'), 'base64'); + + // + // Create continue message + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Binary(new Buffer(clientFinal)) + } + + // + // Execute sasl continue + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + if(r && r.result.done == false) { + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Buffer(0) + } + + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + handleEnd(err, r); + }); + } else { + handleEnd(err, r); + } + }); + }); + } + + // Get the connection + executeScram(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + var err = null; + // No connections + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + + +module.exports = ScramSHA1; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js new file mode 100644 index 0000000..44eece7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js @@ -0,0 +1,236 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , require_optional = require('require_optional') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require_optional('kerberos').Kerberos + // Authentication process for Mongo + MongoAuthProcess = require_optional('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new SSPI authentication mechanism + * @class + * @return {SSPI} A cursor instance + */ +var SSPI = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.auth = function(server, connections, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // 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 execute = function(connection) { + // Start Auth process for a connection + SSIPAuthenticate(username, password, gssapiServiceName, server, connection, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r && typeof r == 'object' && r.result['$err']) { + errorObject = r.result; + } else if(r && typeof r == 'object' && r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +var SSIPAuthenticate = function(username, password, gssapiServiceName, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: '' + , autoAuthorize: 1 + }; + + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); + + // Execute first sasl step + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + 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 + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + 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 + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + 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 + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + if(doc.done) return callback(null, true); + callback(new Error("Authentication failed"), false); + }); + }); + }); + }); + }); + }); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var err = null; + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, authStore[i].options, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = SSPI; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js new file mode 100644 index 0000000..59839c3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js @@ -0,0 +1,146 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new X509 authentication mechanism + * @class + * @return {X509} A cursor instance + */ +var X509 = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // 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 execute = function(connection) { + // Let's start the sasl process + var command = { + authenticate: 1 + , mechanism: 'MONGODB-X509' + , user: username + }; + + // Let's start the process + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var err = null; + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = X509; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js new file mode 100644 index 0000000..98950e4 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js @@ -0,0 +1,540 @@ +"use strict"; + +var f = require('util').format + , Long = require('bson').Long + , setProperty = require('./utils').setProperty + , getProperty = require('./utils').getProperty + , getSingleProperty = require('./utils').getSingleProperty; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var OP_QUERY = 2004; +var OP_GETMORE = 2005; +var OP_KILL_CURSORS = 2007; + +// Query flags +var OPTS_NONE = 0; +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 0; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if(ns == null) throw new Error("ns must be specified for query"); + if(query == null) throw new Error("query must be specified for query"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new Error("namespace cannot contain a null character"); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Ensure empty options + this.options = options || {}; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = _requestId++; + + // Serialization option + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +} + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +} + +// +// Assign a new request Id +Query.nextRequestId = function() { + return _requestId + 1; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + var buffers = []; + var projection = null; + + // Set up the flags + var flags = 0; + if(this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if(this.slaveOk) { + flags |= OPTS_SLAVE; + } + + if(this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if(this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if(this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if(this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if(this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to self.numberToReturn + if(self.batchSize != self.numberToReturn) self.numberToReturn = self.batchSize; + + // Allocate write protocol header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // Flags + + Buffer.byteLength(self.ns) + 1 // namespace + + 4 // numberToSkip + + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + var query = self.bson.serialize(this.query + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + + // Add query document + buffers.push(query); + + if(self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = self.bson.serialize(this.returnFieldSelector, this.checkKeys, true, this.serializeFunctions, this.ignoreUndefined); + // Add projection document + buffers.push(projection); + } + + // Total message size + var totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + var index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = (totalLength) & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (OP_QUERY >> 24) & 0xff; + header[index + 2] = (OP_QUERY >> 16) & 0xff; + header[index + 1] = (OP_QUERY >> 8) & 0xff; + header[index] = (OP_QUERY) & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = (flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = (this.numberToSkip) & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +Query.getRequestId = function() { + return ++_requestId; +} + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + (4 * 4); + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; + _buffer[index] = (OP_GETMORE) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getHighBits()) & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +} + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, cursorIds) { + this.requestId = _requestId++; + this.cursorIds = cursorIds; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); + + // Create command buffer + var index = 0; + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = (OP_KILL_CURSORS) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = (this.cursorIds.length) & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for(var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getHighBits()) & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +} + +var Response = function(connection, bson, data, opts) { + opts = opts || {promoteLongs: true}; + this.parsed = false; + this.connection = connection; + + // + // Parse Header + // + this.index = 0; + this.raw = data; + this.data = data; + this.bson = bson; + this.opts = opts; + + // Read the message length + this.length = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the request id for this reply + this.requestId = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the id of the request that triggered the response + this.responseTo = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Skip op-code field + this.index = this.index + 4; + + // Unpack flags + this.responseFlags = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the cursor + var lowBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + var highBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + // Create long object + this.cursorId = new Long(lowBits, highBits); + + // Unpack the starting from + this.startingFrom = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the number of objects returned + this.numberReturned = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) != 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) != 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) != 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) != 0; + this.promoteLongs = typeof opts.promoteLongs == 'boolean' ? opts.promoteLongs : true; +} + +Response.prototype.isParsed = function() { + return this.parsed; +} + +// Validation buffers +var firstBatch = new Buffer('firstBatch', 'utf8'); +var nextBatch = new Buffer('nextBatch', 'utf8'); +var cursorId = new Buffer('id', 'utf8').toString('hex'); + +var documentBuffers = { + firstBatch: firstBatch.toString('hex'), + nextBatch: nextBatch.toString('hex') +}; + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if(this.parsed) return; + options = options || {}; + + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + var documentsReturnedIn = options.documentsReturnedIn || null; + + // + // Single document and documentsReturnedIn set + // + if(this.numberReturned == 1 && documentsReturnedIn != null && raw) { + // Calculate the bson size + var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + // Slice out the buffer containing the command result document + var document = this.data.slice(this.index, this.index + bsonSize); + // Set up field we wish to keep as raw + var fieldsAsRaw = {} + fieldsAsRaw[documentsReturnedIn] = true; + // Set up the options + var _options = {promoteLongs: this.opts.promoteLongs, fieldsAsRaw: fieldsAsRaw}; + + // Deserialize but keep the array of documents in non-parsed form + var doc = this.bson.deserialize(document, _options); + + // Get the documents + this.documents = doc.cursor[documentsReturnedIn]; + this.numberReturned = this.documents.length; + // Ensure we have a Long valie cursor id + this.cursorId = typeof doc.cursor.id == 'number' + ? Long.fromNumber(doc.cursor.id) + : doc.cursor.id; + + // Adjust the index + this.index = this.index + bsonSize; + + // Set as parsed + this.parsed = true + return; + } + + // + // Parse Body + // + for(var i = 0; i < this.numberReturned; i++) { + var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + // Parse options + var _options = {promoteLongs: this.opts.promoteLongs}; + + // If we have raw results specified slice the return document + if(raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + // Set parsed + this.parsed = true; +} + +module.exports = { + Query: Query + , GetMore: GetMore + , Response: Response + , KillCursor: KillCursor +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js new file mode 100644 index 0000000..6359e6a --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js @@ -0,0 +1,496 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , net = require('net') + , tls = require('tls') + , f = require('util').format + , crypto = require('crypto') + , getSingleProperty = require('./utils').getSingleProperty + , debugOptions = require('./utils').debugOptions + , Response = require('./commands').Response + , MongoError = require('../error') + , Logger = require('./logger'); + +var _id = 0; +var debugFields = ['host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay' + , 'connectionTimeout', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert' + , 'rejectUnauthorized', 'promoteLongs', 'checkServerIdentity']; + +/** + * Creates a new Connection instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @return {Connection} A cursor instance + */ +var Connection = function(options) { + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + // Identification information + this.id = _id++; + // Logger instance + this.logger = Logger('Connection', options); + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Get bson parser + this.bson = options.bson; + // Grouping tag used for debugging purposes + this.tag = options.tag; + // Message handler + this.messageHandler = options.messageHandler; + + // Max BSON message size + this.maxBsonMessageSize = options.maxBsonMessageSize || (1024 * 1024 * 16 * 4); + // Debug information + if(this.logger.isDebug()) this.logger.debug(f('creating connection %s with options [%s]', this.id, JSON.stringify(debugOptions(debugFields, options)))); + + // Default options + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.keepAlive = typeof options.keepAlive == 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = options.keepAliveInitialDelay || 0; + this.noDelay = typeof options.noDelay == 'boolean' ? options.noDelay : true; + this.connectionTimeout = options.connectionTimeout || 0; + this.socketTimeout = options.socketTimeout || 0; + + // If connection was destroyed + this.destroyed = false; + + // Check if we have a domain socket + this.domainSocket = this.host.indexOf('\/') != -1; + + // Serialize commands using function + this.singleBufferSerializtion = typeof options.singleBufferSerializtion == 'boolean' ? options.singleBufferSerializtion : true; + this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; + + // SSL options + this.ca = options.ca || null; + this.cert = options.cert || null; + this.key = options.key || null; + this.passphrase = options.passphrase || null; + this.ssl = typeof options.ssl == 'boolean' ? options.ssl : false; + this.rejectUnauthorized = typeof options.rejectUnauthorized == 'boolean' ? options.rejectUnauthorized : true; + this.checkServerIdentity = typeof options.checkServerIdentity == 'boolean' + || typeof options.checkServerIdentity == 'function' ? options.checkServerIdentity : true; + + // If ssl not enabled + if(!this.ssl) this.rejectUnauthorized = false; + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true + } + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.connection = null; + this.writeStream = null; + + // Create hash method + var hash = crypto.createHash('sha1'); + hash.update(f('%s:%s', this.host, this.port)); + + // Create a hash name + this.hashedName = hash.digest('hex'); +} + +inherits(Connection, EventEmitter); + +// +// Connection handlers +var errorHandler = function(self) { + return function(err) { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] errored out with [%s]', self.id, self.host, self.port, JSON.stringify(err))); + // Emit the error + if(self.listeners('error').length > 0) self.emit("error", MongoError.create(err), self); + } +} + +var timeoutHandler = function(self) { + return function() { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); + // Emit timeout error + self.emit("timeout" + , MongoError.create(f("connection %s to %s:%s timed out", self.id, self.host, self.port)) + , self); + } +} + +var closeHandler = function(self) { + return function(hadError) { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); + // Emit close event + if(!hadError) { + self.emit("close" + , MongoError.create(f("connection %s to %s:%s closed", self.id, self.host, self.port)) + , self); + } + } +} + +var dataHandler = function(self) { + 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.messageHandler(new Response(self, self.bson, emitBuffer, self.responseOptions), self); + } catch(err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // 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 = data.readUInt32LE(0); + var sizeOfMessage = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; + // If we have a negative sizeOfMessage emit error and return + if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { + var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ + sizeOfMessage: sizeOfMessage, + bytesRead: self.bytesRead, + stubBuffer: self.stubBuffer}}; + // 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.maxBsonMessageSize && 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.maxBsonMessageSize && 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.messageHandler(new Response(self, self.bson, emitBuffer, self.responseOptions), self); + } catch (err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + } + } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { + var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ + sizeOfMessage:sizeOfMessage, + bytesRead:0, + buffer:null, + stubBuffer:null}}; + // 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 { + 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.messageHandler(new Response(self, self.bson, emitBuffer, self.responseOptions), 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); + } + } + } + } + } +} + +/** + * Connect + * @method + */ +Connection.prototype.connect = function(_options) { + var self = this; + _options = _options || {}; + // Check if we are overriding the promoteLongs + if(typeof _options.promoteLongs == 'boolean') { + self.responseOptions.promoteLongs = _options.promoteLongs; + } + + // Create new connection instance + self.connection = self.domainSocket + ? net.createConnection(self.host) + : net.createConnection(self.port, self.host); + + // Set the options for the connection + self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); + self.connection.setTimeout(self.connectionTimeout); + self.connection.setNoDelay(self.noDelay); + + // If we have ssl enabled + if(self.ssl) { + var sslOptions = { + socket: self.connection + , rejectUnauthorized: self.rejectUnauthorized + } + + if(self.ca) sslOptions.ca = self.ca; + if(self.cert) sslOptions.cert = self.cert; + if(self.key) sslOptions.key = self.key; + if(self.passphrase) sslOptions.passphrase = self.passphrase; + + // Override checkServerIdentity behavior + if(self.checkServerIdentity == false) { + // Skip the identiy check by retuning undefined as per node documents + // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback + sslOptions.checkServerIdentity = function(servername, cert) { + return undefined; + } + } else if(typeof self.checkServerIdentity == 'function') { + sslOptions.checkServerIdentity = self.checkServerIdentity; + } + + // Attempt SSL connection + self.connection = tls.connect(self.port, self.host, sslOptions, function() { + // Error on auth or skip + if(self.connection.authorizationError && self.rejectUnauthorized) { + return self.emit("error", self.connection.authorizationError, self, {ssl:true}); + } + + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // We are done emit connect + self.emit('connect', self); + }); + self.connection.setTimeout(self.connectionTimeout); + } else { + self.connection.on('connect', function() { + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // Emit connect event + self.emit('connect', self); + }); + } + + // Add handlers for events + self.connection.once('error', errorHandler(self)); + self.connection.once('timeout', timeoutHandler(self)); + self.connection.once('close', closeHandler(self)); + self.connection.on('data', dataHandler(self)); +} + +/** + * Destroy connection + * @method + */ +Connection.prototype.destroy = function() { + if(this.connection) { + this.connection.end(); + this.connection.destroy(); + } + + this.destroyed = true; +} + +/** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ +Connection.prototype.write = function(buffer) { + // Debug Log + if(this.logger.isDebug()) { + if(!Array.isArray(buffer)) { + this.logger.debug(f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port)); + } else { + for(var i = 0; i < buffer.length; i++) + this.logger.debug(f('writing buffer [%s] to %s:%s', buffer[i].toString('hex'), this.host, this.port)); + } + } + + // Write out the command + if(!Array.isArray(buffer)) return this.connection.write(buffer, 'binary'); + // Iterate over all buffers and write them in order to the socket + for(var i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); +} + +/** + * Return id of connection as a string + * @method + * @return {string} + */ +Connection.prototype.toString = function() { + return "" + this.id; +} + +/** + * Return json object of connection + * @method + * @return {object} + */ +Connection.prototype.toJSON = function() { + return {id: this.id, host: this.host, port: this.port}; +} + +/** + * Is the connection connected + * @method + * @return {boolean} + */ +Connection.prototype.isConnected = function() { + if(this.destroyed) return false; + return !this.connection.destroyed && this.connection.writable; +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +module.exports = Connection; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js new file mode 100644 index 0000000..69c6f93 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js @@ -0,0 +1,196 @@ +"use strict"; + +var f = require('util').format + , MongoError = require('../error'); + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Function} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + * @return {Logger} a Logger instance. + */ +var Logger = function(className, options) { + if(!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + var self = this; + this.className = className; + + // Current logger + if(currentLogger == null && options.logger) { + currentLogger = options.logger; + } else if(currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if(level == null) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if(filteredClasses[this.className] == null) classFilters[this.className] = true; +} + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if(this.isDebug() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +} + +/** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.info = function(message, object) { + if(this.isInfo() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.error = function(message, object) { + if(this.isError() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Is the logger set at info level + * @method + * @return {boolean} + */ +Logger.prototype.isInfo = function() { + return level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at error level + * @method + * @return {boolean} + */ +Logger.prototype.isError = function() { + return level == 'error' || level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at debug level + * @method + * @return {boolean} + */ +Logger.prototype.isDebug = function() { + return level == 'debug'; +} + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +} + +/** + * Get the current logger function + * @method + * @return {function} + */ +Logger.currentLogger = function() { + return currentLogger; +} + +/** + * Set the current logger function + * @method + * @param {function} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if(typeof logger != 'function') throw new MongoError("current logger must be a function"); + currentLogger = logger; +} + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if(type == 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +} + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if(_level != 'info' && _level != 'error' && _level != 'debug') throw new Error(f("%s is an illegal logging level", _level)); + level = _level; +} + +module.exports = Logger; \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js new file mode 100644 index 0000000..9d488a9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js @@ -0,0 +1,614 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , Connection = require('./connection') + , Query = require('./commands').Query + , Logger = require('./logger') + , f = require('util').format; + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +var _id = 0; + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=1] Max server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passPhrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(options) { + var self = this; + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + this.size = typeof options.size == 'number' && !isNaN(options.size) ? options.size : 5; + this.waitMS = typeof options.waitMS == 'number' && !isNaN(options.waitMS) ? options.waitMS : 1000; + + // Save host and port + this.host = options.host; + this.port = options.port; + + // Message handler + this.messageHandler = options.messageHandler; + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Contains all connections + this.connections = []; + // Contains all available connections + this.availableConnections = []; + this.inUseConnections = []; + this.newConnections = []; + this.connectingConnections = []; + // Current status of the pool + this.state = DISCONNECTED; + // Round robin index + this.index = 0; + this.dead = false; + // Logger instance + this.logger = Logger('Pool', options); + // If we are monitoring this server we will create an exclusive reserved socket for that + this.monitoring = typeof options.monitoring == 'boolean' ? options.monitoring : false; + // Maintain the monitoring connection + this.monitorConnection = null; + // Pool id + this.id = _id++; + // Grouping tag used for debugging purposes + this.tag = options.tag; + // Operation work queue + this.queue = []; + // Currently executing + this.executing = false; +} + +inherits(Pool, EventEmitter); + +var removeConnection = function(self, connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! number Of connection :: " + self.getAll().length) + var remove = function(connections) { + for(var i = 0; i < connections.length; i++) { + if(connections[i] === connection) { + // console.log("!!!!!!!!!!!!! removing the connection") + connections.splice(i, 1); + return true; + } + } + } + + // self.availableConnections.forEach(function(x) { + // console.log(x === connection) + // }) + // + // console.log("availableConnections :: " + self.availableConnections.length); + // console.log("inUseConnections :: " + self.inUseConnections.length); + // console.log("newConnections :: " + self.newConnections.length); + // console.log("connectingConnections :: " + self.connectingConnections.length); + + // Set the monitoring connection to undefined + if(self.monitorConnection === connection) { + self.monitorConnection = null; + } + + // Clean out the connection + if(remove(self.availableConnections)) return; + if(remove(self.inUseConnections)) return; + if(remove(self.newConnections)) return; + if(remove(self.connectingConnections)) return; +} + +var errorHandler = function(self) { + return function(err, connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! error POOL") + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + // Remove the connection + removeConnection(self, connection); + // Emit error + if(self.listeners('error').length > 0) { + self.emit('error', err, connection); + } + } +} + +var timeoutHandler = function(self) { + return function(err, connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! timeout POOL :: " + self.port) + // console.log("----------------------- pool.write _execute 0 :: availableConnections = " + self.availableConnections.length) + // console.log("----------------------- pool.write _execute 0 :: inUseConnections = " + self.inUseConnections.length) + // console.log("----------------------- pool.write _execute 0 :: newConnections = " + self.newConnections.length) + // console.log("----------------------- pool.write _execute 0 :: queue = " + self.queue.length) + + // // Get all connections + // self.availableConnections.forEach(function(x) { + // if(x === self.monitorConnection) { + // // console.log("!!!!!!!!!!!!!!!!!!!!!!!!! MONITORING CONNECTION") + // } + // }) + + + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] timed out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + // Remove the connection + removeConnection(self, connection); + // Emit connection timeout to server instance + self.emit('timeout', err, connection); + } +} + +var closeHandler = function(self) { + return function(err, connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! close POOL") + // if(connection === self.monitorConnection){ + // console.log(" monitorConnection closed") + // } + + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] closed [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + // Remove the connection + removeConnection(self, connection); + // Emit connection close to server instance + self.emit('close', err, connection); + } +} + +var parseErrorHandler = function(self) { + return function(err, connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! parseError POOL") + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + // Remove the connection + removeConnection(self, connection); + // Emit error to server instance + self.emit('parseError', err, connection); + } +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function() { + this.state = DESTROYED; + // Set dead + this.dead = true; + // Get all the connections + var connections = this.getAll(); + // Destroy all the connections + connections.forEach(function(c) { + // Destroy all event emitters + ["close", "message", "error", "timeout", "parseError", "connect"].forEach(function(e) { + c.removeAllListeners(e); + }); + + // Destroy the connection + c.destroy(); + }); + + // Do we have a monitoring connection + if(this.monitorConnection) { + this.monitorConnection.destroy(); + } +} + +var execute = null; + +try { + execute = setImmediate; +} catch(err) { + execute = process.nextTick; +} + +// execute = function(x) { +// setTimeout(x, 1) +// } + +// execute = setTimeout; + +/** + * Connect pool + * @method + */ +Pool.prototype.connect = function(_options) { + // console.log("---------------------- CONNECT") + var self = this; + // Set to connecting + this.state = CONNECTING + // No dead + this.dead = false; + + // Ensure we allow for a little time to setup connections + var wait = 1; + + // Number of initial connections to perform + var numberOfConnections = this.monitoring ? 2 : 1; + + // Connect all sockets + for(var i = 0; i < numberOfConnections; i++) { + setTimeout(function() { + execute(function() { + self.options.messageHandler = self.messageHandler; + var connection = new Connection(self.options); + + // Add all handlers + connection.once('close', closeHandler(self)); + connection.once('error', errorHandler(self)); + connection.once('timeout', timeoutHandler(self)); + connection.once('parseError', parseErrorHandler(self)); + connection.on('connect', function(connection) { + // Add the connection to the list of available connections + self.availableConnections.push(connection); + + // Have we finished the initial connection + if(self.availableConnections.length == numberOfConnections) { + // Reserve a monitoring socket + if(self.monitoring) { + self.monitorConnection = self.availableConnections.pop(); + } + + // Done connecting + self.emit("connect", self); + } + }); + + // Start connection + connection.connect(_options); + }); + }, wait); + + // wait for 1 miliseconds before attempting to connect, spacing out connections + wait = wait + 1; + } +} + +var _createConnection = function(self) { + self.options.messageHandler = self.messageHandler; + var connection = new Connection(self.options); + + // Push the connection + self.connectingConnections.push(connection); + + // Handle any errors + var tempErrorHandler = function(err) { + // self.emit('error', err); + } + + // All event handlers + var handlers = ["close", "message", "error", "timeout", "parseError", "connect"]; + + // Handle successful connection + var tempConnectHandler = function() { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 0") + // Destroy all event emitters + handlers.forEach(function(e) { + connection.removeAllListeners(e); + }); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 1") + + // Add the final handlers + connection.once('close', closeHandler(self)); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 3") + connection.once('error', errorHandler(self)); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 4") + connection.once('timeout', timeoutHandler(self)); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 5") + connection.once('parseError', parseErrorHandler(self)); + + // Remove the connection from the connectingConnections + var index = self.connectingConnections.indexOf(connection); + if(index != -1) { + self.connectingConnections.splice(index, 1); + } + + // connection.destroy() + + // Add to queue of new connection + self.newConnections.push(connection); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 8") + // Emit connection to server instance + // alowing it to apply any needed authentication + self.emit('connection', connection); + + // Execute any work waiting + _execute(self)(); + } + + // Add all handlers + connection.once('close', tempErrorHandler); + connection.once('error', tempErrorHandler); + connection.once('timeout', tempErrorHandler); + connection.once('parseError', tempErrorHandler); + connection.once('connect', tempConnectHandler); + + // Start connection + connection.connect(); +} + +var _execute = function(self) { + return function() { + if(self.state == 'DESTROYED') return; + // Already executing, skip + if(self.executing) return; + // Set pool as executing + self.executing = true; + // console.log("----------------------- _execute") + // console.log("----------------------- pool.write _execute 0 :: availableConnections = " + self.availableConnections.length) + // console.log("----------------------- pool.write _execute 0 :: inUseConnections = " + self.inUseConnections.length) + // console.log("----------------------- pool.write _execute 0 :: newConnections = " + self.newConnections.length) + // console.log("----------------------- pool.write _execute 0 :: queue = " + self.queue.length) + + // Total availble connections + var totalConnections = self.availableConnections.length + + self.connectingConnections.length + + self.inUseConnections.length + + self.newConnections.length; + + // Have we not reached the max connection size yet + if(self.availableConnections.length == 0 + && self.connectingConnections.length == 0 + && totalConnections < self.size + && self.queue.length > 0) { + // Create a new connection + _createConnection(self); + // Attempt to execute again + self.executing = false; + return; + } + + // Number of ops to do + var numberOfOps = self.availableConnections.length > self.queue.length + ? self.queue.length : self.availableConnections.length; + + // As long as we have available connections + while(true) { + // No available connections available + if(self.availableConnections.length == 0) break; + if(self.queue.length == 0) break; + + // Get a connection + var connection = self.availableConnections.pop(); + if(connection.isConnected()) { + var workItem = self.queue.shift(); + + // Add connection to callback so we can flush out + // only ops for that connection on a socket closure + if(workItem.cb) { + workItem.cb.connection = connection; + } + + // Get actual binary commands + var buffer = workItem.buffer; + + // Add connection to workers in flight + if(connection !== self.monitorConnection) { + self.inUseConnections.push(connection); + } + + // console.log("---------- write to connection " + connection.id) + + if(Array.isArray(buffer)) { + for(var i = 0; i < buffer.length; i++) { + connection.write(buffer[i]); + } + } else { + connection.write(buffer); + } + + // Fire and forgot message + if(workItem.immediateRelease) { + self.availableConnections.push(connection); + } + } + } + + self.executing = false; + } +} + +/** + * Write a message to MongoDB + * @method + * @return {Connection} + */ +Pool.prototype.write = function(buffer, cb, options) { + // We have a monitoring operation and need to use + // the dedicated connection + if(options && options.monitoring && !this.monitorConnection) { + this.monitorConnection = this.availableConnections.pop(); + } + + if(options && options.monitoring && this.monitorConnection) { + return this.monitorConnection.write(buffer); + } + + // Do we have an operation + var operation = {buffer:buffer, cb: cb}; + // Do we immediately release the connection back to available (fire and forget) + if(options && options.immediateRelease) { + operation.immediateRelease = true; + } + + // Push the operation to the queue of operations in progress + this.queue.push(operation); + // Attempt to write all buffers out + _execute(this)(); +} + +/** + * Make a passed connection available + * @method + * @return {Connection} + */ +Pool.prototype.connectionAvailable = function(connection) { + // console.log("@@@@@@ connectionAvailable :: " + connection.id) + // Get the connection from the newConnections + var index = this.newConnections.indexOf(connection); + if(index != -1) { + this.newConnections.splice(index, 1); + } + + // If it's in the inUseConnections + index = this.inUseConnections.indexOf(connection); + if(index != -1) { + this.inUseConnections.splice(index, 1); + } + + // Add the connection to available connections if it's not a monitoring threads + if(this.availableConnections.indexOf(connection) == -1 + && connection !== this.monitorConnection) { + this.availableConnections.push(connection); + } + + // Fire execute loop + _execute(this)(); +} + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function(options) { + options = options || {}; + + // Set the current index + this.index = this.index + 1; + + // Get all connections + var connections = this.availableConnections.slice(0); + + if(connections.length == 1) { + return connections[0]; + } else { + this.index = this.index % connections.length; + return connections[this.index]; + } +} + +/** + * Reduce the poolSize to the provided max connections value + * @method + * @param {number} maxConnections reduce the poolsize to maxConnections + */ +Pool.prototype.capConnections = function(maxConnections) { + // Do we have more connections than specified slice it + if(this.connections.length > maxConnections) { + // Get the rest of the connections + var connections = this.connections.slice(maxConnections); + // Cap the active connections + this.connections = this.connections.slice(0, maxConnections); + + if (this.index >= maxConnections){ + // Go back to the beggining of the pool if capping connections + this.index = 0; + } + + // Remove all listeners + for(var i = 0; i < connections.length; i++) { + connections[i].removeAllListeners('close'); + connections[i].removeAllListeners('error'); + connections[i].removeAllListeners('timeout'); + connections[i].removeAllListeners('parseError'); + connections[i].removeAllListeners('connect'); + connections[i].destroy(); + } + } +} + +/** + * Get all pool connections + * @method + * @return {array} + */ +Pool.prototype.getAll = function() { + return this.availableConnections + .concat(this.inUseConnections) + .concat(this.connectingConnections) + .concat(this.newConnections); +} + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + // Available connections + for(var i = 0; i < this.availableConnections.length; i++) { + if(this.availableConnections[i].isConnected()) return true; + } + + // inUseConnections + for(var i = 0; i < this.inUseConnections.length; i++) { + if(this.inUseConnections[i].isConnected()) return true; + } + + return this.state == CONNECTED; +} + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state == DESTROYED; +} + + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +module.exports = Pool; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js new file mode 100644 index 0000000..07e4233 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js @@ -0,0 +1,85 @@ +"use strict"; + +// Set property function +var setProperty = function(obj, prop, flag, values) { + Object.defineProperty(obj, prop.name, { + enumerable:true, + set: function(value) { + if(typeof value != 'boolean') throw new Error(f("%s required a boolean", prop.name)); + // Flip the bit to 1 + if(value == true) values.flags |= flag; + // Flip the bit to 0 if it's set, otherwise ignore + if(value == false && (values.flags & flag) == flag) values.flags ^= flag; + prop.value = value; + } + , get: function() { return prop.value; } + }); +} + +// Set property function +var getProperty = function(obj, propName, fieldName, values, func) { + Object.defineProperty(obj, propName, { + enumerable:true, + get: function() { + // Not parsed yet, parse it + if(values[fieldName] == null && obj.isParsed && !obj.isParsed()) { + obj.parse(); + } + + // Do we have a post processing function + if(typeof func == 'function') return func(values[fieldName]); + // Return raw value + return values[fieldName]; + } + }); +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +// Shallow copy +var copy = function(fObj, tObj) { + tObj = tObj || {}; + for(var name in fObj) tObj[name] = fObj[name]; + return tObj; +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) return callback; + var boundCallback = domain.bind(callback); + + // Copy all fields over + for(var name in callback) { + boundCallback[name] = callback[name]; + } + + // Return the bound callback + return boundCallback; +} + +exports.setProperty = setProperty; +exports.getProperty = getProperty; +exports.getSingleProperty = getSingleProperty; +exports.copy = copy; +exports.bindToCurrentDomain = bindToCurrentDomain; +exports.debugOptions = debugOptions; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js new file mode 100644 index 0000000..b435bb3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js @@ -0,0 +1,688 @@ +"use strict"; + +var Long = require('bson').Long + , Logger = require('./connection/logger') + , MongoError = require('./error') + , f = require('util').format; + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * assert.equal(null, err); + * + * // Execute the write + * var cursor = _server.cursor('integration_tests.inserts_example4', { + * find: 'integration_tests.example4' + * , query: {a:1} + * }, { + * readPreference: new ReadPreference('secondary'); + * }); + * + * // Get the first document + * cursor.next(function(err, doc) { + * assert.equal(null, err); + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Cursor, not to be used directly + * @class + * @param {object} bson An instance of the BSON parser + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next + * @param {object} topology The server topology instance. + * @param {object} topologyOptions The server topology options. + * @return {Cursor} A cursor instance + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + options = options || {}; + // Cursor reference + var self = this; + // Initial query + var query = null; + + // Cursor pool + this.pool = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = bson; + this.ns = ns; + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null + , cmd: cmd + , documents: options.documents || [] + , cursorIndex: 0 + , dead: false + , killed: false + , init: false + , notified: false + , limit: options.limit || cmd.limit || 0 + , skip: options.skip || cmd.skip || 0 + , batchSize: options.batchSize || cmd.batchSize || 1000 + , currentLimit: 0 + // Result field name if not a cursor (contains the array of results) + , transforms: options.transforms + } + + // Callback controller + this.callbacks = null; + + // Logger + this.logger = Logger('Cursor', options); + + // + // Did we pass in a cursor id + if(typeof cmd == 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + this.cursorState.lastCursorId = this.cursorState.cursorId; + } else if(cmd instanceof Long) { + this.cursorState.cursorId = cmd; + this.cursorState.lastCursorId = cmd; + } +} + +Cursor.prototype.setCursorBatchSize = function(value) { + this.cursorState.batchSize = value; +} + +Cursor.prototype.cursorBatchSize = function() { + return this.cursorState.batchSize; +} + +Cursor.prototype.setCursorLimit = function(value) { + this.cursorState.limit = value; +} + +Cursor.prototype.cursorLimit = function() { + return this.cursorState.limit; +} + +Cursor.prototype.setCursorSkip = function(value) { + this.cursorState.skip = value; +} + +Cursor.prototype.cursorSkip = function() { + return this.cursorState.skip; +} + +// +// Handle callback (including any exceptions thrown) +var handleCallback = function(callback, err, result) { + try { + callback(err, result); + } catch(err) { + process.nextTick(function() { + throw err; + }); + } +} + +// Internal methods +Cursor.prototype._find = function(callback) { + var self = this; + + if(self.logger.isDebug()) { + self.logger.debug(f("issue initial query [%s] with flags [%s]" + , JSON.stringify(self.cmd) + , JSON.stringify(self.query))); + } + + var queryCallback = function(err, result) { + if(err) return callback(err); + + if(result.queryFailure) { + return callback(MongoError.create(result.documents[0]), null); + } + + // Check if we have a command cursor + if(Array.isArray(result.documents) && result.documents.length == 1 + && (!self.cmd.find || (self.cmd.find && self.cmd.virtual == false)) + && (result.documents[0].cursor != 'string' + || result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || Array.isArray(result.documents[0].result)) + ) { + + // We have a an error document return the error + if(result.documents[0]['$err'] + || result.documents[0]['errmsg']) { + return callback(MongoError.create(result.documents[0]), null); + } + + // We have a cursor document + if(result.documents[0].cursor != null + && typeof result.documents[0].cursor != 'string') { + var id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if(result.documents[0].cursor.ns) { + self.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + self.cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; + self.cursorState.lastCursorId = self.cursorState.cursorId; + // If we have a firstBatch set it + if(Array.isArray(result.documents[0].cursor.firstBatch)) { + self.cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); + } + + // Return after processing command cursor + return callback(null, null); + } + + if(Array.isArray(result.documents[0].result)) { + self.cursorState.documents = result.documents[0].result; + self.cursorState.cursorId = Long.ZERO; + return callback(null, null); + } + } + + // Otherwise fall back to regular find path + self.cursorState.cursorId = result.cursorId; + self.cursorState.documents = result.documents; + self.cursorState.lastCursorId = result.cursorId; + + // Transform the results with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.query == 'function') { + self.cursorState.documents = self.cursorState.transforms.query(result); + } + + // Return callback + callback(null, null); + } + + // If we have a raw query decorate the function + if(self.options.raw || self.cmd.raw) { + queryCallback.raw = self.options.raw || self.cmd.raw; + } + + // Do we have documentsReturnedIn set on the query + if(typeof self.query.documentsReturnedIn == 'string') { + queryCallback.documentsReturnedIn = self.query.documentsReturnedIn; + } + + // Set up callback + self.callbacks.register(self.query.requestId, queryCallback); + + // Write the initial command out + self.pool.write(self.query.toBin(), queryCallback); +} + +Cursor.prototype._getmore = function(callback) { + if(this.logger.isDebug()) this.logger.debug(f("schedule getMore call for query [%s]", JSON.stringify(this.query))) + // Determine if it's a raw query + var raw = this.options.raw || this.cmd.raw; + + // Set the current batchSize + var batchSize = this.cursorState.batchSize; + if(this.cursorState.limit > 0 + && ((this.cursorState.currentLimit + batchSize) > this.cursorState.limit)) { + batchSize = this.cursorState.limit - this.cursorState.currentLimit; + } + + // We have a wire protocol handler + this.server.wireProtocolHandler.getMore(this.bson, this.ns, this.cursorState, batchSize, raw, this.pool, this.callbacks, this.options, callback); +} + +Cursor.prototype._killcursor = function(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if(this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init == false) { + if(callback) callback(null, null); + return; + } + + // Execute command + this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState.cursorId, this.pool, this.callbacks, callback); +} + +/** + * Clone the cursor + * @method + * @return {Cursor} + */ +Cursor.prototype.clone = function() { + return this.topology.cursor(this.ns, this.cmd, this.options); +} + +/** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ +Cursor.prototype.isDead = function() { + return this.cursorState.dead == true; +} + +/** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ +Cursor.prototype.isKilled = function() { + return this.cursorState.killed == true; +} + +/** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ +Cursor.prototype.isNotified = function() { + return this.cursorState.notified == true; +} + +/** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ +Cursor.prototype.bufferedCount = function() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; +} + +/** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ +Cursor.prototype.readBufferedDocuments = function(number) { + var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + var elements = this.cursorState.documents.slice(this.cursorState.cursorIndex, this.cursorState.cursorIndex + length); + + // Transform the doc with passed in transformation method if provided + if(this.cursorState.transforms && typeof this.cursorState.transforms.doc == 'function') { + // Transform all the elements + for(var i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if(this.cursorState.limit > 0 && (this.cursorState.currentLimit + elements.length) > this.cursorState.limit) { + elements = elements.slice(0, (this.cursorState.limit - this.cursorState.currentLimit)); + this.kill(); + } + + // Adjust current limit + this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; + + // Return elements + return elements; +} + +/** + * Kill the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.kill = function(callback) { + this._killcursor(callback); +} + +/** + * Resets the cursor + * @method + * @return {null} + */ +Cursor.prototype.rewind = function() { + if(this.cursorState.init) { + if(!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } +} + +/** + * Validate if the pool is dead and return error + */ +var isConnectionDead = function(self, callback) { + if(self.pool + && !self.pool.isConnected()) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + callback(MongoError.create(f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port))) + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +var isCursorDeadButNotkilled = function(self, callback) { + // Cursor is dead but not marked killed, return null + if(self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +var isCursorDeadAndKilled = function(self, callback) { + if(self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, MongoError.create("cursor is dead")); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +var isCursorKilled = function(self, callback) { + if(self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +var setCursorDeadAndNotified = function(self, callback) { + self.cursorState.dead = true; + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +/** + * Mark cursor as being notified + */ +var setCursorNotified = function(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +var push = Array.prototype.push; + +var nextFunction = function(self, callback) { + // Exhaust message and cursor already finished and notified + if(self.cmd.exhaust && self.cursorState.notified) return; + // We have notified about it + if(self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if(isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if(isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if(isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if(!self.cursorState.init) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.topology.isConnected(self.options) && self.disconnectHandler != null) { + return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); + } + + try { + // Get a server + self.server = self.topology.getServer(self.options); + // Get a connection + self.pool = self.server.s.pool; + // Get the callbacks + self.callbacks = self.server.getCallbacks(); + } catch(err) { + return callback(err); + } + + // Set as init + self.cursorState.init = true; + + try { + // Get the right wire protocol command + self.query = self.server.wireProtocolHandler.command(self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options); + } catch(err) { + return callback(err); + } + } + + // Process exhaust messages + var processExhaustMessages = function(err, result) { + if(err) { + self.cursorState.dead = true; + self.callbacks.unregister(self.query.requestId); + return callback(err); + } + + // Concatenate all the documents + push.apply(self.cursorState.documents, result.documents); + + // If we have no documents left + if(Long.ZERO.equals(result.cursorId)) { + self.cursorState.cursorId = Long.ZERO; + self.callbacks.unregister(self.query.requestId); + return nextFunction(self, callback); + } + + // Set up next listener + self.callbacks.register(result.requestId, processExhaustMessages) + + // Initial result + if(self.cursorState.cursorId == null) { + self.cursorState.cursorId = result.cursorId; + self.cursorState.lastCursorId = result.cursorId; + nextFunction(self, callback); + } + } + + // If we have exhaust + if(self.cmd.exhaust && self.cursorState.cursorId == null) { + // Handle all the exhaust responses + self.callbacks.register(self.query.requestId, processExhaustMessages); + // Write the initial command out + return self.pool.write(self.query.toBin(), processExhaustMessages); + } else if(self.cmd.exhaust && self.cursorState.cursorIndex < self.cursorState.documents.length) { + return handleCallback(callback, null, self.cursorState.documents[self.cursorState.cursorIndex++]); + } else if(self.cmd.exhaust && Long.ZERO.equals(self.cursorState.cursorId)) { + self.callbacks.unregister(self.query.requestId); + return setCursorNotified(self, callback); + } else if(self.cmd.exhaust) { + return setTimeout(function() { + if(Long.ZERO.equals(self.cursorState.cursorId)) return; + nextFunction(self, callback); + }, 1); + } + + // If we don't have a cursorId execute the first query + if(self.cursorState.cursorId == null) { + // Check if pool is dead and return if not possible to + // execute the query against the db + if(isConnectionDead(self, callback)) return; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); + + // query, cmd, options, cursorState, callback + self._find(function(err, r) { + if(err) return handleCallback(callback, err, null); + if(self.cursorState.documents.length == 0 && !self.cmd.tailable && !self.cmd.awaitData) { + return setCursorNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } else if(self.cursorState.cursorIndex == self.cursorState.documents.length + && !Long.ZERO.equals(self.cursorState.cursorId)) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); + + // Check if connection is dead and return if not possible to + // execute a getmore on this connection + if(isConnectionDead(self, callback)) return; + + // Execute the next get more + self._getmore(function(err, doc) { + if(err) return handleCallback(callback, err); + if(self.cursorState.documents.length == 0 + && Long.ZERO.equals(self.cursorState.cursorId) && !self.cmd.tailable) { + self.cursorState.dead = true; + // Finished iterating over the cursor + return setCursorDeadAndNotified(self, callback); + } + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if(self.cursorState.documents.length == 0 && self.cmd.tailable) { + return handleCallback(callback, MongoError.create({ + message: "No more documents in tailed cursor" + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } + + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && self.cmd.tailable) { + return handleCallback(callback, MongoError.create({ + message: "No more documents in tailed cursor" + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && Long.ZERO.equals(self.cursorState.cursorId)) { + setCursorDeadAndNotified(self, callback); + } else { + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Doc overflow + if(doc.$err) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, function() { + handleCallback(callback, new MongoError(doc.$err)); + }); + } + + // Transform the doc with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +} + +/** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.next = function(callback) { + nextFunction(this, callback); +} + +module.exports = Cursor; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js new file mode 100644 index 0000000..4e17ef3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js @@ -0,0 +1,44 @@ +"use strict"; + +/** + * Creates a new MongoError + * @class + * @augments Error + * @param {string} message The error message + * @return {MongoError} A MongoError instance + */ +function MongoError(message) { + this.name = 'MongoError'; + this.message = message; + Error.captureStackTrace(this, MongoError); +} + +/** + * Creates a new MongoError object + * @method + * @param {object} options The error options + * @return {MongoError} A MongoError instance + */ +MongoError.create = function(options) { + var err = null; + + if(options instanceof Error) { + err = new MongoError(options.message); + err.stack = options.stack; + } else if(typeof options == 'string') { + err = new MongoError(options); + } else { + err = new MongoError(options.message || options.errmsg || options.$err || "n/a"); + // Other options + for(var name in options) { + err[name] = options[name]; + } + } + + return err; +} + +// Extend JavaScript error +MongoError.prototype = new Error; + +module.exports = MongoError; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js new file mode 100644 index 0000000..dcceda4 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js @@ -0,0 +1,59 @@ +var fs = require('fs'); + +/* Note: because this plugin uses process.on('uncaughtException'), only one + * of these can exist at any given time. This plugin and anything else that + * uses process.on('uncaughtException') will conflict. */ +exports.attachToRunner = function(runner, outputFile) { + var smokeOutput = { results : [] }; + var runningTests = {}; + + var integraPlugin = { + beforeTest: function(test, callback) { + test.startTime = Date.now(); + runningTests[test.name] = test; + callback(); + }, + afterTest: function(test, callback) { + smokeOutput.results.push({ + status: test.status, + start: test.startTime, + end: Date.now(), + test_file: test.name, + exit_code: 0, + url: "" + }); + delete runningTests[test.name]; + callback(); + }, + beforeExit: function(obj, callback) { + fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { + callback(); + }); + } + }; + + // In case of exception, make sure we write file + process.on('uncaughtException', function(err) { + // Mark all currently running tests as failed + for (var testName in runningTests) { + smokeOutput.results.push({ + status: "fail", + start: runningTests[testName].startTime, + end: Date.now(), + test_file: testName, + exit_code: 0, + url: "" + }); + } + + // write file + fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); + + // Standard NodeJS uncaught exception handler + console.error(err.stack); + process.exit(1); + }); + + runner.plugin(integraPlugin); + return integraPlugin; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js new file mode 100644 index 0000000..ff7bf1b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js @@ -0,0 +1,37 @@ +"use strict"; + +var setProperty = require('../connection/utils').setProperty + , getProperty = require('../connection/utils').getProperty + , getSingleProperty = require('../connection/utils').getSingleProperty; + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection) { + this.result = result; + this.connection = connection; +} + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + return this.result; +} + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +} + +module.exports = CommandResult; \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js new file mode 100644 index 0000000..bd926e7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js @@ -0,0 +1,1056 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , b = require('bson') + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , EventEmitter = require('events').EventEmitter + , BasicCursor = require('../cursor') + , BSON = require('bson').native().BSON + , BasicCursor = require('../cursor') + , Server = require('./server') + , MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram') + , Logger = require('../connection/logger') + , ReadPreference = require('./read_preference') + , Session = require('./session') + , MongoError = require('../error'); + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * @example + * var Mongos = require('mongodb-core').Mongos + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Mongos([{host: 'localhost', port: 30000}]); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; + +// Instance id +var mongosId = 0; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +var State = function(readPreferenceStrategies, localThresholdMS) { + // Internal state + this.s = { + connectedServers: [] + , disconnectedServers: [] + , readPreferenceStrategies: readPreferenceStrategies + , lowerBoundLatency: Number.MAX_VALUE + , localThresholdMS: localThresholdMS + , index: 0 + } +} + +// +// A Mongos connected +State.prototype.connected = function(server) { + // Locate in disconnected servers and remove + this.s.disconnectedServers = this.s.disconnectedServers.filter(function(s) { + return !s.equals(server); + }); + + var found = false; + // Check if the server exists + this.s.connectedServers.forEach(function(s) { + if(s.equals(server)) found = true; + }); + + // Add to disconnected list if it does not already exist + if(!found) this.s.connectedServers.push(server); + + // Adjust lower bound + if(this.s.lowerBoundLatency > server.s.isMasterLatencyMS) { + this.s.lowerBoundLatency = server.s.isMasterLatencyMS; + } +} + +// +// A Mongos disconnected +State.prototype.disconnected = function(server) { + // Locate in disconnected servers and remove + this.s.connectedServers = this.s.connectedServers.filter(function(s) { + return !s.equals(server); + }); + + var found = false; + // Check if the server exists + this.s.disconnectedServers.forEach(function(s) { + if(s.equals(server)) found = true; + }); + + // Add to disconnected list if it does not already exist + if(!found) this.s.disconnectedServers.push(server); +} + +// +// Return the list of disconnected servers +State.prototype.disconnectedServers = function() { + return this.s.disconnectedServers.slice(0); +} + +// +// Get connectedServers +State.prototype.connectedServers = function() { + return this.s.connectedServers.slice(0) +} + +// +// Get all servers +State.prototype.getAll = function() { + return this.s.connectedServers.slice(0).concat(this.s.disconnectedServers); +} + +// +// Get all connections +State.prototype.getAllConnections = function() { + var connections = []; + + this.s.connectedServers.forEach(function(e) { + connections = connections.concat(e.connections()); + }); + return connections; +} + +// +// Destroy the state +State.prototype.destroy = function() { + // Destroy any connected servers + while(this.s.connectedServers.length > 0) { + var server = this.s.connectedServers.shift(); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Server destroy + server.destroy(); + // Add to list of disconnected servers + this.s.disconnectedServers.push(server); + } +} + +// +// Are we connected +State.prototype.isConnected = function() { + return this.s.connectedServers.length > 0; +} + +// +// Pick a server +State.prototype.pickServer = function(readPreference) { + var self = this; + readPreference = readPreference || ReadPreference.primary; + + // Filter out the possible servers + var servers = this.s.connectedServers.filter(function(server) { + if((server.s.isMasterLatencyMS <= (self.s.lowerBoundLatency + self.s.localThresholdMS)) + && server.isConnected()) { + return true; + } + }); + + // Do we have a custom readPreference strategy, use it + if(this.s.readPreferenceStrategies != null && this.s.readPreferenceStrategies[readPreference] != null) { + return this.s.readPreferenceStrategies[readPreference].pickServer(servers, readPreference); + } + + // No valid connections + if(servers.length == 0) throw new MongoError("no mongos proxy available"); + + // Update index + this.s.index = (this.s.index + 1) % servers.length; + + // Pick first one + return servers[this.s.index]; +} + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.reconnectTries=30] Reconnect retries for HA if no servers available + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#joined + * @fires Mongos#left + */ +var Mongos = function(seedlist, options) { + var self = this; + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // BSON Parser, ensure we have a single instance + bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; + // Pick the right bson parser + var bson = options.bson ? options.bson : bsonInstance; + // Add bson parser to options + options.bson = bson; + + // The Mongos state + this.s = { + // Seed list for sharding passed in + seedlist: seedlist + // Passed in options + , options: options + // Logger + , logger: Logger('Mongos', options) + // Reconnect tries + , reconnectTries: options.reconnectTries || 30 + // Ha interval + , haInterval: options.haInterval || 5000 + // localThresholdMS + , localThresholdMS: options.localThresholdMS || 15 + // Have omitted fullsetup + , fullsetup: false + // Cursor factory + , Cursor: options.cursorFactory || BasicCursor + // Current credentials used for auth + , credentials: [] + // BSON Parser + , bsonInstance: bsonInstance + , bson: bson + // Pings + , pings: {} + // Default state + , state: DISCONNECTED + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Contains any alternate strategies for picking + , readPreferenceStrategies: {} + // Auth providers + , authProviders: {} + // Unique instance id + , id: mongosId++ + // Authentication in progress + , authInProgress: false + // Servers added while auth in progress + , authInProgressServers: [] + // Current retries left + , retriesLeft: options.reconnectTries || 30 + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + } + + // Set up the connection timeout for the options + options.connectionTimeout = options.connectionTimeout || 1000; + + // Create a new state for the mongos + this.s.mongosState = new State(this.s.readPreferenceStrategies, this.s.localThresholdMS); + + // Add the authentication mechanisms + this.addAuthProvider('mongocr', new MongoCR()); + this.addAuthProvider('x509', new X509()); + this.addAuthProvider('plain', new Plain()); + this.addAuthProvider('gssapi', new GSSAPI()); + this.addAuthProvider('sspi', new SSPI()); + this.addAuthProvider('scram-sha-1', new ScramSHA1()); + + // BSON property (find a server and pass it along) + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + var servers = self.s.mongosState.getAll(); + return servers.length > 0 ? servers[0].bson : null; + } + }); + + Object.defineProperty(this, 'id', { + enumerable:true, get: function() { return self.s.id; } + }); + + Object.defineProperty(this, 'type', { + enumerable:true, get: function() { return 'mongos'; } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.haInterval; } + }); + + Object.defineProperty(this, 'state', { + enumerable:true, get: function() { return self.s.mongosState; } + }); +} + +inherits(Mongos, EventEmitter); + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +Mongos.prototype.parserType = function() { + if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +Mongos.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + var connectedServers = this.s.mongosState.connectedServers(); + if(connectedServers.length > 0) return connectedServers[0].lastIsMaster(); + return null; +} + +/** + * Initiate server connect + * @method + */ +Mongos.prototype.connect = function(_options) { + var self = this; + // Start replicaset inquiry process + setTimeout(mongosInquirer(self, self.s), self.s.haInterval); + // Additional options + if(_options) for(var name in _options) self.s.options[name] = _options[name]; + // For all entries in the seedlist build a server instance + self.s.seedlist.forEach(function(e) { + // Clone options + var opts = cloneOptions(self.s.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = self.s.readPreferenceStrategies; + // Share the auth store + opts.authProviders = self.s.authProviders; + // Don't emit errors + opts.emitError = true; + // Create a new Server + self.s.mongosState.disconnected(new Server(opts)); + }); + + // Get the disconnected servers + var servers = self.s.mongosState.disconnectedServers(); + + // Set connecting state + this.s.state = CONNECTING; + + // Attempt to connect to all the servers + while(servers.length > 0) { + // Get the server + var server = servers.shift(); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // Set up the event handlers + server.once('error', errorHandlerTemp(self, self.s, server)); + server.once('close', errorHandlerTemp(self, self.s, server)); + server.once('timeout', errorHandlerTemp(self, self.s, server)); + server.once('parseError', errorHandlerTemp(self, self.s, server)); + server.once('connect', connectHandler(self, self.s, 'connect')); + + if(self.s.logger.isInfo()) self.s.logger.info(f('connecting to server %s', server.name)); + // Attempt to connect + server.connect(); + } +} + +/** + * Destroy the server connection + * @method + */ +Mongos.prototype.destroy = function(emitClose) { + this.s.state = DESTROYED; + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + // Destroy the state + this.s.mongosState.destroy(); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.s.mongosState.isConnected(); +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.s.state == DESTROYED; +} + +// +// Operations +// + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'update', ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'remove', ns, ops, options, callback); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + var server = null; + // Ensure we have no options + options = options || {}; + + // We need to execute the command on all servers + if(options.onAll) { + var servers = self.s.mongosState.getAll(); + var count = servers.length; + var cmdErr = null; + + for(var i = 0; i < servers.length; i++) { + servers[i].command(ns, cmd, options, function(err, r) { + count = count - 1; + // Finished executing command + if(count == 0) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // Return the error + callback(err, r); + } + }); + } + + return; + } + + + try { + // Get a primary + server = self.s.mongosState.pickServer(options.writeConcern ? ReadPreference.primary : options.readPreference); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no mongos found")); + server.command(ns, cmd, options, function(err, r) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + callback(err, r); + }); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // Authenticate against all the servers + var servers = this.s.mongosState.connectedServers().slice(0); + var count = servers.length; + // Correct authentication + var authenticated = true; + var authErr = null; + // Set auth in progress + this.s.authInProgress = true; + + // Authenticate against all servers + while(servers.length > 0) { + var server = servers.shift(); + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err, r) { + count = count - 1; + if(err) authErr = err; + if(!r) authenticated = false; + + // We are done + if(count == 0) { + // We have more servers that are not authenticated, let's authenticate + if(self.s.authInProgressServers.length > 0) { + self.s.authInProgressServers = []; + return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); + } + + // Auth is done + self.s.authInProgress = false; + // Add successful credentials + if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); + // Return the auth error + if(authErr) return callback(authErr, false); + // Successfully authenticated session + callback(null, new Session({}, self)); + } + }]); + + // Execute the auth + server.auth.apply(server, finalArguments); + } +} + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +Mongos.prototype.addReadPreferenceStrategy = function(name, strategy) { + if(this.s.readPreferenceStrategies == null) this.s.readPreferenceStrategies = {}; + this.s.readPreferenceStrategies[name] = strategy; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +Mongos.prototype.addAuthProvider = function(name, provider) { + this.s.authProviders[name] = provider; +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +Mongos.prototype.getConnection = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + var server = this.s.mongosState.pickServer(options.readPreference); + if(server == null) return null; + // Return connection + return server.getConnection(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Mongos.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + return this.s.mongosState.pickServer(options.readPreference); +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + return this.s.mongosState.getAllConnections(); +} + +// +// Inquires about state changes +// +var mongosInquirer = function(self, state) { + return function() { + if(state.state == DESTROYED) return + if(state.state == CONNECTED) state.retriesLeft = state.reconnectTries; + + // If we have a disconnected site + if(state.state == DISCONNECTED && state.retriesLeft == 0) { + self.destroy(); + return self.emit('error', new MongoError(f('failed to reconnect after %s', state.reconnectTries))); + } else if(state == DISCONNECTED) { + state.retriesLeft = state.retriesLeft - 1; + } + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(state.mongosState.isConnected() && state.disconnectHandler) { + state.disconnectHandler.execute(); + } + + // Log the information + if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess running')); + + // Let's query any disconnected proxies + var disconnectedServers = state.mongosState.disconnectedServers(); + if(disconnectedServers.length == 0) return setTimeout(mongosInquirer(self, state), state.haInterval); + + // Count of connections waiting to be connected + var connectionCount = disconnectedServers.length; + if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess found %d disconnected proxies', connectionCount)); + + // Let's attempt to reconnect + while(disconnectedServers.length > 0) { + // Connect to proxy + var connectToProxy = function(_server) { + setTimeout(function() { + var events = ['error', 'close', 'timeout', 'connect', 'message', 'parseError']; + // Remove any listeners + events.forEach(function(e) { + _server.removeAllListeners(e); + }); + + // Set up the event handlers + _server.once('error', errorHandlerTemp(self, state, server)); + _server.once('close', errorHandlerTemp(self, state, server)); + _server.once('timeout', errorHandlerTemp(self, state, server)); + _server.once('connect', connectHandler(self, state, 'ha')); + // Start connect + _server.connect(); + }, 1); + } + + var server = disconnectedServers.shift(); + if(state.logger.isDebug()) state.logger.debug(f('attempting to connect to server %s', server.name)); + connectToProxy(server); + } + + // Let's keep monitoring but wait for possible timeout to happen + return setTimeout(mongosInquirer(self, state), state.options.connectionTimeout + state.haInterval); + } +} + +// +// Error handler for initial connect +var errorHandlerTemp = function(self, state, server) { + return function(err, server) { + // Log the information + if(state.logger.isInfo()) state.logger.info(f('server %s disconnected with error %s', server.name, JSON.stringify(err))); + + // Signal disconnect of server + state.mongosState.disconnected(server); + + // Remove any non used handlers + var events = ['error', 'close', 'timeout', 'connect']; + events.forEach(function(e) { + server.removeAllListeners(e); + }) + } +} + +// +// Handlers +var errorHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', server.name, JSON.stringify(err))); + state.mongosState.disconnected(server); + // No more servers left emit close + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + if(state.emitError) self.emit('error', err, server); + } +} + +var timeoutHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s timed out', server.name)); + state.mongosState.disconnected(server); + + // No more servers emit close event if no entries left + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + } +} + +var closeHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s closed', server.name)); + state.mongosState.disconnected(server); + + // No more servers left emit close + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + } +} + +// Connect handler +var connectHandler = function(self, state, e) { + return function(server) { + if(state.logger.isInfo()) state.logger.info(f('connected to %s', server.name)); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // finish processing the server + var processNewServer = function(_server) { + // Add the server handling code + if(_server.isConnected()) { + _server.once('error', errorHandler(self, state)); + _server.once('close', closeHandler(self, state)); + _server.once('timeout', timeoutHandler(self, state)); + _server.once('parseError', timeoutHandler(self, state)); + } + + // Emit joined event + self.emit('joined', 'mongos', _server); + + // Add to list connected servers + state.mongosState.connected(_server); + + // Do we have a reconnect event + if('ha' == e && state.mongosState.connectedServers().length == 1) { + self.emit('reconnect', _server); + } + + // Full setup + if(state.mongosState.disconnectedServers().length == 0 && + state.mongosState.connectedServers().length > 0 && + !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup'); + } + + // all connected + if(state.mongosState.disconnectedServers().length == 0 && + state.mongosState.connectedServers().length == state.seedlist.length && + !state.all) { + state.all = true; + self.emit('all'); + } + + // Set connected + if(state.state == DISCONNECTED) { + state.state = CONNECTED; + self.emit('reconnect', self); + } else if(state.state == CONNECTING) { + state.state = CONNECTED; + self.emit('connect', self); + } + } + + // Is there an authentication process ongoing + if(state.authInProgress) { + state.authInProgressServers.push(server); + } + + // No credentials just process server + if(state.credentials.length == 0) return processNewServer(server); + + // Do we have credentials, let's apply them all + var count = state.credentials.length; + // Apply the credentials + for(var i = 0; i < state.credentials.length; i++) { + server.auth.apply(server, state.credentials[i].concat([function(err, r) { + count = count - 1; + if(count == 0) processNewServer(server); + }])); + } + } +} + +// +// Add server to the list if it does not exist +var addToListIfNotExist = function(list, server) { + var found = false; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Check if the server already exists + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) found = true; + } + + if(!found) { + list.push(server); + } +} + +// Add the new credential for a db, removing the old +// credential from the cache +var addCredentials = function(state, db, argsWithoutCallback) { + // Remove any credentials for the db + clearCredentials(state, db + ".dummy"); + // Add new credentials to list + state.credentials.push(argsWithoutCallback); +} + +// Clear out credentials for a namespace +var clearCredentials = function(state, ns) { + var db = ns.split('.')[0]; + var filteredCredentials = []; + + // Filter out all credentials for the db the user is logging out off + for(var i = 0; i < state.credentials.length; i++) { + if(state.credentials[i][1] != db) filteredCredentials.push(state.credentials[i]); + } + + // Set new list of credentials + state.credentials = filteredCredentials; +} + +var processReadPreference = function(cmd, options) { + options = options || {} + // No read preference specified + if(options.readPreference == null) return cmd; +} + +// +// Execute write operation +var executeWriteOperation = function(state, op, ns, ops, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + var server = null; + // Ensure we have no options + options = options || {}; + try { + // Get a primary + server = state.mongosState.pickServer(); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no mongos found")); + // Execute the command + server[op](ns, ops, options, callback); +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +module.exports = Mongos; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js new file mode 100644 index 0000000..913ca1b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js @@ -0,0 +1,106 @@ +"use strict"; + +var needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * var cursor = server.cursor('db.test' + * , {find: 'db.test', query: {}} + * , {readPreference: new ReadPreference('secondary')}); + * cursor.next(function(err, doc) { + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Pool instance + * @class + * @param {string} preference A string describing the preference (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {object} tags The tags object + * @param {object} [options] Additional read preference options + * @property {string} preference The preference string (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @property {object} tags The tags object + * @property {object} options Additional read preference options + * @return {ReadPreference} + */ +var ReadPreference = function(preference, tags, options) { + this.preference = preference; + this.tags = tags; + this.options = options; +} + +/** + * This needs slaveOk bit set + * @method + * @return {boolean} + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.preference) != -1; +} + +/** + * Are the two read preference equal + * @method + * @return {boolean} + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.preference == this.preference; +} + +/** + * Return JSON representation + * @method + * @return {Object} + */ +ReadPreference.prototype.toJSON = function() { + var readPreference = {mode: this.preference}; + if(Array.isArray(this.tags)) readPreference.tags = this.tags; + return readPreference; +} + +/** + * Primary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js new file mode 100644 index 0000000..5f74546 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js @@ -0,0 +1,1562 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , b = require('bson') + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , debugOptions = require('../connection/utils').debugOptions + , EventEmitter = require('events').EventEmitter + , Server = require('./server') + , ReadPreference = require('./read_preference') + , MongoError = require('../error') + , Ping = require('./strategies/ping') + , Session = require('./session') + , BasicCursor = require('../cursor') + , BSON = require('bson').native().BSON + , State = require('./replset_state') + , MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram') + , Logger = require('../connection/logger'); + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connecctions. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// +// ReplSet instance id +var replSetId = 1; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + // Clone the options + options = cloneOptions(options); + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // Add event listener + EventEmitter.call(this); + + // Set the bson instance + bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; + + // Internal state hash for the object + this.s = { + options: options + // Logger instance + , logger: Logger('ReplSet', options) + // Uniquely identify the replicaset instance + , id: replSetId++ + // Index + , index: 0 + // Ha Index + , haId: 0 + // Current credentials used for auth + , credentials: [] + // Factory overrides + , Cursor: options.cursorFactory || BasicCursor + // BSON Parser, ensure we have a single instance + , bsonInstance: bsonInstance + // Pick the right bson parser + , bson: options.bson ? options.bson : bsonInstance + // Special replicaset options + , secondaryOnlyConnectionAllowed: typeof options.secondaryOnlyConnectionAllowed == 'boolean' + ? options.secondaryOnlyConnectionAllowed : false + , haInterval: options.haInterval || 10000 + // Are we running in debug mode + , debug: typeof options.debug == 'boolean' ? options.debug : false + // The replicaset name + , setName: options.setName + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Grouping tag used for debugging purposes + , tag: options.tag + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + // Currently connecting servers + , connectingServers: {} + // Contains any alternate strategies for picking + , readPreferenceStrategies: {} + // Auth providers + , authProviders: {} + // All the servers + , disconnectedServers: [] + // Initial connection servers + , initialConnectionServers: [] + // High availability process running + , highAvailabilityProcessRunning: false + // Full setup + , fullsetup: false + // All servers accounted for (used for testing) + , all: false + // Seedlist + , seedlist: seedlist + // Authentication in progress + , authInProgress: false + // Servers added while auth in progress + , authInProgressServers: [] + // Minimum heartbeat frequency used if we detect a server close + , minHeartbeatFrequencyMS: 500 + // stores high availability timer to allow efficient destroy + , haTimer : null + } + + // Add bson parser to options + options.bson = this.s.bson; + // Set up the connection timeout for the options + options.connectionTimeout = options.connectionTimeout || 10000; + + // Replicaset state + var replState = new State(this, { + id: this.s.id, setName: this.s.setName + , connectingServers: this.s.connectingServers + , secondaryOnlyConnectionAllowed: this.s.secondaryOnlyConnectionAllowed + }); + + // Add Replicaset state to our internal state + this.s.replState = replState; + + // Add the authentication mechanisms + this.addAuthProvider('mongocr', new MongoCR()); + this.addAuthProvider('x509', new X509()); + this.addAuthProvider('plain', new Plain()); + this.addAuthProvider('gssapi', new GSSAPI()); + this.addAuthProvider('sspi', new SSPI()); + this.addAuthProvider('scram-sha-1', new ScramSHA1()); + + // BSON property (find a server and pass it along) + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + var servers = self.s.replState.getAll(); + return servers.length > 0 ? servers[0].bson : null; + } + }); + + Object.defineProperty(this, 'id', { + enumerable:true, get: function() { return self.s.id; } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.haInterval; } + }); + + Object.defineProperty(this, 'state', { + enumerable:true, get: function() { return self.s.replState; } + }); + + // + // Debug options + if(self.s.debug) { + // Add access to the read Preference Strategies + Object.defineProperty(this, 'readPreferenceStrategies', { + enumerable: true, get: function() { return self.s.readPreferenceStrategies; } + }); + } + + Object.defineProperty(this, 'type', { + enumerable:true, get: function() { return 'replset'; } + }); + + // Add the ping strategy for nearest + this.addReadPreferenceStrategy('nearest', new Ping(options)); +} + +inherits(ReplSet, EventEmitter); + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +ReplSet.prototype.addReadPreferenceStrategy = function(name, func) { + this.s.readPreferenceStrategies[name] = func; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +ReplSet.prototype.addAuthProvider = function(name, provider) { + if(this.s.authProviders == null) this.s.authProviders = {}; + this.s.authProviders[name] = provider; +} + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +ReplSet.prototype.parserType = function() { + if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +ReplSet.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + return this.s.replState.lastIsMaster(); +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +ReplSet.prototype.getConnection = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + var server = pickServer(this, this.s, options.readPreference); + if(server == null) return null; + // Return connection + return server.getConnection(); +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + return this.s.replState.getAllConnections(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +ReplSet.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + return pickServer(this, this.s, options.readPreference); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +// +// Execute write operation +var executeWriteOperation = function(self, op, ns, ops, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + var server = null; + // Ensure we have no options + options = options || {}; + // Get a primary + try { + server = pickServer(self, self.s, ReadPreference.primary); + if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no server found")); + + // Handler + var handler = function(err, r) { + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); + // Return the result + callback(err, r); + } + + // Add operationId if existing + if(callback.operationId) handler.operationId = callback.operationId; + // Execute the command + server[op](ns, ops, options, handler); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + var server = null; + var self = this; + // Ensure we have no options + options = options || {}; + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected(options) && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // We need to execute the command on all servers + if(options.onAll) { + var servers = this.s.replState.getAll(); + var count = servers.length; + var cmdErr = null; + + for(var i = 0; i < servers.length; i++) { + servers[i].command(ns, cmd, options, function(err, r) { + count = count - 1; + // Finished executing command + if(count == 0) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); + // Return the error + callback(err, r); + } + }); + } + + return; + } + + // Pick the right server based on readPreference + try { + server = pickServer(self, self.s, options.writeConcern ? ReadPreference.primary : options.readPreference); + if(self.s.debug) self.emit('pickedServer', options.writeConcern ? ReadPreference.primary : options.readPreference, server); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no server found")); + // Execute the command + server.command(ns, cmd, options, function(err, r) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) { + replicasetInquirer(self, self.s, true)(); + } + // Return the error + callback(err, r); + }); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + executeWriteOperation(this, 'remove', ns, ops, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + executeWriteOperation(this, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + executeWriteOperation(this, 'update', ns, ops, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(mechanism, db) { + // console.log("=========================== REPLSET.auth") + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.s.authProviders[mechanism] == null && mechanism != 'default') { + throw new MongoError(f("auth provider %s does not exist", mechanism)); + } + + // Authenticate against all the servers + var servers = this.s.replState.getAll().slice(0); + var count = servers.length; + // Correct authentication + var authenticated = true; + var authErr = null; + // Set auth in progress + this.s.authInProgress = true; + + // Authenticate against all servers + while(servers.length > 0) { + var server = servers.shift(); + + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err, r) { + count = count - 1; + if(err) authErr = err; + if(!r) authenticated = false; + + // We are done + if(count == 0) { + // We have more servers that are not authenticated, let's authenticate + if(self.s.authInProgressServers.length > 0) { + self.s.authInProgressServers = []; + return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); + } + + // Auth is done + self.s.authInProgress = false; + // Add successful credentials + if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); + // Return the auth error + if(authErr) return callback(authErr, false); + // Successfully authenticated session + callback(null, new Session({}, self)); + } + }]); + + // Execute the auth + server.auth.apply(server, finalArguments); + } +} + +ReplSet.prototype.state = function() { + return this.s.replState.state; +} + +/** + * Ensure single socket connections to arbiters and hidden servers + * @method + */ +var handleIsmaster = function(self) { + return function(ismaster, _server) { + if(ismaster.arbiterOnly) { + _server.s.options.size = 1; + } else if(ismaster.hidden) { + _server.s.options.size = 1; + } + } +} + +/** + * Initiate server connect + * @method + */ +ReplSet.prototype.connect = function(_options) { + var self = this; + // Start replicaset inquiry process + setHaTimer(self, self.s); + // Additional options + if(_options) for(var name in _options) this.s.options[name] = _options[name]; + + // Set the state as connecting + this.s.replState.state = CONNECTING; + + // No fullsetup reached + this.s.fullsetup = false; + + // For all entries in the seedlist build a server instance + this.s.seedlist.forEach(function(e) { + // Clone options + var opts = cloneOptions(self.s.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = self.s.readPreferenceStrategies; + opts.emitError = true; + // Add a reserved connection for monitoring + opts.size = opts.size + 1; + opts.monitoring = true; + // Set up tags if any + if(self.s.tag) opts.tag = self.s.tag; + // Share the auth store + opts.authProviders = self.s.authProviders; + // Create a new Server + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + // Add to list of disconnected servers + self.s.disconnectedServers.push(server); + // Add to list of inflight Connections + self.s.initialConnectionServers.push(server); + }); + + // Attempt to connect to all the servers + while(this.s.disconnectedServers.length > 0) { + // Get the server + var server = self.s.disconnectedServers.shift(); + + // Set up the event handlers + server.once('error', errorHandlerTemp(self, self.s, 'error')); + server.once('close', errorHandlerTemp(self, self.s, 'close')); + server.once('timeout', errorHandlerTemp(self, self.s, 'timeout')); + server.once('connect', connectHandler(self, self.s)); + + // Ensure we schedule the opening of new socket + // on separate ticks of the event loop + var execute = function(_server) { + // Attempt to connect + process.nextTick(function() { + _server.connect(); + }); + } + + execute(server); + } +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + // If we specified a read preference check if we are connected to something + // than can satisfy this + if(options.readPreference + && options.readPreference.equals(ReadPreference.secondary)) + return this.s.replState.isSecondaryConnected(); + + if(options.readPreference + && options.readPreference.equals(ReadPreference.primary)) + return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); + + if(options.readPreference + && options.readPreference.equals(ReadPreference.primaryPreferred)) + return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); + + if(options.readPreference + && options.readPreference.equals(ReadPreference.secondaryPreferred)) + return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); + + if(this.s.secondaryOnlyConnectionAllowed + && this.s.replState.isSecondaryConnected()) return true; + + return this.s.replState.isPrimaryConnected(); +} + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.s.replState.state == DESTROYED; +} + +/** + * Destroy the server connection + * @method + */ +ReplSet.prototype.destroy = function(emitClose) { + var self = this; + if(this.s.logger.isInfo()) this.s.logger.info(f('[%s] destroyed', this.s.id)); + this.s.replState.state = DESTROYED; + + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + + // Destroy state + this.s.replState.destroy(); + + // Clear out any listeners + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); + + clearTimeout(self.s.haTimer); +} + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +// +// Inquires about state changes +// + +// Add the new credential for a db, removing the old +// credential from the cache +var addCredentials = function(s, db, argsWithoutCallback) { + // Remove any credentials for the db + clearCredentials(s, db + ".dummy"); + // Add new credentials to list + s.credentials.push(argsWithoutCallback); +} + +// Clear out credentials for a namespace +var clearCredentials = function(s, ns) { + var db = ns.split('.')[0]; + var filteredCredentials = []; + + // Filter out all credentials for the db the user is logging out off + for(var i = 0; i < s.credentials.length; i++) { + if(s.credentials[i][1] != db) filteredCredentials.push(s.credentials[i]); + } + + // Set new list of credentials + s.credentials = filteredCredentials; +} + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tagsArray = !Array.isArray(readPreference.tags) ? [tags] : tags; + + // Iterate over the tags + for(var j = 0; j < tagsArray.length; j++) { + var tags = tagsArray[j]; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) found = false; + } + + // Add to candidate list + if(found) { + filteredServers.push(servers[i]); + } + } + + // We found servers by the highest priority + if(found) break; + } + + // Returned filtered servers + return filteredServers; +} + +// +// Pick a server based on readPreference +var pickServer = function(self, s, readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // Do we have a custom readPreference strategy, use it + if(s.readPreferenceStrategies != null && s.readPreferenceStrategies[readPreference.preference] != null) { + if(s.readPreferenceStrategies[readPreference.preference] == null) throw new MongoError(f("cannot locate read preference handler for %s", readPreference.preference)); + var server = s.readPreferenceStrategies[readPreference.preference].pickServer(s.replState, readPreference); + if(s.debug) self.emit('pickedServer', readPreference, server); + return server; + } + + // Filter out any hidden secondaries + var secondaries = s.replState.secondaries.filter(function(server) { + if(server.lastIsMaster().hidden) return false; + return true; + }); + + // Check if we can satisfy and of the basic read Preferences + if(readPreference.equals(ReadPreference.secondary) + && secondaries.length == 0) + throw new MongoError("no secondary server available"); + + if(readPreference.equals(ReadPreference.secondaryPreferred) + && secondaries.length == 0 + && s.replState.primary == null) + throw new MongoError("no secondary or primary server available"); + + if(readPreference.equals(ReadPreference.primary) + && s.replState.primary == null) + throw new MongoError("no primary server available"); + + // Secondary + if(readPreference.equals(ReadPreference.secondary)) { + s.index = (s.index + 1) % secondaries.length; + return secondaries[s.index]; + } + + // Secondary preferred + if(readPreference.equals(ReadPreference.secondaryPreferred)) { + if(secondaries.length > 0) { + // Apply tags if present + var servers = filterByTags(readPreference, secondaries); + // If have a matching server pick one otherwise fall through to primary + if(servers.length > 0) { + s.index = (s.index + 1) % servers.length; + return servers[s.index]; + } + } + + return s.replState.primary; + } + + // Primary preferred + if(readPreference.equals(ReadPreference.primaryPreferred)) { + if(s.replState.primary) return s.replState.primary; + + if(secondaries.length > 0) { + // Apply tags if present + var servers = filterByTags(readPreference, secondaries); + // If have a matching server pick one otherwise fall through to primary + if(servers.length > 0) { + s.index = (s.index + 1) % servers.length; + return servers[s.index]; + } + + // Throw error a we have not valid secondary or primary servers + throw new MongoError("no secondary or primary server available"); + } + } + + // Return the primary + return s.replState.primary; +} + +var setHaTimer = function(self, state) { + // all haTimers are set to to repeat, so we pass norepeat false + self.s.haTimer = setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return self.s.haTimer; +} + +var haveAvailableServers = function(state) { + // console.log("!---------------------------------------------------------------") + // console.dir("state.disconnectedServers.length = " + state.disconnectedServers.length) + // console.dir("state.replState.secondaries.length = " + state.replState.secondaries.length) + // console.dir("state.replState.arbiters.length = " + state.replState.arbiters.length) + // console.dir("state.replState.primary = " + (state.replState.primary != null)) + if(state.disconnectedServers.length == 0 + && state.replState.secondaries.length == 0 + && state.replState.arbiters.length == 0 + && state.replState.primary == null) return false; + return true; +} + +var replicasetInquirer = function(self, state, norepeat) { + return function() { + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer :: " + state.replState.state) + if(state.replState.state == DESTROYED) return + // We have no connections we need to reseed the disconnected list + if(!haveAvailableServers(state)) { + // console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ replicasetInquirer 0") + // For all entries in the seedlist build a server instance + state.disconnectedServers = state.seedlist.map(function(e) { + // Clone options + var opts = cloneOptions(state.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = state.readPreferenceStrategies; + opts.emitError = true; + // Add a reserved connection for monitoring + opts.size = opts.size + 1; + opts.monitoring = true; + // Set up tags if any + if(state.tag) opts.tag = stage.tag; + // Share the auth store + opts.authProviders = state.authProviders; + // Create a new Server + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + return server; + }); + } + + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 2") + + // Process already running don't rerun + if(state.highAvailabilityProcessRunning) return; + // Started processes + state.highAvailabilityProcessRunning = true; + if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring process running %s', state.id, JSON.stringify(state.replState))); + + // Unique HA id to identify the current look running + var localHaId = state.haId++; + + // Clean out any failed connection attempts + state.connectingServers = {}; + + // Controls if we are doing a single inquiry or repeating + norepeat = typeof norepeat == 'boolean' ? norepeat : false; + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(state.replState.isPrimaryConnected() && state.replState.isSecondaryConnected() && state.disconnectHandler) { + state.disconnectHandler.execute(); + } + + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 3") + + // Emit replicasetInquirer + self.emit('ha', 'start', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + + // Let's process all the disconnected servers + while(state.disconnectedServers.length > 0) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!! ATTEMPT TO RECONNECT") + // Get the first disconnected server + var server = state.disconnectedServers.shift(); + if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring attempting to connect to %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, 'error')); + server.once('close', errorHandlerTemp(self, state, 'close')); + server.once('timeout', errorHandlerTemp(self, state, 'timeout')); + server.once('connect', connectHandler(self, state)); + + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! SERVER") + // console.log("&&&&&&&&&&&&&&&&&&&&& reconnect to server :: " + server.name) + // console.dir(server.s.options) + + // Ensure we schedule the opening of new socket + // on separate ticks of the event loop + var execute = function(_server) { + // Attempt to connect + process.nextTick(function() { + _server.connect(); + }); + } + + execute(server); + } + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 4") + + // Cleanup state (removed disconnected servers) + state.replState.clean(); + + // We need to query all servers + var servers = state.replState.getAll({includeArbiters:true}); + var serversLeft = servers.length; + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 5 :: " + serversLeft) + + // If no servers and we are not destroyed keep pinging + if(servers.length == 0 && state.replState.state == CONNECTED) { + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 6:1") + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 6:2") + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 6:3 :: " + norepeat) + // Restart ha process + if(!norepeat) setHaTimer(self, state); + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 6:4") + return; + } + + // + // ismaster for Master server + var primaryIsMaster = null; + + // Kill the server connection if it hangs + var timeoutServer = function(_server) { + return setTimeout(function() { + if(_server.isConnected()) { + _server.connections()[0].connection.destroy(); + } + }, self.s.options.connectionTimeout); + } + + // + // Inspect a specific servers ismaster + var inspectServer = function(server) { + if(state.replState.state == DESTROYED) return; + // Did we get a server + if(server && server.isConnected()) { + // Get the timeout id + var timeoutId = timeoutServer(server); + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 1:1") + // Execute ismaster + server.command('admin.$cmd', { ismaster:true }, { monitoring:true }, function(err, r) { + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 1:2") + // console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ replicasetInquirer :: " + new Date().getTime()) + // if(r)console.dir(r.result) + // Clear out the timeoutServer + clearTimeout(timeoutId); + + // If the state was destroyed + if(state.replState.state == DESTROYED) return; + + // Count down the number of servers left + serversLeft = serversLeft - 1; + + // If we have an error but still outstanding server request return + if(err && serversLeft > 0) return; + + // We had an error and have no more servers to inspect, schedule a new check + if(err && serversLeft == 0) { + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunnfing + state.highAvailabilityProcessRunning = false; + // Return the replicasetInquirer + if(!norepeat) setHaTimer(self, state); + return; + } + + // Let all the read Preferences do things to the servers + var rPreferencesCount = Object.keys(state.readPreferenceStrategies).length; + + // Handle the primary + var ismaster = r.result; + if(state.logger.isDebug()) state.logger.debug(f('[%s] monitoring process ismaster %s', state.id, JSON.stringify(ismaster))); + + // Update the replicaset state + state.replState.update(ismaster, server); + + // + // Process hosts list from ismaster under two conditions + // 1. Ismaster result is from primary + // 2. There is no primary and the ismaster result is from a non-primary + if(err == null + && (ismaster.ismaster || (!state.primary)) + && Array.isArray(ismaster.hosts)) { + // Hosts to process + var hosts = ismaster.hosts; + // Add arbiters to list of hosts if we have any + if(Array.isArray(ismaster.arbiters)) { + hosts = hosts.concat(ismaster.arbiters.map(function(x) { + return {host: x, arbiter:true}; + })); + } + + if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); + // Process all the hsots + processHosts(self, state, hosts); + } else if(err == null && !Array.isArray(ismaster.hosts)) { + server.destroy(); + } + + // No read Preferences strategies + if(rPreferencesCount == 0) { + // Don't schedule a new inquiry + if(serversLeft > 0) return; + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Let's keep monitoring + if(!norepeat) setHaTimer(self, state); + return; + } + + // No servers left to query, execute read preference strategies + if(serversLeft == 0) { + // Go over all the read preferences + for(var name in state.readPreferenceStrategies) { + state.readPreferenceStrategies[name].ha(self, state.replState, function() { + rPreferencesCount = rPreferencesCount - 1; + + if(rPreferencesCount == 0) { + // Add any new servers in primary ismaster + if(err == null + && ismaster.ismaster + && Array.isArray(ismaster.hosts)) { + processHosts(self, state, ismaster.hosts); + } + + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Let's keep monitoring + if(!norepeat) setHaTimer(self, state); + return; + } + }); + } + } + }); + } + } + + // Call ismaster on all servers + for(var i = 0; i < servers.length; i++) { + inspectServer(servers[i]); + } + + // If no more initial servers and new scheduled servers to connect + if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup', self); + } + + // If all servers are accounted for and we have not sent the all event + if(state.replState.primary != null && self.lastIsMaster() + && Array.isArray(self.lastIsMaster().hosts) && !state.all) { + var length = 1 + state.replState.secondaries.length; + // If we have all secondaries + primary + if(length == self.lastIsMaster().hosts.length + 1) { + state.all = true; + self.emit('all', self); + } + } + } +} + +// Error handler for initial connect +var errorHandlerTemp = function(self, state, event) { + return function(err, server) { + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET") + // console.dir(err) + // Log the information + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s disconnected', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + // Filter out any connection servers + state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { + return server.name != _server.name; + }); + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET 1") + + // Connection is destroyed, ignore + if(state.replState.state == DESTROYED) return; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET 2") + + // Push to list of disconnected servers + addToListIfNotExist(state.disconnectedServers, server); + + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET 3") + + // End connection operation if we have no legal replicaset state + if(state.initialConnectionServers == 0 && state.replState.state == CONNECTING) { + if((state.secondaryOnlyConnectionAllowed && !state.replState.isSecondaryConnected() && !state.replState.isPrimaryConnected()) + || (!state.secondaryOnlyConnectionAllowed && !state.replState.isPrimaryConnected())) { + // console.log("----- REPLSET 0") + if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); + + if(self.listeners('error').length > 0) { + // console.log("----- REPLSET 1") + return self.emit('error', new MongoError('no valid seed servers in list')); + } + } + } + + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET 4") + + // If the number of disconnected servers is equal to + // the number of seed servers we cannot connect + if(state.disconnectedServers.length == state.seedlist.length && state.replState.state == CONNECTING) { + if(state.emitError && self.listeners('error').length > 0) { + // console.log("----- REPLSET 2") + if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); + + if(self.listeners('error').length > 0) { + // console.log("----- REPLSET 3") + self.emit('error', new MongoError('no valid seed servers in list')); + } + } + } + + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET 5") + } +} +// TODO with arbiter +// - if connected to an arbiter, shut down all but single server connection + +// Connect handler +var connectHandler = function(self, state) { + return function(server) { + // console.log(" --------------------------- connectHandler 0") + // console.log("SERVER CONNECTED") + if(state.logger.isInfo()) state.logger.info(f('[%s] connected to %s', state.id, server.name)); + // Destroyed connection + if(state.replState.state == DESTROYED) { + server.destroy(false, false); + return; + } + + // Filter out any connection servers + state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { + return server.name != _server.name; + }); + + // Process the new server + var processNewServer = function() { + // Discover any additional servers + var ismaster = server.lastIsMaster(); + + // Are we an arbiter, restrict number of connections to + // one single connection + if(ismaster.arbiterOnly) { + server.capConnections(1); + } + + // Deal with events + var events = ['error', 'close', 'timeout', 'connect', 'message']; + // Remove any non used handlers + events.forEach(function(e) { + server.removeAllListeners(e); + }) + + // Clean up + delete state.connectingServers[server.name]; + // Update the replicaset state, destroy if not added + if(!state.replState.update(ismaster, server)) { + // Destroy the server instance + server.destroy(); + // No more candiate servers + if(state.state == CONNECTING && state.initialConnectionServers.length == 0 + && state.replState.primary == null && state.replState.secondaries.length == 0) { + return self.emit('error', new MongoError("no replicaset members found in seedlist")); + } + + return; + } + + // Add the server handling code + if(server.isConnected()) { + server.on('error', errorHandler(self, state)); + server.on('close', closeHandler(self, state)); + server.on('timeout', timeoutHandler(self, state)); + } + + // Hosts to process + var hosts = ismaster.hosts; + // Add arbiters to list of hosts if we have any + if(Array.isArray(ismaster.arbiters)) { + hosts = hosts.concat(ismaster.arbiters.map(function(x) { + return {host: x, arbiter:true}; + })); + } + + if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); + + // Add any new servers + processHosts(self, state, hosts); + + // If have the server instance already destroy it + if(state.initialConnectionServers.length == 0 && Object.keys(state.connectingServers).length == 0 + && !state.replState.isPrimaryConnected() && !state.secondaryOnlyConnectionAllowed && state.replState.state == CONNECTING) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no primary found in replicaset', state.id)); + self.emit('error', new MongoError("no primary found in replicaset")); + return self.destroy(); + } + + // If no more initial servers and new scheduled servers to connect + if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup', self); + } + } + + // console.log(" --------------------------- connectHandler 1 :: " + self.s.authInProgress) + // Save up new members to be authenticated against + if(self.s.authInProgress) { + self.s.authInProgressServers.push(server); + } + + // console.log(" --------------------------- connectHandler 2") + + // No credentials just process server + if(state.credentials.length == 0) return processNewServer(); + // Do we have credentials, let's apply them all + var count = state.credentials.length; + // console.log(" --------------------------- connectHandler 3 :: " + count) + // Apply the credentials + for(var i = 0; i < state.credentials.length; i++) { + server.auth.apply(server, state.credentials[i].concat([function(err, r) { + count = count - 1; + if(count == 0) { + // console.log(" --------------------------- connectHandler 4") + processNewServer(); + } + }])); + } + } +} + +// +// Detect if we need to add new servers +var processHosts = function(self, state, hosts) { + if(state.replState.state == DESTROYED) return; + if(Array.isArray(hosts)) { + // Check any hosts exposed by ismaster + for(var i = 0; i < hosts.length; i++) { + // Get the object + var host = hosts[i]; + var options = {}; + + // Do we have an arbiter + if(typeof host == 'object') { + host = host.host; + options.arbiter = host.arbiter; + } + + // If not found we need to create a new connection + if(!state.replState.contains(host)) { + if(state.connectingServers[host] == null && !inInitialConnectingServers(self, state, host)) { + if(state.logger.isInfo()) state.logger.info(f('[%s] scheduled server %s for connection', state.id, host)); + // Make sure we know what is trying to connect + state.connectingServers[host] = host; + // Connect the server + connectToServer(self, state, host.split(':')[0], parseInt(host.split(':')[1], 10), options); + } + } + } + } +} + +var inInitialConnectingServers = function(self, state, address) { + for(var i = 0; i < state.initialConnectionServers.length; i++) { + if(state.initialConnectionServers[i].name == address) return true; + } + return false; +} + +// Connect to a new server +var connectToServer = function(self, state, host, port, options) { + options = options || {}; + var opts = cloneOptions(state.options); + opts.host = host; + opts.port = port; + opts.reconnect = false; + opts.readPreferenceStrategies = state.readPreferenceStrategies; + if(state.tag) opts.tag = state.tag; + // Share the auth store + opts.authProviders = state.authProviders; + opts.emitError = true; + // Set the size to size + 1 and mark monitoring + opts.size = opts.size + 1; + opts.monitoring = true; + + // Do we have an arbiter set the poolSize to 1 + if(options.arbiter) { + opts.size = 1; + } + + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Server :: connectToServer :: " + opts.port) + + // Create a new server instance + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, 'error')); + server.once('close', errorHandlerTemp(self, state, 'close')); + server.once('timeout', errorHandlerTemp(self, state, 'timeout')); + server.once('connect', connectHandler(self, state)); + + // Attempt to connect + process.nextTick(function() { + server.connect(); + }); +} + +// +// Add server to the list if it does not exist +var addToListIfNotExist = function(list, server) { + var found = false; + // If the server is a null value return false + if(server == null) return found; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Check if the server already exists + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) found = true; + } + + if(!found) { + list.push(server); + } + + return found; +} + +var errorHandler = function(self, state) { + return function(err, server) { + // console.log("!!!!!!!!!!!!!!!!!!!!! err handler REPLSET") + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s errored out with %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name, JSON.stringify(err))); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + if(found && state.emitError && self.listeners('error').length > 0) self.emit('error', err, server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + // replicasetInquirer(self, self.s, true)(); + replicasetInquirer(self, self.s, self.s.highAvailabilityProcessRunning)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +var timeoutHandler = function(self, state) { + return function(err, server) { + // console.log("!!!!!!!!!!!!!!!!!!!!! timeout handler REPLSET") + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s timed out', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + // replicasetInquirer(self, self.s, true)(); + replicasetInquirer(self, self.s, self.s.highAvailabilityProcessRunning)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +var closeHandler = function(self, state) { + return function(err, server) { + // console.log("!!!!!!!!!!!!!!!!!!!!! close handler REPLSET") + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s closed', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) { + self.emit('left', state.replState.remove(server), server); + } + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + // replicasetInquirer(self, self.s, true)(); + replicasetInquirer(self, self.s, self.s.highAvailabilityProcessRunning)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +// +// Validate if a non-master or recovering error +var notMasterError = function(r) { + // Get result of any + var result = r && r.result ? r.result : r; + + // Explore if we have a not master error + if(result && (result.err == 'not master' + || result.errmsg == 'not master' || (result['$err'] && result['$err'].indexOf('not master or secondary') != -1) + || (result['$err'] && result['$err'].indexOf("not master and slaveOk=false") != -1) + || result.errmsg == 'node is recovering')) { + return true; + } + + return false; +} + +module.exports = ReplSet; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js new file mode 100644 index 0000000..f47b1e7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js @@ -0,0 +1,506 @@ +"use strict"; + +var Logger = require('../connection/logger') + , f = require('util').format + , ObjectId = require('bson').ObjectId + , MongoError = require('../error'); + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +/** + * Creates a new Replicaset State object + * @class + * @property {object} primary Primary property + * @property {array} secondaries List of secondaries + * @property {array} arbiters List of arbiters + * @return {State} A cursor instance + */ +var State = function(replSet, options) { + this.replSet = replSet; + this.options = options; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.primary = null; + // Initial state is disconnected + this.state = DISCONNECTED; + // Current electionId + this.electionId = null; + // Get a logger instance + this.logger = Logger('ReplSet', options); + // Unpacked options + this.id = options.id; + this.setName = options.setName; + this.connectingServers = options.connectingServers; + this.secondaryOnlyConnectionAllowed = options.secondaryOnlyConnectionAllowed; +} + +/** + * Is there a secondary connected + * @method + * @return {boolean} + */ +State.prototype.isSecondaryConnected = function() { + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].isConnected()) return true; + } + + return false; +} + +/** + * Is there a primary connection + * @method + * @return {boolean} + */ +State.prototype.isPrimaryConnected = function() { + return this.primary != null && this.primary.isConnected(); +} + +/** + * Is the given address the primary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isPrimary = function(address) { + if(this.primary == null) return false; + return this.primary && this.primary.equals(address); +} + +/** + * Is the given address a secondary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isSecondary = function(address) { + // Check if the server is a secondary at the moment + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].equals(address)) { + return true; + } + } + + return false; +} + +/** + * Is the given address a secondary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isPassive = function(address) { + // Check if the server is a secondary at the moment + for(var i = 0; i < this.passives.length; i++) { + if(this.passives[i].equals(address)) { + return true; + } + } + + return false; +} + +/** + * Does the replicaset contain this server + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.contains = function(address) { + if(this.primary && this.primary.equals(address)) return true; + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].equals(address)) return true; + } + + for(var i = 0; i < this.arbiters.length; i++) { + if(this.arbiters[i].equals(address)) return true; + } + + for(var i = 0; i < this.passives.length; i++) { + if(this.passives[i].equals(address)) return true; + } + + return false; +} + +/** + * Clean out all dead connections + * @method + */ +State.prototype.clean = function() { + if(this.primary != null && !this.primary.isConnected()) { + this.primary = null; + } + + // Filter out disconnected servers + this.secondaries = this.secondaries.filter(function(s) { + return s.isConnected(); + }); + + // Filter out disconnected servers + this.arbiters = this.arbiters.filter(function(s) { + return s.isConnected(); + }); +} + +/** + * Destroy state + * @method + */ +State.prototype.destroy = function() { + this.state = DESTROYED; + if(this.primary) this.primary.destroy(); + this.secondaries.forEach(function(s) { + s.destroy(); + }); + this.arbiters.forEach(function(s) { + s.destroy(); + }); +} + +/** + * Remove server from state + * @method + * @param {Server} Server to remove + * @return {string} Returns type of server removed (primary|secondary) + */ +State.prototype.remove = function(server) { + if(this.primary && this.primary.equals(server)) { + this.primary = null; + } + + var length = this.arbiters.length; + // Filter out the server from the arbiters + this.arbiters = this.arbiters.filter(function(s) { + return !s.equals(server); + }); + if(this.arbiters.length < length) return 'arbiter'; + + var length = this.passives.length; + // Filter out the server from the passives + this.passives = this.passives.filter(function(s) { + return !s.equals(server); + }); + + // We have removed a passive + if(this.passives.length < length) { + // Ensure we removed it from the list of secondaries as well if it exists + this.secondaries = this.secondaries.filter(function(s) { + return !s.equals(server); + }); + } + + // Filter out the server from the secondaries + this.secondaries = this.secondaries.filter(function(s) { + return !s.equals(server); + }); + + // Get the isMaster + var isMaster = server.lastIsMaster(); + // Return primary if the server was primary + if(isMaster.ismaster && isMaster.hosts) return 'primary'; + if(isMaster.ismaster) return 'secondary'; + if(isMaster.secondary) return 'secondary'; + if(isMaster.passive) return 'passive'; + return 'arbiter'; +} + +/** + * Get the server by name + * @method + * @param {string} address Server address + * @return {Server} + */ +State.prototype.get = function(server) { + var found = false; + // All servers to search + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + // Locate the server + for(var i = 0; i < servers.length; i++) { + if(servers[i].equals(server)) { + return servers[i]; + } + } +} + +/** + * Get all the servers in the set + * @method + * @param {boolean} [options.includeArbiters] Include Arbiters in returned server list + * @return {array} + */ +State.prototype.getAll = function(options) { + options = options || {}; + var servers = []; + if(this.primary) servers.push(this.primary); + servers = servers.concat(this.secondaries); + + // Include the arbiters + if(options.includeArbiters) { + servers = servers.concat(this.arbiters); + } + + // return ; + return servers; +} + +/** + * All raw connections + * @method + * @param {boolean} [options.includeArbiters] Include Arbiters in returned server list + * @return {array} + */ +State.prototype.getAllConnections = function(options) { + options = options || {}; + var connections = []; + if(this.primary) connections = connections.concat(this.primary.connections()); + this.secondaries.forEach(function(s) { + connections = connections.concat(s.connections()); + }) + + // Include the arbiters + if(options.includeArbiters) { + this.arbiters.forEach(function(s) { + connections = connections.concat(s.connections()); + }) + } + + return connections; +} + +/** + * Return JSON object + * @method + * @return {object} + */ +State.prototype.toJSON = function() { + return { + primary: this.primary ? this.primary.lastIsMaster().me : null + , secondaries: this.secondaries.map(function(s) { + return s.lastIsMaster().me + }) + } +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +State.prototype.lastIsMaster = function() { + if(this.primary) return this.primary.lastIsMaster(); + if(this.secondaries.length > 0) return this.secondaries[0].lastIsMaster(); + return {}; +} + +/** + * Promote server to primary + * @method + * @param {Server} server Server we wish to promote + */ +State.prototype.promotePrimary = function(server) { + var currentServer = this.get(server); + // Server does not exist in the state, add it as new primary + if(currentServer == null) { + this.primary = server; + return; + } + + // We found a server, make it primary and remove it from the secondaries + // Remove the server first + this.remove(currentServer); + // Set as primary + this.primary = currentServer; +} + +var add = function(list, server) { + // Check if the server is a secondary at the moment + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) return false; + } + + list.push(server); + return true; +} + +/** + * Add server to list of secondaries + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addSecondary = function(server) { + return add(this.secondaries, server); +} + +/** + * Add server to list of arbiters + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addArbiter = function(server) { + return add(this.arbiters, server); +} + +/** + * Add server to list of passives + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addPassive = function(server) { + return add(this.passives, server); +} + +var compareObjectIds = function(id1, id2) { + var a = new Buffer(id1.toHexString(), 'hex'); + var b = new Buffer(id2.toHexString(), 'hex'); + + if(a === b) { + return 0; + } + + if(typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +/** + * Update the state given a specific ismaster result + * @method + * @param {object} ismaster IsMaster result + * @param {Server} server IsMaster Server source + */ +State.prototype.update = function(ismaster, server) { + var self = this; + // Not in a known connection valid state + if((!ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) || !Array.isArray(ismaster.hosts)) { + // Remove the state + var result = self.remove(server); + if(self.state == CONNECTED) { + if(self.logger.isInfo()) self.logger.info(f('[%s] removing %s from set', self.id, ismaster.me)); + self.replSet.emit('left', self.remove(server), server); + } + + return false; + } + + // Set the setName if it's not set from the first server + if(self.setName == null && ismaster.setName) { + if(self.logger.isInfo()) self.logger.info(f('[%s] setting setName to %s', self.id, ismaster.setName)); + self.setName = ismaster.setName; + } + + // Check if the replicaset name matches the provided one + if(ismaster.setName && self.setName != ismaster.setName) { + if(self.logger.isError()) self.logger.error(f('[%s] server in replset %s is not part of the specified setName %s', self.id, ismaster.setName, self.setName)); + self.remove(server); + self.replSet.emit('error', new MongoError("provided setName for Replicaset Connection does not match setName found in server seedlist")); + return false; + } + + // Log information + if(self.logger.isInfo()) self.logger.info(f('[%s] updating replicaset state %s', self.id, JSON.stringify(this))); + + // It's a master set it + if(ismaster.ismaster && self.setName == ismaster.setName && !self.isPrimary(ismaster.me)) { + // Check if the electionId is not null + if(ismaster.electionId instanceof ObjectId && self.electionId instanceof ObjectId) { + if(compareObjectIds(self.electionId, ismaster.electionId) == -1) { + self.electionId = ismaster.electionId; + } else if(compareObjectIds(self.electionId, ismaster.electionId) == 0) { + self.electionId = ismaster.electionId; + } else { + return false; + } + } + + // Initial electionId + if(ismaster.electionId instanceof ObjectId && self.electionId == null) { + self.electionId = ismaster.electionId; + } + + // Promote to primary + self.promotePrimary(server); + // Log change of primary + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to primary', self.id, ismaster.me)); + // Emit primary + self.replSet.emit('joined', 'primary', this.primary); + + // We are connected + if(self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } else { + self.state = CONNECTED; + self.replSet.emit('reconnect', server); + } + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.arbiterOnly) { + if(self.addArbiter(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to arbiter', self.id, ismaster.me)); + self.replSet.emit('joined', 'arbiter', server); + return true; + }; + + return false; + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.secondary && ismaster.passive) { + if(self.addPassive(server) && self.addSecondary(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to passive', self.id, ismaster.me)); + self.replSet.emit('joined', 'passive', server); + + // If we have secondaryOnlyConnectionAllowed and just a passive it's + // still a valid connection + if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } + + return true; + }; + + return false; + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.secondary) { + if(self.addSecondary(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to secondary', self.id, ismaster.me)); + self.replSet.emit('joined', 'secondary', server); + + if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } + + return true; + }; + + return false; + } + + // Return update applied + return true; +} + +module.exports = State; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js new file mode 100644 index 0000000..65490f9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js @@ -0,0 +1,1371 @@ + "use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , EventEmitter = require('events').EventEmitter + , Pool = require('../connection/pool') + , b = require('bson') + , crypto = require('crypto') + , Query = require('../connection/commands').Query + , MongoError = require('../error') + , ReadPreference = require('./read_preference') + , BasicCursor = require('../cursor') + , CommandResult = require('./command_result') + , getSingleProperty = require('../connection/utils').getSingleProperty + , getProperty = require('../connection/utils').getProperty + , debugOptions = require('../connection/utils').debugOptions + , BSON = require('bson').native().BSON + , PreTwoSixWireProtocolSupport = require('../wireprotocol/2_4_support') + , TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support') + , ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support') + , Session = require('./session') + , Logger = require('../connection/logger') + , MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram'); + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; +// Server instance id +var serverId = 0; +// Callbacks instance id +var callbackId = 0; + +// Single store for all callbacks +var Callbacks = function() { + // EventEmitter.call(this); + var self = this; + // Callbacks + this.callbacks = {}; + // Set the callbacks id + this.id = callbackId++; + // Set the type to server + this.type = 'server'; +} + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +// +// Flush all callbacks +Callbacks.prototype.flush = function(err) { + for(var id in this.callbacks) { + if(!isNaN(parseInt(id, 10))) { + var callback = this.callbacks[id]; + delete this.callbacks[id]; + callback(err, null); + } + } +} + +// +// Flush all callbacks +Callbacks.prototype.flushConnection = function(err, connection) { + for(var id in this.callbacks) { + if(!isNaN(parseInt(id, 10))) { + var callback = this.callbacks[id]; + + // Validate if the operation ran on the connection + if(callback.connection === connection) { + delete this.callbacks[id]; + callback(err, null); + } + } + } +} + +Callbacks.prototype.callback = function(id) { + return this.callbacks[id]; +} + +Callbacks.prototype.emit = function(id, err, value) { + var callback = this.callbacks[id]; + delete this.callbacks[id]; + callback(err, value); +} + +Callbacks.prototype.raw = function(id) { + if(this.callbacks[id] == null) return false; + return this.callbacks[id].raw == true ? true : false +} + +Callbacks.prototype.documentsReturnedIn = function(id) { + if(this.callbacks[id] == null) return false; + return typeof this.callbacks[id].documentsReturnedIn == 'string' ? this.callbacks[id].documentsReturnedIn : null; +} + +Callbacks.prototype.unregister = function(id) { + delete this.callbacks[id]; +} + +Callbacks.prototype.register = function(id, callback) { + this.callbacks[id] = bindToCurrentDomain(callback); +} + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// Supports server +var supportsServer = function(_s) { + return _s.ismaster && typeof _s.ismaster.minWireVersion == 'number'; +} + +// +// createWireProtocolHandler +var createWireProtocolHandler = function(result) { + // 3.2 wire protocol handler + if(result && result.maxWireVersion >= 4) { + return new ThreeTwoWireProtocolSupport(new TwoSixWireProtocolSupport()); + } + + // 2.6 wire protocol handler + if(result && result.maxWireVersion >= 2) { + return new TwoSixWireProtocolSupport(); + } + + // 2.4 or earlier wire protocol handler + return new PreTwoSixWireProtocolSupport(); +} + +// +// Reconnect server +var reconnectServer = function(self, state) { + // Flush out any left over callbacks + if(self && state && state.callbacks) { + state.callbacks.flush(new MongoError(f("server %s received a broken socket pipe error", self.name))); + } + + // If the current reconnect retries is 0 stop attempting to reconnect + if(state.currentReconnectRetry == 0) { + return self.destroy(true, true); + } + + // Adjust the number of retries + state.currentReconnectRetry = state.currentReconnectRetry - 1; + + // Set status to connecting + state.state = CONNECTING; + // Create a new Pool + state.pool = new Pool(state.options); + // error handler + var reconnectErrorHandler = function(err) { + // Set the state to disconnected so we can peform a proper reconnect + state.state = DISCONNECTED; + // Destroy the pool + state.pool.destroy(); + // Adjust the number of retries + state.currentReconnectRetry = state.currentReconnectRetry - 1; + // No more retries + if(state.currentReconnectRetry <= 0) { + self.state = DESTROYED; + self.emit('error', f('failed to connect to %s:%s after %s retries', state.options.host, state.options.port, state.reconnectTries)); + } else { + setTimeout(function() { + reconnectServer(self, state); + }, state.reconnectInterval); + } + } + + // + // Attempt to connect + state.pool.once('connect', function() { + // Reset retries + state.currentReconnectRetry = state.reconnectTries; + + // Remove any non used handlers + var events = ['error', 'close', 'timeout', 'parseError']; + events.forEach(function(e) { + state.pool.removeAllListeners(e); + }); + + // Set connected state + state.state = CONNECTED; + + // Add proper handlers + state.pool.once('error', reconnectErrorHandler); + state.pool.once('close', closeHandler(self, state)); + state.pool.once('timeout', timeoutHandler(self, state)); + state.pool.once('parseError', fatalErrorHandler(self, state)); + + // We need to ensure we have re-authenticated + var keys = Object.keys(state.authProviders); + if(keys.length == 0) return self.emit('reconnect', self); + + // Get all connections + var connections = state.pool.getAll(); + // Execute all providers + var count = keys.length; + // Iterate over keys + for(var i = 0; i < keys.length; i++) { + state.authProviders[keys[i]].reauthenticate(self, connections, function(err, r) { + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + return self.emit('reconnect', self); + } + }); + } + }); + + // + // Handle connection failure + state.pool.once('error', errorHandler(self, state)); + state.pool.once('close', errorHandler(self, state)); + state.pool.once('timeout', errorHandler(self, state)); + state.pool.once('parseError', errorHandler(self, state)); + + // Connect pool + state.pool.connect(); +} + +// +// Handlers +var messageHandler = function(self, state) { + return function(response, connection) { + // console.log("!----------------------- messageHandler " + self.s.pool.availableConnections.length + " :: " + connection.id) + // Release the connection back to the pool + // self.s.pool.connectionAvailable(connection); + + // Attempt to parse the message + try { + // Parse the message + response.parse({raw: state.callbacks.raw(response.responseTo), documentsReturnedIn: state.callbacks.documentsReturnedIn(response.responseTo)}); + + // Get the callback + var cb = state.callbacks.callback(response.responseTo); + + // console.dir(Object.keys(cb)) + // console.dir(response.documents) + + // If no + if(!cb.noRelease) { + self.s.pool.connectionAvailable(connection); + } + + // Log if debug enabled + if(state.logger.isDebug()) state.logger.debug(f('message [%s] received from %s', response.raw.toString('hex'), self.name)); + // Execute the registered callback + state.callbacks.emit(response.responseTo, null, response); + } catch (err) { + state.callbacks.flush(new MongoError(err)); + self.destroy(); + } + } +} + +var errorHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% errorHandler") + // console.log(err) + // Flush the connection operations + if(self.s.callbacks) { + self.s.callbacks.flushConnection(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err))), connection); + } + + // Emit error event + if(state.emitError && self.listeners('error').length > 0) self.emit('error', err, self); + + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% errorHandler 1") + // No more connections left, emit a close + if(state.pool.getAll().length == 0) { + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% errorHandler 2 :: " + state.emitError) + // Set disconnected state + state.state = DISCONNECTED; + // Notify any strategies for read Preferences about closure + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); + // Destroy all connections + self.destroy(); + // console.log("!!!!!!!!!!!!! EMIT ERROR :: " + state.emitError + " :: " + self.listeners('error').length + " :: " + state.reconnect) + // Emit error event + if(state.emitError && self.listeners('error').length > 0) self.emit('error', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + reconnectServer(self, state) + }, state.reconnectInterval); + } + } +} + +var fatalErrorHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fatalErrorHandler") + // Flush the connection operations + if(self.s.callbacks) { + self.s.callbacks.flushConnection(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err))), connection); + } + + // // Emit error event + // if(self.listeners('error').length > 0) self.emit('error', err, self); + + // No more connections left, emit a close + if(state.pool.getAll().length == 0) { + // Set disconnected state + state.state = DISCONNECTED; + // Notify any strategies for read Preferences about closure + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); + // Emit error event + if(self.listeners('error').length > 0) self.emit('error', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } + } +} + +var timeoutHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% timeoutHandler = " + connection.port + " :: " + state.pool.getAll().length) + // console.log("----------------------- pool.write _execute 0 :: availableConnections = " + self.s.pool.availableConnections.length) + // console.log("----------------------- pool.write _execute 0 :: inUseConnections = " + self.s.pool.inUseConnections.length) + // console.log("----------------------- pool.write _execute 0 :: newConnections = " + self.s.pool.newConnections.length) + // console.log("----------------------- pool.write _execute 0 :: queue = " + self.s.pool.queue.length) + + // Flush the connection operations + if(self.s.callbacks) { + self.s.callbacks.flushConnection(new MongoError(f("server %s timed out", self.name)), connection); + } + + // // Emit error event + // self.emit('timeout', err, self); + + // No more connections left, emit a close + if(state.pool.getAll().length == 0) { + // Set disconnected state + state.state = DISCONNECTED; + // Notify any strategies for read Preferences about closure + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'timeout', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s timed out', self.name)); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s timed out", self.name))); + // Emit error event + self.emit('timeout', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } + } +} + +var closeHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% closeHandler :: " + state.pool.getAll().length) + + // // Emit error event + // self.emit('close', err, self); + + // No more connections left, emit a close + if(state.pool.getAll().length == 0) { + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% closeHandler 1 :: " + state.pool.getAll().length) + // Set state to disconnected + state.state = DISCONNECTED; + // Notify any strategies for read Preferences about closure + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'close', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s closed', self.name)); + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% closeHandler 2 :: " + state.pool.getAll().length) + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% closeHandler 3 :: " + state.pool.getAll().length) + // Emit error event + self.emit('close', err, self); + // console.log("!!!!!!!!!!!!! EMIT CLOSE :: " + state.reconnect) + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% closeHandler 1 :: " + state.pool.getAll().length) + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } + } +} + +var connectHandler = function(self, state) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! server connect :: " + self.name) + // Apply all stored authentications + var applyAuthentications = function(callback) { + // We need to ensure we have re-authenticated + var keys = Object.keys(state.authProviders); + if(keys.length == 0) return callback(null, null); + + // Get all connections + var connections = state.pool.getAll(); + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~ connectHandler :: " + connections.length) + // Execute all providers + var count = keys.length; + // Iterate over keys + for(var i = 0; i < keys.length; i++) { + state.authProviders[keys[i]].reauthenticate(self, connections, function(err, r) { + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + return callback(null, null); + } + }); + } + } + + return function() { + // Apply any applyAuthentications + applyAuthentications(function() { + // Get the actual latency of the ismaster + var start = new Date().getTime(); + // Execute an ismaster + self.command('admin.$cmd', {ismaster:true}, function(err, r) { + if(err) { + state.state = DISCONNECTED; + return self.emit('close', err, self); + } + + // Set the latency for this instance + state.isMasterLatencyMS = new Date().getTime() - start; + + // Set the current ismaster + if(!err) { + state.ismaster = r.result; + } + + // Emit the ismaster + self.emit('ismaster', r.result, self); + + // Determine the wire protocol handler + state.wireProtocolHandler = createWireProtocolHandler(state.ismaster); + + // Set the wireProtocolHandler + state.options.wireProtocolHandler = state.wireProtocolHandler; + + // Log the ismaster if available + if(state.logger.isInfo()) state.logger.info(f('server %s connected with ismaster [%s]', self.name, JSON.stringify(r.result))); + + // Validate if we it's a server we can connect to + if(!supportsServer(state) && state.wireProtocolHandler == null) { + state.state = DISCONNECTED + return self.emit('error', new MongoError("non supported server version"), self); + } + + // Set the details + if(state.ismaster && state.ismaster.me) state.serverDetails.name = state.ismaster.me; + + // No read preference strategies just emit connect + if(state.readPreferenceStrategies == null) { + state.state = CONNECTED; + return self.emit('connect', self); + } + + // Signal connect to all readPreferences + notifyStrategies(self, self.s, 'connect', [self], function(err, result) { + state.state = CONNECTED; + return self.emit('connect', self); + }); + }); + }); + } +} + +var slaveOk = function(r) { + if(r) return r.slaveOk() + return false; +} + +// +// Execute readPreference Strategies +var notifyStrategies = function(self, state, op, params, callback) { + if(typeof callback != 'function') { + // Notify query start to any read Preference strategies + for(var name in state.readPreferenceStrategies) { + if(state.readPreferenceStrategies[name][op]) { + var strat = state.readPreferenceStrategies[name]; + strat[op].apply(strat, params); + } + } + // Finish up + return; + } + + // Execute the async callbacks + var nPreferences = Object.keys(state.readPreferenceStrategies).length; + if(nPreferences == 0) return callback(null, null); + for(var name in state.readPreferenceStrategies) { + if(state.readPreferenceStrategies[name][op]) { + var strat = state.readPreferenceStrategies[name]; + // Add a callback to params + var cParams = params.slice(0); + cParams.push(function(err, r) { + nPreferences = nPreferences - 1; + if(nPreferences == 0) { + callback(null, null); + } + }) + // Execute the readPreference + strat[op].apply(strat, cParams); + } + } +} + +var debugFields = ['reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host' + , 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout', 'checkServerIdentity' + , 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs']; + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + */ +var Server = function(options) { + var self = this; + + // Add event listener + EventEmitter.call(this); + + // BSON Parser, ensure we have a single instance + if(bsonInstance == null) { + bsonInstance = new BSON(bsonTypes); + } + + // Reconnect retries + var reconnectTries = options.reconnectTries || 30; + + // console.log(")))))))))))))))))))))))))))))))))))))))))))))))))))))") + // console.dir(options) + + // Keeps all the internal state of the server + this.s = { + // Options + options: options + // Contains all the callbacks + , callbacks: new Callbacks() + // Logger + , logger: Logger('Server', options) + // Server state + , state: DISCONNECTED + // Reconnect option + , reconnect: typeof options.reconnect == 'boolean' ? options.reconnect : true + , reconnectTries: reconnectTries + , reconnectInterval: options.reconnectInterval || 1000 + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Current state + , currentReconnectRetry: reconnectTries + // Contains the ismaster + , ismaster: null + // Contains any alternate strategies for picking + , readPreferenceStrategies: options.readPreferenceStrategies + // Auth providers + , authProviders: options.authProviders || {} + // Server instance id + , id: serverId++ + // Grouping tag used for debugging purposes + , tag: options.tag + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + // wireProtocolHandler methods + , wireProtocolHandler: options.wireProtocolHandler || new PreTwoSixWireProtocolSupport() + // Factory overrides + , Cursor: options.cursorFactory || BasicCursor + // BSON Parser, ensure we have a single instance + , bsonInstance: bsonInstance + // Pick the right bson parser + , bson: options.bson ? options.bson : bsonInstance + // Internal connection pool + , pool: null + // Is master latency + , isMasterLatencyMS: 0 + // Server details + , serverDetails: { + host: options.host + , port: options.port + , name: options.port ? f("%s:%s", options.host, options.port) : options.host + } + } + + // Create hash method + var hash = crypto.createHash('sha1'); + hash.update(f('%s:%s', this.host, this.port)); + + // Create a hash name + this.hashedName = hash.digest('hex'); + + // Reference state + var s = this.s; + + // Add bson parser to options + options.bson = s.bson; + + // Set error properties + getProperty(this, 'name', 'name', s.serverDetails, {}); + getProperty(this, 'bson', 'bson', s.options, {}); + getProperty(this, 'wireProtocolHandler', 'wireProtocolHandler', s.options, {}); + getSingleProperty(this, 'id', s.id); + + // If we do not have an inherited authorization mechanism + if(!options.authProviders) { + this.addAuthProvider('mongocr', new MongoCR()); + this.addAuthProvider('x509', new X509()); + this.addAuthProvider('plain', new Plain()); + this.addAuthProvider('gssapi', new GSSAPI()); + this.addAuthProvider('sspi', new SSPI()); + this.addAuthProvider('scram-sha-1', new ScramSHA1()); + } +} + +inherits(Server, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +Server.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Reduce the poolSize to the provided max connections value + * @method + * @param {number} maxConnections reduce the poolsize to maxConnections + */ +Server.prototype.capConnections = function(maxConnections) { + this.s.pool.capConnections(maxConnections); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.s.ismaster; +} + +/** + * Initiate server connect + * @method + */ +Server.prototype.connect = function(_options) { + var self = this; + // Set server specific settings + _options = _options || {} + // Set the promotion + if(typeof _options.promoteLongs == 'boolean') { + self.s.options.promoteLongs = _options.promoteLongs; + } + + // Destroy existing pool + if(self.s.pool) { + self.s.pool.destroy(); + self.s.pool = null; + } + + // Set the state to connection + self.s.state = CONNECTING; + // Create a new connection pool + if(!self.s.pool) { + self.s.options.messageHandler = messageHandler(self, self.s); + self.s.pool = new Pool(self.s.options); + } + + // Add all the event handlers + self.s.pool.on('timeout', timeoutHandler(self, self.s)); + self.s.pool.on('close', closeHandler(self, self.s)); + self.s.pool.on('error', errorHandler(self, self.s)); + self.s.pool.once('connect', connectHandler(self, self.s)); + self.s.pool.on('parseError', fatalErrorHandler(self, self.s)); + + // + // Handle new connections + self.s.pool.on('connection', function(connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NEW Connection :: " + connection.id + " -- server -- " + self.s.id + " -- " + self.s.options.port) + + // No auth handler used, return the connection + var keys = Object.keys(self.s.authProviders); + if(keys.length == 0) return self.s.pool.connectionAvailable(connection); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NEW Connection 1 :: " + keys.length) + + // Get all connections + var connections = [connection]; + // Execute all providers + var count = keys.length; + + // Iterate over all auth methods + for(var i = 0; i < keys.length; i++) { + // console.log("------------------ authenticating against " + keys[i]); + // if(keys[i] == 'scram-sha-1') { + // console.dir(self.s.authProviders[keys[i]].authStore) + // } + // reauthenticate the connection + self.s.authProviders[keys[i]].reauthenticate(self, connections, function(err, r) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NEW Connection 1 auth :: ") + // console.dir(err) + // console.dir(r) + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NEW Connection 2 auth :: " + r) + // console.dir(err) + return self.s.pool.connectionAvailable(connection); + } + }); + } + }); + + // Connect the pool + self.s.pool.connect(); +} + +/** + * Destroy the server connection + * @method + */ +Server.prototype.destroy = function(emitClose, emitDestroy) { + var self = this; + if(self.s.logger.isDebug()) self.s.logger.debug(f('destroy called on server %s', self.name)); + + // Emit close + if(emitClose && self.listeners('close').length > 0) { + self.emit('close', null, self); + } + + // Emit destroy event + if(emitDestroy) self.emit('destroy', self); + // Set state as destroyed + self.s.state = DESTROYED; + // Close the pool + self.s.pool.destroy(); + // Flush out all the callbacks + if(self.s.callbacks) self.s.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + var self = this; + if(self.s.pool) return self.s.pool.isConnected(); + return false; +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + return this.s.state == DESTROYED; +} + +var executeSingleOperation = function(self, ns, cmd, queryOptions, options, onAll, callback) { + // Create a query instance + var query = new Query(self.s.bson, ns, cmd, queryOptions); + // Set slave OK + query.slaveOk = slaveOk(options.readPreference); + + // Notify query start to any read Preference strategies + if(self.s.readPreferenceStrategies != null) { + notifyStrategies(self, self.s, 'startOperation', [self, query, new Date()]); + } + + // Raw BSON response + var raw = typeof options.raw == 'boolean' ? options.raw : false; + + // Execute multiple queries + if(onAll) { + var connections = self.s.pool.getAll(); + var total = connections.length; + // We have an error + var error = null; + // Execute on all connections + for(var i = 0; i < connections.length; i++) { + // Command callback + var commandCallback = function(_connection) { + return function(err, result) { + if(err) error = err; + total = total - 1; + + // Done + if(total == 0) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, error, result, new Date()]); + if(error) return callback(MongoError.create(error)); + + // Add the connection details + result.hashedName = _connection.hashedName; + + // Execute callback, catch and rethrow if needed + try { + callback(null, new CommandResult(options.fullResult ? result : result.documents[0], connections)); + } catch(err) { + process.nextTick(function() { throw err}); + } + } + } + }; + + try { + query.incRequestId(); + connections[i].write(query.toBin()); + } catch(err) { + total = total - 1; + if(total == 0) return callback(MongoError.create(err)); + } + + // Return raw BSON docs + if(raw) { + commandCallback.raw = true; + } + + // Set the executed connection on the callback + commandCallback.connection = connections[i]; + + // Register the callback + self.s.callbacks.register(query.requestId, commandCallback(connections[i])); + } + + return; + } + + // Command callback + var commandCallback = function(err, result) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); + if(err) return callback(err); + // if(result && result.connection) { + // console.log("====== received result from connection " + result.connection.id) + // } + + if(result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || result.documents[0]['err'] + || result.documents[0]['code']) return callback(MongoError.create(result.documents[0])); + + // Add the connection details + result.hashedName = result.connection.hashedName; + + // Execute callback, catch and rethrow if needed + try { + callback(null, new CommandResult(options.fullResult ? result : result.documents[0], result.connection)); + } catch(err) { + process.nextTick(function() { throw err}); + } + }; + + try { + // Write the query out to the passed in connection or use the pool + // Passed in connections are used for authentication mechanisms + if(options.connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!! ONE") + // Add the reference to the connection to the callback so + // we can flush only the affected operations + commandCallback.connection = options.connection; + commandCallback.noRelease = true; + // Write out the command + options.connection.write(query.toBin()); + } else { + // console.log("!!!!!!!!!!!!!!!!!!!!!! TWO") + self.s.pool.write(query.toBin(), commandCallback, options); + } + + } catch(err) { + return callback(MongoError.create(err)); + } + + // Return raw BSON docs + if(raw) commandCallback.raw = true; + + // Register the callback + self.s.callbacks.register(query.requestId, commandCallback); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! execute command :: " + this.name) + // console.dir(cmd) + // console.dir(this.s.authProviders['scram-sha-1'].authStore) + // console.dir(Object.keys(options)) + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Ensure we have no options + options = options || {}; + + // Do we have a read Preference it need to be of type ReadPreference + if(options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error("readPreference must be an instance of ReadPreference"); + } + + // Debug log + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command [%s] against %s', JSON.stringify({ + ns: ns, cmd: cmd, options: debugOptions(debugFields, options) + }), self.name)); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // If we have no connection error + if(!self.s.pool.isConnected()) { + return callback(new MongoError(f("no connection available to server %s", self.name))); + } + + // Execute on all connections + var onAll = typeof options.onAll == 'boolean' ? options.onAll : false; + + // Check keys + var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys: false; + + // Serialize function + var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + + // Ignore undefined values + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + + // Raw BSON response + var raw = typeof options.raw == 'boolean' ? options.raw : false; + + // Query options + var queryOptions = { + numberToSkip: 0, numberToReturn: -1, checkKeys: checkKeys + }; + + // Set up the serialize functions and ignore undefined + if(serializeFunctions) queryOptions.serializeFunctions = serializeFunctions; + if(ignoreUndefined) queryOptions.ignoreUndefined = ignoreUndefined; + + // Single operation execution + executeSingleOperation(self, ns, cmd, queryOptions, options, onAll, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.insert(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + + // Execute write + return self.s.wireProtocolHandler.update(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.remove(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(mechanism, db) { + // console.log("=========================== SERVER.auth -- server -- " + this.s.id + " :: " + this.s.options.port) + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(self.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // If we have the default mechanism we pick mechanism based on the wire + // protocol max version. If it's >= 3 then scram-sha1 otherwise mongodb-cr + if(mechanism == 'default' && self.s.ismaster && self.s.ismaster.maxWireVersion >= 3) { + mechanism = 'scram-sha-1'; + } else if(mechanism == 'default') { + mechanism = 'mongocr'; + } + + // Get all available connections + var connections = self.s.pool.getAll(); + + // Actual arguments + var finalArguments = [self, connections, db].concat(args.slice(0)).concat([function(err, r) { + // console.log("=========================== SERVER.auth 0 :: " + self.s.id) + // console.dir(self.s.authProviders[mechanism].authStore) + // console.dir(err) + if(err) return callback(err); + if(!r) return callback(new MongoError('could not authenticate')); + callback(null, new Session({}, self)); + }]); + + // Let's invoke the auth mechanism + self.s.authProviders[mechanism].auth.apply(self.s.authProviders[mechanism], finalArguments); +} + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +Server.prototype.addReadPreferenceStrategy = function(name, strategy) { + var self = this; + if(self.s.readPreferenceStrategies == null) self.s.readPreferenceStrategies = {}; + self.s.readPreferenceStrategies[name] = strategy; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +Server.prototype.addAuthProvider = function(name, provider) { + // console.log("===== Server.prototype.addAuthProvider :: " + this.name) + var self = this; + self.s.authProviders[name] = provider; +} + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if(typeof server == 'string') return server == this.name; + + if(server && server.name) { + return server.name == this.name; + } + + return false; +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.getAll(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Server.prototype.getServer = function(options) { + return this; +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +Server.prototype.getConnection = function(options) { + return this.s.pool.get(); +} + +/** + * Get callbacks object + * @method + * @return {Callbacks} + */ +Server.prototype.getCallbacks = function() { + return this.s.callbacks; +} + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +Server.prototype.parserType = function() { + var s = this.s; + if(s.options.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +// // Command +// { +// find: ns +// , query: +// , limit: +// , fields: +// , skip: +// , hint: +// , explain: +// , snapshot: +// , batchSize: +// , returnKey: +// , maxScan: +// , min: +// , max: +// , showDiskLoc: +// , comment: +// , maxTimeMS: +// , raw: +// , readPreference: +// , tailable: +// , oplogReplay: +// , noCursorTimeout: +// , awaitdata: +// , exhaust: +// , partial: +// } + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.cursor = function(ns, cmd, cursorOptions) { + var s = this.s; + cursorOptions = cursorOptions || {}; + // Set up final cursor type + var FinalCursor = cursorOptions.cursorFactory || s.Cursor; + // Return the cursor + return new FinalCursor(s.bson, ns, cmd, cursorOptions, this, s.options); +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Server#close + * @type {Server} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Server#error + * @type {Server} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Server#timeout + * @type {Server} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Server#parseError + * @type {Server} + */ + +/** + * The server reestablished the connection + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * This is an insert result callback + * + * @callback opResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {CommandResult} command result + */ + +/** + * This is an authentication result callback + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {Session} an authenticated session + */ + +module.exports = Server; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js new file mode 100644 index 0000000..032c3c5 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js @@ -0,0 +1,93 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , EventEmitter = require('events').EventEmitter; + +/** + * Creates a new Authentication Session + * @class + * @param {object} [options] Options for the session + * @param {{Server}|{ReplSet}|{Mongos}} topology The topology instance underpinning the session + */ +var Session = function(options, topology) { + this.options = options; + this.topology = topology; + + // Add event listener + EventEmitter.call(this); +} + +inherits(Session, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {object} [options.readPreference] Specify read preference if command supports it + * @param {object} [options.connection] Specify connection object to execute command against + * @param {opResultCallback} callback A callback function + */ +Session.prototype.command = function(ns, cmd, options, callback) { + this.topology.command(ns, cmd, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.insert = function(ns, ops, options, callback) { + this.topology.insert(ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.update = function(ns, ops, options, callback) { + this.topology.update(ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.remove = function(ns, ops, options, callback) { + this.topology.remove(ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {boolean} [options.tailable=false] Tailable flag set + * @param {boolean} [options.oplogReply=false] oplogReply flag set + * @param {boolean} [options.awaitdata=false] awaitdata flag set + * @param {boolean} [options.exhaust=false] exhaust flag set + * @param {boolean} [options.partial=false] partial flag set + * @param {opResultCallback} callback A callback function + */ +Session.prototype.cursor = function(ns, cmd, options) { + return this.topology.cursor(ns, cmd, options); +} + +module.exports = Session; \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js new file mode 100644 index 0000000..4b7a1bb --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js @@ -0,0 +1,276 @@ +"use strict"; + +var Logger = require('../../connection/logger') + , EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format; + +/** + * Creates a new Ping read preference strategy instance + * @class + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) + * @return {Ping} A cursor instance + */ +var Ping = function(options) { + // Add event listener + EventEmitter.call(this); + + // Contains the ping state + this.s = { + // Contains all the ping data + pings: {} + // Set no options if none provided + , options: options || {} + // Logger + , logger: Logger('Ping', options) + // Ping interval + , pingInterval: options.pingInterval || 10000 + , acceptableLatency: options.acceptableLatency || 15 + // Debug options + , debug: typeof options.debug == 'boolean' ? options.debug : false + // Index + , index: 0 + // Current ping time + , lastPing: null + + } + + // Log the options set + if(this.s.logger.isDebug()) this.s.logger.debug(f('ping strategy interval [%s], acceptableLatency [%s]', this.s.pingInterval, this.s.acceptableLatency)); + + // If we have enabled debug + if(this.s.debug) { + // Add access to the read Preference Strategies + Object.defineProperty(this, 'data', { + enumerable: true, get: function() { return this.s.pings; } + }); + } +} + +inherits(Ping, EventEmitter); + +/** + * @ignore + */ +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tags = readPreference.tags; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) found = false; + } + + // Add to candidate list + if(found) filteredServers.push(servers[i]); + } + + // Returned filtered servers + return filteredServers; +} + +/** + * Pick a server + * @method + * @param {State} set The current replicaset state object + * @param {ReadPreference} readPreference The current readPreference object + * @param {readPreferenceResultCallback} callback The callback to return the result from the function + * @return {object} + */ +Ping.prototype.pickServer = function(set, readPreference) { + var self = this; + // Only get primary and secondaries as seeds + var seeds = {}; + var servers = []; + if(set.primary) { + servers.push(set.primary); + } + + for(var i = 0; i < set.secondaries.length; i++) { + servers.push(set.secondaries[i]); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Transform the list + var serverList = []; + // for(var name in seeds) { + for(var i = 0; i < servers.length; i++) { + serverList.push({name: servers[i].name, time: self.s.pings[servers[i].name] || 0}); + } + + // Sort by time + serverList.sort(function(a, b) { + return a.time > b.time; + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = serverList.length > 0 ? serverList[0].time : 0; + + // Filter by latency + serverList = serverList.filter(function(s) { + return s.time <= lowest + self.s.acceptableLatency; + }); + + // No servers, default to primary + if(serverList.length == 0 && set.primary) { + if(self.s.logger.isInfo()) self.s.logger.info(f('picked primary server [%s]', set.primary.name)); + return set.primary; + } else if(serverList.length == 0) { + return null + } + + // We picked first server + if(self.s.logger.isInfo()) self.s.logger.info(f('picked server [%s] with ping latency [%s]', serverList[0].name, serverList[0].time)); + + // Add to the index + self.s.index = self.s.index + 1; + // Select the index + self.s.index = self.s.index % serverList.length; + // Return the first server of the sorted and filtered list + return set.get(serverList[self.s.index].name); +} + +/** + * Start of an operation + * @method + * @param {Server} server The server the operation is running against + * @param {object} query The operation running + * @param {Date} date The start time of the operation + * @return {object} + */ +Ping.prototype.startOperation = function(server, query, date) { +} + +/** + * End of an operation + * @method + * @param {Server} server The server the operation is running against + * @param {error} err An error from the operation + * @param {object} result The result from the operation + * @param {Date} date The start time of the operation + * @return {object} + */ +Ping.prototype.endOperation = function(server, err, result, date) { +} + +/** + * High availability process running + * @method + * @param {State} set The current replicaset state object + * @param {resultCallback} callback The callback to return the result from the function + * @return {object} + */ +Ping.prototype.ha = function(topology, state, callback) { + var self = this; + var servers = state.getAll(); + var count = servers.length; + + // No servers return + if(servers.length == 0) return callback(null, null); + + // Return if we have not yet reached the ping interval + if(self.s.lastPing != null) { + var diff = new Date().getTime() - self.s.lastPing.getTime(); + if(diff < self.s.pingInterval) return callback(null, null); + } + + // Execute operation + var operation = function(_server) { + var start = new Date(); + // Execute ping against server + _server.command('system.$cmd', {ismaster:1}, function(err, r) { + count = count - 1; + var time = new Date().getTime() - start.getTime(); + self.s.pings[_server.name] = time; + // Log info for debug + if(self.s.logger.isDebug()) self.s.logger.debug(f('ha latency for server [%s] is [%s] ms', _server.name, time)); + // We are done with all the servers + if(count == 0) { + // Emit ping event + topology.emit('ping', err, r ? r.result : null); + // Update the last ping time + self.s.lastPing = new Date(); + // Return + callback(null, null); + } + }); + } + + // Let's ping all servers + while(servers.length > 0) { + operation(servers.shift()); + } +} + +var removeServer = function(self, server) { + delete self.s.pings[server.name]; +} + +/** + * Server connection closed + * @method + * @param {Server} server The server that closed + */ +Ping.prototype.close = function(server) { + removeServer(this, server); +} + +/** + * Server connection errored out + * @method + * @param {Server} server The server that errored out + */ +Ping.prototype.error = function(server) { + removeServer(this, server); +} + +/** + * Server connection timeout + * @method + * @param {Server} server The server that timed out + */ +Ping.prototype.timeout = function(server) { + removeServer(this, server); +} + +/** + * Server connection happened + * @method + * @param {Server} server The server that connected + * @param {resultCallback} callback The callback to return the result from the function + */ +Ping.prototype.connect = function(server, callback) { + var self = this; + // Get the command start date + var start = new Date(); + // Execute ping against server + server.command('system.$cmd', {ismaster:1}, function(err, r) { + var time = new Date().getTime() - start.getTime(); + self.s.pings[server.name] = time; + // Log info for debug + if(self.s.logger.isDebug()) self.s.logger.debug(f('connect latency for server [%s] is [%s] ms', server.name, time)); + // Set last ping + self.s.lastPing = new Date(); + // Done, return + callback(null, null); + }); +} + +/** + * This is a result from a readPreference strategy + * + * @callback readPreferenceResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {Server} server The server picked by the strategy + */ + +module.exports = Ping; \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js new file mode 100644 index 0000000..af062cb --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js @@ -0,0 +1,589 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +// Write concern fields +var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync']; + +var WireProtocol = function() {} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var legacy = typeof options.legacy == 'boolean' ? options.legacy : false; + ops = Array.isArray(ops) ? ops :[ops]; + + // If we have more than a 1000 ops fails + if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000")); + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callbacks, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(pool && pool.isConnected()) pool.write(killCursor.toBin(), callback, {immediateRelease:true}); + // Set cursor to 0 + cursorId = Long.ZERO; + // Return to caller + if(callback) callback(null, null); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, pool, callbacks, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId == 'number' + ? Long.fromNumber(r.cursorId) + : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Register a callback + callbacks.register(getMore.requestId, queryCallback); + // Write out the getMore command + pool.write(getMore.toBin(), queryCallback); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Does the cmd have a readPreference + if(cmd.readPreference) { + readPreference = cmd.readPreference; + } + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + if(cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Set up the serialize and ignoreUndefined fields + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; + if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; + if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Does the cmd have a readPreference + if(cmd.readPreference) { + readPreference = cmd.readPreference; + } + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) delete cmd['readConcern']; + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + finalCmd = { + '$query': finalCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +var hasWriteConcern = function(writeConcern) { + if(writeConcern.w + || writeConcern.wtimeout + || writeConcern.j == true + || writeConcern.fsync == true + || Object.keys(writeConcern).length == 0) { + return true; + } + return false; +} + +var cloneWriteConcern = function(writeConcern) { + var wc = {}; + if(writeConcern.w != null) wc.w = writeConcern.w; + if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout; + if(writeConcern.j != null) wc.j = writeConcern.j; + if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync; + return wc; +} + +// +// Aggregate up all the results +// +var aggregateWriteOperationResults = function(opType, ops, results, connection) { + var finalResult = { ok: 1, n: 0 } + + // Map all the results coming back + for(var i = 0; i < results.length; i++) { + var result = results[i]; + var op = ops[i]; + + if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) { + finalResult.upserted = []; + } + + // Push the upserted document to the list of upserted values + if(result.upserted) { + finalResult.upserted.push({index: i, _id: result.upserted}); + } + + // We have an upsert where we passed in a _id + if(result.updatedExisting == false && result.n == 1 && result.upserted == null) { + finalResult.upserted.push({index: i, _id: op.q._id}); + } + + // We have an insert command + if(result.ok == 1 && opType == 'insert' && result.err == null) { + finalResult.n = finalResult.n + 1; + } + + // We have a command error + if(result != null && result.ok == 0 || result.err || result.errmsg) { + if(result.ok == 0) finalResult.ok = 0; + finalResult.code = result.code; + finalResult.errmsg = result.errmsg || result.err || result.errMsg; + + // Check if we have a write error + if(result.code == 11000 + || result.code == 11001 + || result.code == 12582 + || result.code == 16544 + || result.code == 16538 + || result.code == 16542 + || result.code == 14 + || result.code == 13511) { + if(finalResult.writeErrors == null) finalResult.writeErrors = []; + finalResult.writeErrors.push({ + index: i + , code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + }); + } else { + finalResult.writeConcernError = { + code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + } + } + } else if(typeof result.n == 'number') { + finalResult.n += result.n; + } else { + finalResult.n += 1; + } + + // Result as expected + if(result != null && result.lastOp) finalResult.lastOp = result.lastOp; + } + + // Return finalResult aggregated results + return new CommandResult(finalResult, connection); +} + +// +// Execute all inserts in an ordered manner +// +var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + var _ops = ops.slice(0); + // Bind to current domain + callback = bindToCurrentDomain(callback); + // Collect all the getLastErrors + var getLastErrors = []; + + // Execute an operation + var executeOp = function(list, _callback) { + // No more items in the list + if(list.length == 0) { + return process.nextTick(function() { + _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); + }); + } + + // Get the first operation + var doc = list.shift(); + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options); + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + + // Get the db name + var db = ns.split('.').shift(); + + try { + // Add binary message to list of commands to execute + var commands = [op.toBin()]; + + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var i = 0; i < writeConcernFields.length; i++) { + if(writeConcern[writeConcernFields[i]] != null) { + getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]]; + } + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Add getLastError command to list of ops to execute + commands.push(getLastErrorOp.toBin()); + + // getLastError callback + var getLastErrorCallback = function(err, result) { + if(err) return callback(err); + // Get the document + var doc = result.documents[0]; + // Save the getLastError document + getLastErrors.push(doc); + + // If we have an error terminate + if(doc.ok == 0 || doc.err || doc.errmsg) { + return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection)); + } + + // Execute the next op in the list + executeOp(list, callback); + } + + // Register the callback + callbacks.register(getLastErrorOp.requestId, getLastErrorCallback); + // Write both commands out at the same time + pool.write(commands, getLastErrorCallback); + } else { + // Write both commands out at the same time + pool.write(commands, callback, {immediateRelease:true}); + } + } catch(err) { + if(typeof err == 'string') err = new MongoError(err); + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors.push({ ok: 1, errmsg: err.message, code: 14 }); + // Return due to an error + process.nextTick(function() { + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); + }); + } + } + + // Execute the operations + executeOp(_ops, callback); +} + +var executeUnordered = function(opType, command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + // Bind to current domain + callback = bindToCurrentDomain(callback); + // Total operations to write + var totalOps = ops.length; + // Collect all the getLastErrors + var getLastErrors = []; + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + // Driver level error + var error; + + // Execute all the operations + for(var i = 0; i < ops.length; i++) { + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options); + // Get db name + var db = ns.split('.').shift(); + + try { + // Add binary message to list of commands to execute + var commands = [op.toBin()]; + + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var j = 0; j < writeConcernFields.length; j++) { + if(writeConcern[writeConcernFields[j]] != null) + getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]]; + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Add getLastError command to list of ops to execute + commands.push(getLastErrorOp.toBin()); + + // Give the result from getLastError the right index + var callbackOp = function(_index) { + return function(err, result) { + if(err) error = err; + // Update the number of operations executed + totalOps = totalOps - 1; + // Save the getLastError document + if(!err) getLastErrors[_index] = result.documents[0]; + // Check if we are done + if(totalOps == 0) { + process.nextTick(function() { + if(error) return callback(error); + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection)); + }); + } + } + } + + // Register the callback + callbacks.register(getLastErrorOp.requestId, callbackOp(i)); + // Write both commands out at the same time + pool.write(commands, callbackOp(i)); + } else { + // Write both commands out at the same time + pool.write(commands, callback, {immediateRelease:true}); + } + } catch(err) { + if(typeof err == 'string') err = new MongoError(err); + // Update the number of operations executed + totalOps = totalOps - 1; + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors[i] = { ok: 1, errmsg: err.message, code: 14 }; + // Check if we are done + if(totalOps == 0) { + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); + } + } + } + + // Empty w:0 return + if(writeConcern + && writeConcern.w == 0 && callback) { + callback(null, null); + } +} + +module.exports = WireProtocol; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js new file mode 100644 index 0000000..1dace34 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js @@ -0,0 +1,329 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +var WireProtocol = function() {} + +// +// Execute a write operation +var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern || {}; + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + // Did we specify a write concern + if(writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + // Options object + var opts = {}; + if(type == 'insert') opts.checkKeys = true; + // Ensure we support serialization of functions + if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; + if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; + // Execute command + topology.command(f("%s.$cmd", d), writeCommand, opts, callback); +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'update', 'updates', ns, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callbacks, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(pool && pool.isConnected()) pool.write(killCursor.toBin(), callback, {immediateRelease:true}); + // Set cursor to 0 + cursorId = Long.ZERO; + // Return to caller + if(callback) callback(null, null); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, pool, callbacks, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId == 'number' + ? Long.fromNumber(r.cursorId) + : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Register a callback + callbacks.register(getMore.requestId, queryCallback); + // Write out the getMore command + pool.write(getMore.toBin(), callback); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Does the cmd have a readPreference + if(cmd.readPreference) { + readPreference = cmd.readPreference; + } + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + if(cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + , serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') { + query.tailable = cmd.tailable; + } + + if(typeof cmd.oplogReplay == 'boolean') { + query.oplogReplay = cmd.oplogReplay; + } + + if(typeof cmd.noCursorTimeout == 'boolean') { + query.noCursorTimeout = cmd.noCursorTimeout; + } + + if(typeof cmd.awaitData == 'boolean') { + query.awaitData = cmd.awaitData; + } + + if(typeof cmd.exhaust == 'boolean') { + query.exhaust = cmd.exhaust; + } + + if(typeof cmd.partial == 'boolean') { + query.partial = cmd.partial; + } + + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Does the cmd have a readPreference + if(cmd.readPreference) { + readPreference = cmd.readPreference; + } + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) delete cmd['readConcern']; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + finalCmd = { + '$query': finalCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +module.exports = WireProtocol; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js new file mode 100644 index 0000000..aa1618d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js @@ -0,0 +1,520 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +var WireProtocol = function(legacyWireProtocol) { + this.legacyWireProtocol = legacyWireProtocol; +} + +// +// Execute a write operation +var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern; + + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + // Did we specify a write concern + if(writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + // Do we have bypassDocumentValidation set, then enable it on the write command + if(typeof options.bypassDocumentValidation == 'boolean') { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Options object + var opts = {}; + if(type == 'insert') opts.checkKeys = true; + // Ensure we support serialization of functions + if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; + if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; + // Execute command + topology.command(f("%s.$cmd", d), writeCommand, opts, callback); +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'update', 'updates', ns, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callbacks, callback) { + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + // Create getMore command + var killcursorCmd = { + killCursors: parts.join('.'), + cursors: [cursorId] + } + + // Build Query object + var query = new Query(bson, commandns, killcursorCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + }); + + // Set query flags + query.slaveOk = true; + + // Execute the kill cursor command + if(pool && pool.isConnected()) { + pool.write(query.toBin(), callback); + } + + // Kill cursor callback + var killCursorCallback = function(err, r) { + if(err) { + if(typeof callback != 'function') return; + return callback(err); + } + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + if(typeof callback != 'function') return; + return callback(new MongoError("cursor killed or timed out"), null); + } + + if(!Array.isArray(r.documents) || r.documents.length == 0) { + if(typeof callback != 'function') return; + return callback(new MongoError(f('invalid killCursors result returned for cursor id %s', cursorState.cursorId))); + } + + // Return the result + if(typeof callback == 'function') { + callback(null, r.documents[0]); + } + } + + // Register a callback + callbacks.register(query.requestId, killCursorCallback); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, pool, callbacks, options, callback) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + + // Check if we have an maxTimeMS set + var maxTimeMS = typeof cursorState.cmd.maxTimeMS == 'number' ? cursorState.cmd.maxTimeMS : 3000; + + // Create getMore command + var getMoreCmd = { + getMore: cursorState.cursorId, + collection: parts.join('.'), + batchSize: Math.abs(batchSize) + } + + if(cursorState.cmd.tailable + && typeof cursorState.cmd.maxAwaitTimeMS == 'number') { + getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; + } + + // Build Query object + var query = new Query(bson, commandns, getMoreCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + }); + + // Set query flags + query.slaveOk = true; + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Raw, return all the extracted documents + if(raw) { + cursorState.documents = r.documents; + cursorState.cursorId = r.cursorId; + return callback(null, r.documents); + } + + // We have an error detected + if(r.documents[0].ok == 0) { + return callback(MongoError.create(r.documents[0])); + } + + // Ensure we have a Long valid cursor id + var cursorId = typeof r.documents[0].cursor.id == 'number' + ? Long.fromNumber(r.documents[0].cursor.id) + : r.documents[0].cursor.id; + + // Set all the values + cursorState.documents = r.documents[0].cursor.nextBatch; + cursorState.cursorId = cursorId; + + // Return the result + callback(null, r.documents[0]); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Add the result field needed + queryCallback.documentsReturnedIn = 'nextBatch'; + + // Register a callback + callbacks.register(query.requestId, queryCallback); + // Write out the getMore command + pool.write(query.toBin(), queryCallback); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + if(cmd.exhaust) { + return this.legacyWireProtocol.command(bson, ns, cmd, cursorState, topology, options); + } + + // Create the find command + var query = executeFindCommand(bson, ns, cmd, cursorState, topology, options) + // Mark the cmd as virtual + cmd.virtual = false; + // Signal the documents are in the firstBatch value + query.documentsReturnedIn = 'firstBatch'; + // Return the query + return query; + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// // Command +// { +// find: ns +// , query: +// , limit: +// , fields: +// , skip: +// , hint: +// , explain: +// , snapshot: +// , batchSize: +// , returnKey: +// , maxScan: +// , min: +// , max: +// , showDiskLoc: +// , comment: +// , maxTimeMS: +// , raw: +// , readPreference: +// , tailable: +// , oplogReplay: +// , noCursorTimeout: +// , awaitdata: +// , exhaust: +// , partial: +// } + +// FIND/GETMORE SPEC +// { +// “find”: , +// “filter”: { ... }, +// “sort”: { ... }, +// “projection”: { ... }, +// “hint”: { ... }, +// “skip”: , +// “limit”: , +// “batchSize”: , +// “singleBatch”: , +// “comment”: , +// “maxScan”: , +// “maxTimeMS”: , +// “max”: { ... }, +// “min”: { ... }, +// “returnKey”: , +// “showRecordId”: , +// “snapshot”: , +// “tailable”: , +// “oplogReplay”: , +// “noCursorTimeout”: , +// “awaitData”: , +// “partial”: , +// “$readPreference”: { ... } +// } + +// +// Execute a find command +var executeFindCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Does the cmd have a readPreference + if(cmd.readPreference) { + readPreference = cmd.readPreference; + } + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + + // Build actual find command + var findCmd = { + find: parts.join('.') + }; + + // I we provided a filter + if(cmd.query) findCmd.filter = cmd.query; + + // Sort value + var sortValue = cmd.sort; + + // Handle issue of sort being an Array + if(Array.isArray(sortValue)) { + var sortObject = {}; + + if(sortValue.length > 0 && !Array.isArray(sortValue[0])) { + var sortDirection = sortValue[1]; + // Translate the sort order text + if(sortDirection == 'asc') { + sortDirection = 1; + } else if(sortDirection == 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[0]] = sortDirection; + } else { + for(var i = 0; i < sortValue.length; i++) { + var sortDirection = sortValue[i][1]; + // Translate the sort order text + if(sortDirection == 'asc') { + sortDirection = 1; + } else if(sortDirection == 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[i][0]] = sortDirection; + } + } + + sortValue = sortObject; + }; + + // Add sort to command + if(cmd.sort) findCmd.sort = sortValue; + // Add a projection to the command + if(cmd.fields) findCmd.projection = cmd.fields; + // Add a hint to the command + if(cmd.hint) findCmd.hint = cmd.hint; + // Add a skip + if(cmd.skip) findCmd.skip = cmd.skip; + // Add a limit + if(cmd.limit) findCmd.limit = cmd.limit; + // Add a batchSize + if(typeof cmd.batchSize == 'number') findCmd.batchSize = Math.abs(cmd.batchSize); + + // Check if we wish to have a singleBatch + if(cmd.limit < 0) { + findCmd.limit = Math.abs(cmd.limit); + findCmd.singleBatch = true; + } + + // If we have comment set + if(cmd.comment) findCmd.comment = cmd.comment; + + // If we have maxScan + if(cmd.maxScan) findCmd.maxScan = cmd.maxScan; + + // If we have maxTimeMS set + if(cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; + + // If we have min + if(cmd.min) findCmd.min = cmd.min; + + // If we have max + if(cmd.max) findCmd.max = cmd.max; + + // If we have returnKey set + if(cmd.returnKey) findCmd.returnKey = cmd.returnKey; + + // If we have showDiskLoc set + if(cmd.showDiskLoc) findCmd.showRecordId = cmd.showDiskLoc; + + // If we have snapshot set + if(cmd.snapshot) findCmd.snapshot = cmd.snapshot; + + // If we have tailable set + if(cmd.tailable) findCmd.tailable = cmd.tailable; + + // If we have oplogReplay set + if(cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; + + // If we have noCursorTimeout set + if(cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; + + // If we have awaitData set + if(cmd.awaitData) findCmd.awaitData = cmd.awaitData; + if(cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; + + // If we have partial set + if(cmd.partial) findCmd.partial = cmd.partial; + + // If we have explain, we need to rewrite the find command + // to wrap it in the explain command + if(cmd.explain) { + findCmd = { + explain: findCmd + } + } + + // Did we provide a readConcern + if(cmd.readConcern) findCmd.readConcern = cmd.readConcern; + + // Set up the serialize and ignoreUndefined fields + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + findCmd = { + '$query': findCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, commandns, findCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + finalCmd = { + '$query': finalCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +module.exports = WireProtocol; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js new file mode 100644 index 0000000..9c665ee --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js @@ -0,0 +1,357 @@ +"use strict"; + +var MongoError = require('../error'); + +// Wire command operation ids +var OP_UPDATE = 2001; +var OP_INSERT = 2002; +var OP_DELETE = 2006; + +var Insert = function(requestId, ismaster, bson, ns, documents, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + if(!Array.isArray(documents) || documents.length == 0) throw new MongoError("documents array must contain at least one document to insert"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new MongoError("namespace cannot contain a null character"); + } + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.documents = documents; + this.ismaster = ismaster; + + // Ensure empty options + options = options || {}; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.continueOnError = typeof options.continueOnError == 'boolean' ? options.continueOnError : false; + // Set flags + this.flags = this.continueOnError ? 1 : 0; +} + +// To Binary +Insert.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // Flags + + Buffer.byteLength(this.ns) + 1 // namespace + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize all the documents + for(var i = 0; i < this.documents.length; i++) { + var buffer = this.bson.serialize(this.documents[i] + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + + // Document is larger than maxBsonObjectSize, terminate serialization + if(buffer.length > this.ismaster.maxBsonObjectSize) { + throw new MongoError("Document exceeds maximum allowed bson size of " + this.ismaster.maxBsonObjectSize + " bytes"); + } + + // Add to total length of wire protocol message + totalLength = totalLength + buffer.length; + // Add to buffer + buffers.push(buffer); + } + + // Command is larger than maxMessageSizeBytes terminate serialization + if(totalLength > this.ismaster.maxMessageSizeBytes) { + throw new MongoError("Command exceeds maximum message size of " + this.ismaster.maxMessageSizeBytes + " bytes"); + } + + // Add all the metadata + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_INSERT >> 24) & 0xff; + header[index + 2] = (OP_INSERT >> 16) & 0xff; + header[index + 1] = (OP_INSERT >> 8) & 0xff; + header[index] = (OP_INSERT) & 0xff; + index = index + 4; + + // Flags + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Return the buffers + return buffers; +} + +var Update = function(requestId, ismaster, bson, ns, update, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.upsert = typeof update[0].upsert == 'boolean' ? update[0].upsert : false; + this.multi = typeof update[0].multi == 'boolean' ? update[0].multi : false; + this.q = update[0].q; + this.u = update[0].u; + + // Create flag value + this.flags = this.upsert ? 1 : 0; + this.flags = this.multi ? this.flags | 2 : this.flags; +} + +// To Binary +Update.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // ZERO + + Buffer.byteLength(this.ns) + 1 // namespace + + 4 // Flags + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize the selector + var selector = this.bson.serialize(this.q + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(selector); + totalLength = totalLength + selector.length; + + // Serialize the update + var update = this.bson.serialize(this.u + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(update); + totalLength = totalLength + update.length; + + // Index in header buffer + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_UPDATE >> 24) & 0xff; + header[index + 2] = (OP_UPDATE >> 16) & 0xff; + header[index + 1] = (OP_UPDATE >> 8) & 0xff; + header[index] = (OP_UPDATE) & 0xff; + index = index + 4; + + // Write ZERO + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Flags + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +var Remove = function(requestId, ismaster, bson, ns, remove, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.limit = typeof remove[0].limit == 'number' ? remove[0].limit : 1; + this.q = remove[0].q; + + // Create flag value + this.flags = this.limit == 1 ? 1 : 0; +} + +// To Binary +Remove.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // ZERO + + Buffer.byteLength(this.ns) + 1 // namespace + + 4 // Flags + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize the selector + var selector = this.bson.serialize(this.q + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(selector); + totalLength = totalLength + selector.length; + + // Index in header buffer + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_DELETE >> 24) & 0xff; + header[index + 2] = (OP_DELETE >> 16) & 0xff; + header[index + 1] = (OP_DELETE >> 8) & 0xff; + header[index] = (OP_DELETE) & 0xff; + index = index + 4; + + // Write ZERO + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write ZERO + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +module.exports = { + Insert: Insert + , Update: Update + , Remove: Remove +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.npmignore b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.npmignore new file mode 100644 index 0000000..e920c16 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.npmignore @@ -0,0 +1,33 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +node_modules + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.travis.yml b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.travis.yml new file mode 100644 index 0000000..38de5c6 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "4.2.1" +sudo: false diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/LICENSE @@ -0,0 +1,201 @@ + 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/README.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/README.md new file mode 100644 index 0000000..c0323f0 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/README.md @@ -0,0 +1,2 @@ +# require_optional +Work around the problem that we do not have a optionalPeerDependencies concept in node.js making it a hassle to optionally include native modules diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js new file mode 100644 index 0000000..9754581 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js @@ -0,0 +1,109 @@ +var path = require('path'), + fs = require('fs'), + f = require('util').format, + resolveFrom = require('resolve-from'), + semver = require('semver'); + +var exists = fs.existsSync || path.existsSync; + +var find_package_json = function(location) { + var found = false; + + while(!found) { + if (exists(location + '/package.json')) { + found = location; + } else if (location !== '/') { + location = path.dirname(location); + } else { + return false; + } + } + + return location; +} + +var require_optional = function(name, options) { + options = options || {}; + options.strict = typeof options.strict == 'boolean' ? options.strict : true; + + // Current location + var location = __dirname; + // Check if we have a parent + if(module.parent) { + location = module.parent.filename; + } + + // Locate this module's package.json file + var location = find_package_json(location); + if(!location) { + throw new Error('package.json can not be located'); + } + + // Read the package.json file + var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Is the name defined by interal file references + var parts = name.split(/\//); + + // Optional dependencies exist + if(!object.peerOptionalDependencies) { + throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in package.json', parts[0])); + } else if(object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]]) { + throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in package.json', parts[0])); + } + + // Unpack the expected version + var expectedVersions = object.peerOptionalDependencies[parts[0]]; + // The resolved package + var moduleEntry = undefined; + // Module file + var moduleEntryFile = name; + + try { + // Validate if it's possible to read the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + // Attempt to resolve in top level package + try { + // Get the module entry file + moduleEntryFile = resolveFrom(process.cwd(), name); + if(moduleEntryFile == null) return undefined; + // Attempt to resolve the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + if(err.code === 'MODULE_NOT_FOUND') return undefined; + } + } + + // Resolve the location of the module's package.json file + var location = find_package_json(require.resolve(moduleEntryFile)); + if(!location) { + throw new Error('package.json can not be located'); + } + + // Read the module file + var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Get the version + var version = dependentOnModule.version; + // Validate if the found module satisfies the version id + if(semver.satisfies(version, expectedVersions) == false + && options.strict) { + var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); + error.code = 'OPTIONAL_MODULE_NOT_FOUND'; + throw error; + } + + // Satifies the module requirement + return moduleEntry; +} + +require_optional.exists = function(name) { + try { + var m = require_optional(name); + if(m === undefined) return false; + return true; + } catch(err) { + return false; + } +} + +module.exports = require_optional; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver new file mode 120000 index 0000000..317eb29 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/index.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/index.js new file mode 100644 index 0000000..434159f --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/index.js @@ -0,0 +1,23 @@ +'use strict'; +var path = require('path'); +var Module = require('module'); + +module.exports = function (fromDir, moduleId) { + if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { + throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); + } + + fromDir = path.resolve(fromDir); + + var fromFile = path.join(fromDir, 'noop.js'); + + try { + return Module._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: Module._nodeModulePaths(fromDir) + }); + } catch (err) { + return null; + } +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/license b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/package.json new file mode 100644 index 0000000..72dbde6 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/package.json @@ -0,0 +1,63 @@ +{ + "name": "resolve-from", + "version": "2.0.0", + "description": "Resolve the path of a module like require.resolve() but from a given path", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/sindresorhus/resolve-from" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "require", + "resolve", + "path", + "module", + "from", + "like", + "path" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "gitHead": "583e0f8df06e1bc4d1c96d8d4f2484c745f522c3", + "bugs": { + "url": "https://github.com/sindresorhus/resolve-from/issues" + }, + "homepage": "https://github.com/sindresorhus/resolve-from", + "_id": "resolve-from@2.0.0", + "_shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", + "_from": "resolve-from@>=2.0.0 <3.0.0", + "_npmVersion": "2.14.7", + "_nodeVersion": "4.2.1", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "dist": { + "shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", + "tarball": "http://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/readme.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/readme.md new file mode 100644 index 0000000..bb4ca91 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/readme.md @@ -0,0 +1,58 @@ +# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) + +> Resolve the path of a module like [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve) but from a given path + +Unlike `require.resolve()` it returns `null` instead of throwing when the module can't be found. + + +## Install + +``` +$ npm install --save resolve-from +``` + + +## Usage + +```js +const resolveFrom = require('resolve-from'); + +// there's a file at `./foo/bar.js` + +resolveFrom('foo', './bar'); +//=> '/Users/sindresorhus/dev/test/foo/bar.js' +``` + + +## API + +### resolveFrom(fromDir, moduleId) + +#### fromDir + +Type: `string` + +Directory to resolve from. + +#### moduleId + +Type: `string` + +What you would use in `require()`. + + +## Tip + +Create a partial using a bound function if you want to require from the same `fromDir` multiple times: + +```js +const resolveFromFoo = resolveFrom.bind(null, 'foo'); + +resolveFromFoo('./bar'); +resolveFromFoo('./baz'); +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.npmignore b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.npmignore new file mode 100644 index 0000000..534108e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.npmignore @@ -0,0 +1,4 @@ +node_modules/ +coverage/ +.nyc_output/ +nyc_output/ diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.travis.yml b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.travis.yml new file mode 100644 index 0000000..991d04b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - 'iojs' diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/README.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/README.md new file mode 100644 index 0000000..0b14a7e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/README.md @@ -0,0 +1,327 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Usage + + $ npm install semver + + semver.valid('1.2.3') // '1.2.3' + semver.valid('a.b.c') // null + semver.clean(' =v1.2.3 ') // '1.2.3' + semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true + semver.gt('1.2.3', '9.8.7') // false + semver.lt('1.2.3', '9.8.7') // true + +As a command-line utility: + + $ semver -h + + Usage: semver [ [...]] [-r | -i | --preid | -l | -rv] + Test if version(s) satisfy the supplied range(s), and sort them. + + Multiple versions or ranges may be supplied, unless increment + option is specified. In that case, only a single version may + be used, and it is incremented by the specified level + + Program exits successfully if any valid version satisfies + all supplied ranges, and prints all satisfying versions. + + If no versions are valid, or ranges are not satisfied, + then exits failure. + + Versions are printed in ascending order, so supplying + multiple versions to the utility will just sort them. + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +> semver.inc('1.2.3', 'prerelease', 'beta') +'1.2.4-beta.0' +``` + +command-line example: + +```shell +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```shell +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero digit in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9']['0'-'9']+ +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `loose` boolean argument that, if +true, will be more forgiving about not-quite-valid semver strings. +The resulting output will always be 100% strict, of course. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/bin/semver b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/bin/semver new file mode 100755 index 0000000..c5f2e85 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/bin/semver @@ -0,0 +1,133 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + , versions = [] + , range = [] + , gt = [] + , lt = [] + , eq = [] + , inc = null + , version = require("../package.json").version + , loose = false + , identifier = undefined + , semver = require("../semver") + , reverse = false + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var i = a.indexOf('=') + if (i !== -1) { + a = a.slice(0, i) + argv.unshift(a.slice(i + 1)) + } + switch (a) { + case "-rv": case "-rev": case "--rev": case "--reverse": + reverse = true + break + case "-l": case "--loose": + loose = true + break + case "-v": case "--version": + versions.push(argv.shift()) + break + case "-i": case "--inc": case "--increment": + switch (argv[0]) { + case "major": case "minor": case "patch": case "prerelease": + case "premajor": case "preminor": case "prepatch": + inc = argv.shift() + break + default: + inc = "patch" + break + } + break + case "--preid": + identifier = argv.shift() + break + case "-r": case "--range": + range.push(argv.shift()) + break + case "-h": case "--help": case "-?": + return help() + default: + versions.push(a) + break + } + } + + versions = versions.filter(function (v) { + return semver.valid(v, loose) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) + return failInc() + + for (var i = 0, l = range.length; i < l ; i ++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], loose) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error("--inc can only be used on a single version with no range") + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? "rcompare" : "compare" + versions.sort(function (a, b) { + return semver[compare](a, b, loose) + }).map(function (v) { + return semver.clean(v, loose) + }).map(function (v) { + return inc ? semver.inc(v, inc, loose, identifier) : v + }).forEach(function (v,i,_) { console.log(v) }) +} + +function help () { + console.log(["SemVer " + version + ,"" + ,"A JavaScript implementation of the http://semver.org/ specification" + ,"Copyright Isaac Z. Schlueter" + ,"" + ,"Usage: semver [options] [ [...]]" + ,"Prints valid versions sorted by SemVer precedence" + ,"" + ,"Options:" + ,"-r --range " + ," Print versions that match the specified range." + ,"" + ,"-i --increment []" + ," Increment a version by the specified level. Level can" + ," be one of: major, minor, patch, premajor, preminor," + ," prepatch, or prerelease. Default level is 'patch'." + ," Only one version may be specified." + ,"" + ,"--preid " + ," Identifier to be used to prefix premajor, preminor," + ," prepatch or prerelease version increments." + ,"" + ,"-l --loose" + ," Interpret versions and ranges loosely" + ,"" + ,"Program exits successfully if any valid version satisfies" + ,"all supplied ranges, and prints all satisfying versions." + ,"" + ,"If no satisfying versions are found, then exits failure." + ,"" + ,"Versions are printed in ascending order, so supplying" + ,"multiple versions to the utility will just sort them." + ].join("\n")) +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/package.json new file mode 100644 index 0000000..ce73daa --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/package.json @@ -0,0 +1,50 @@ +{ + "name": "semver", + "version": "5.1.0", + "description": "The semantic version parser used by npm.", + "main": "semver.js", + "scripts": { + "test": "tap test/*.js" + }, + "devDependencies": { + "tap": "^2.0.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "./bin/semver" + }, + "gitHead": "8e33a30e62e40e4983d1c5f55e794331b861aadc", + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "homepage": "https://github.com/npm/node-semver#readme", + "_id": "semver@5.1.0", + "_shasum": "85f2cf8550465c4df000cf7d86f6b054106ab9e5", + "_from": "semver@>=5.1.0 <6.0.0", + "_npmVersion": "3.3.2", + "_nodeVersion": "4.0.0", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "dist": { + "shasum": "85f2cf8550465c4df000cf7d86f6b054106ab9e5", + "tarball": "http://registry.npmjs.org/semver/-/semver-5.1.0.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + { + "name": "othiym23", + "email": "ogd@aoaioxxysz.net" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/semver/-/semver-5.1.0.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/range.bnf b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/range.bnf new file mode 100644 index 0000000..000df92 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9']['0'-'9']+ +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/semver.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/semver.js new file mode 100644 index 0000000..71795f6 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/semver.js @@ -0,0 +1,1188 @@ +exports = module.exports = SemVer; + +// The debug function is excluded entirely from the minified version. +/* nomin */ var debug; +/* nomin */ if (typeof process === 'object' && + /* nomin */ process.env && + /* nomin */ process.env.NODE_DEBUG && + /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ debug = function() { + /* nomin */ var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ args.unshift('SEMVER'); + /* nomin */ console.log.apply(console, args); + /* nomin */ }; +/* nomin */ else + /* nomin */ debug = function() {}; + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; + +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; + +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; + + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; + +src[FULL] = '^' + FULLPLAIN + '$'; + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; + +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; + +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; + +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; + +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; + +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; + +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; + + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; + +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; + +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) + re[i] = new RegExp(src[i]); +} + +exports.parse = parse; +function parse(version, loose) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + if (version.length > MAX_LENGTH) + return null; + + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; + + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } +} + +exports.valid = valid; +function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; +} + + +exports.clean = clean; +function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; +} + +exports.SemVer = SemVer; + +function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + if (!(this instanceof SemVer)) + return new SemVer(version, loose); + + debug('SemVer', version, loose); + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + + if (!m) + throw new TypeError('Invalid Version: ' + version); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') + + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num + } + return id; + }); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} + +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; + +SemVer.prototype.toString = function() { + return this.version; +}; + +SemVer.prototype.compare = function(other) { + debug('SemVer.compare', this.version, this.loose, other); + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); +}; + +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; + + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); +}; + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + this.raw = this.version; + return this; +}; + +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } +} + +exports.compareIdentifiers = compareIdentifiers; + +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} + +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} + +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} + +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} + +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} + +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(b); +} + +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} + +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} + +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} + +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} + +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} + +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} + +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} + +exports.Comparator = Comparator; +function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) + return comp; + else + comp = comp.value; + } + + if (!(this instanceof Comparator)) + return new Comparator(comp, loose); + + debug('comparator', comp, loose); + this.loose = loose; + this.parse(comp); + + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; + + debug('comp', this); +} + +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) + throw new TypeError('Invalid comparator: ' + comp); + + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.loose); +}; + +Comparator.prototype.toString = function() { + return this.value; +}; + +Comparator.prototype.test = function(version) { + debug('Comparator.test', version, this.loose); + + if (this.semver === ANY) + return true; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + return cmp(version, this.operator, this.semver, this.loose); +}; + + +exports.Range = Range; +function Range(range, loose) { + if ((range instanceof Range) && range.loose === loose) + return range; + + if (!(this instanceof Range)) + return new Range(range, loose); + + this.loose = loose; + + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function() { + return this.range; +}; + +Range.prototype.parseRange = function(range) { + var loose = this.loose; + range = range.trim(); + debug('range', range, loose); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, loose); + }); + + return set; +}; + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, loose) { + return new Range(range, loose).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, loose) { + debug('comp', comp); + comp = replaceCarets(comp, loose); + debug('caret', comp); + comp = replaceTildes(comp, loose); + debug('tildes', comp); + comp = replaceXRanges(comp, loose); + debug('xrange', comp); + comp = replaceStars(comp, loose); + debug('stars', comp); + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, loose); + }).join(' '); +} + +function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0- <1.3.0- + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + + debug('tilde return', ret); + return ret; + }); +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, loose); + }).join(' '); +} + +function replaceCaret(comp, loose) { + debug('caret', comp, loose); + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + + debug('caret return', ret); + return ret; + }); +} + +function replaceXRanges(comp, loose) { + debug('replaceXRanges', comp, loose); + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, loose); + }).join(' '); +} + +function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) + gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) + M = +M + 1 + else + m = +m + 1 + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + + return ret; + }); +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, loose) { + debug('replaceStars', comp, loose); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; + + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; + + return (from + ' ' + to).trim(); +} + + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) + return true; + } + return false; +}; + +function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } + + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) + continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false; + } + + return true; +} + +exports.satisfies = satisfies; +function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, loose) { + return versions.filter(function(version) { + return satisfies(version, range, loose); + }).sort(function(a, b) { + return rcompare(a, b, loose); + })[0] || null; +} + +exports.validRange = validRange; +function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, loose) { + return outside(version, range, '<', loose); +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, loose) { + return outside(version, range, '>', loose); +} + +exports.outside = outside; +function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, loose)) { + return false; + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/big-numbers.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/big-numbers.js new file mode 100644 index 0000000..c051864 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/big-numbers.js @@ -0,0 +1,31 @@ +var test = require('tap').test +var semver = require('../') + +test('long version is too long', function (t) { + var v = '1.2.' + new Array(256).join('1') + t.throws(function () { + new semver.SemVer(v) + }) + t.equal(semver.valid(v, false), null) + t.equal(semver.valid(v, true), null) + t.equal(semver.inc(v, 'patch'), null) + t.end() +}) + +test('big number is like too long version', function (t) { + var v = '1.2.' + new Array(100).join('1') + t.throws(function () { + new semver.SemVer(v) + }) + t.equal(semver.valid(v, false), null) + t.equal(semver.valid(v, true), null) + t.equal(semver.inc(v, 'patch'), null) + t.end() +}) + +test('parsing null does not throw', function (t) { + t.equal(semver.parse(null), null) + t.equal(semver.parse({}), null) + t.equal(semver.parse(new semver.SemVer('1.2.3')).version, '1.2.3') + t.end() +}) diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/clean.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/clean.js new file mode 100644 index 0000000..9e268de --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/clean.js @@ -0,0 +1,29 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var clean = semver.clean; + +test('\nclean tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.2.3', '1.2.3'], + [' 1.2.3 ', '1.2.3'], + [' 1.2.3-4 ', '1.2.3-4'], + [' 1.2.3-pre ', '1.2.3-pre'], + [' =v1.2.3 ', '1.2.3'], + ['v1.2.3', '1.2.3'], + [' v1.2.3 ', '1.2.3'], + ['\t1.2.3', '1.2.3'], + ['>1.2.3', null], + ['~1.2.3', null], + ['<=1.2.3', null], + ['1.2.x', null] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var msg = 'clean(' + range + ') = ' + version; + t.equal(clean(range), version, msg); + }); + t.end(); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/gtr.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/gtr.js new file mode 100644 index 0000000..bbb8789 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/gtr.js @@ -0,0 +1,173 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var gtr = semver.gtr; + +test('\ngtr tests', function(t) { + // [range, version, loose] + // Version should be greater than range + [ + ['~1.2.2', '1.3.0'], + ['~0.6.1-1', '0.7.1-1'], + ['1.0.0 - 2.0.0', '2.0.1'], + ['1.0.0', '1.0.1-beta1'], + ['1.0.0', '2.0.0'], + ['<=2.0.0', '2.1.1'], + ['<=2.0.0', '3.2.9'], + ['<2.0.0', '2.0.0'], + ['0.1.20 || 1.2.4', '1.2.5'], + ['2.x.x', '3.0.0'], + ['1.2.x', '1.3.0'], + ['1.2.x || 2.x', '3.0.0'], + ['2.*.*', '5.0.1'], + ['1.2.*', '1.3.3'], + ['1.2.* || 2.*', '4.0.0'], + ['2', '3.0.0'], + ['2.3', '2.4.2'], + ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.5.5'], + ['~>3.2.1', '3.3.0'], // >=3.2.1 <3.3.0 + ['~1', '2.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '2.2.4'], + ['~> 1', '3.2.3'], + ['~1.0', '1.1.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '1.1.0'], + ['<1.2', '1.2.0'], + ['< 1.2', '1.2.1'], + ['1', '2.0.0beta', true], + ['~v0.5.4-pre', '0.6.0'], + ['~v0.5.4-pre', '0.6.1-pre'], + ['=0.7.x', '0.8.0'], + ['=0.7.x', '0.8.0-asdf'], + ['<0.7.x', '0.7.0'], + ['~1.2.2', '1.3.0'], + ['1.0.0 - 2.0.0', '2.2.3'], + ['1.0.0', '1.0.1'], + ['<=2.0.0', '3.0.0'], + ['<=2.0.0', '2.9999.9999'], + ['<=2.0.0', '2.2.9'], + ['<2.0.0', '2.9999.9999'], + ['<2.0.0', '2.2.9'], + ['2.x.x', '3.1.3'], + ['1.2.x', '1.3.3'], + ['1.2.x || 2.x', '3.1.3'], + ['2.*.*', '3.1.3'], + ['1.2.*', '1.3.3'], + ['1.2.* || 2.*', '3.1.3'], + ['2', '3.1.2'], + ['2.3', '2.4.1'], + ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 + ['~>3.2.1', '3.3.2'], // >=3.2.1 <3.3.0 + ['~1', '2.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '2.2.3'], + ['~1.0', '1.1.0'], // >=1.0.0 <1.1.0 + ['<1', '1.0.0'], + ['1', '2.0.0beta', true], + ['<1', '1.0.0beta', true], + ['< 1', '1.0.0beta', true], + ['=0.7.x', '0.8.2'], + ['<0.7.x', '0.7.2'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'gtr(' + version + ', ' + range + ', ' + loose + ')'; + t.ok(gtr(version, range, loose), msg); + }); + t.end(); +}); + +test('\nnegative gtr tests', function(t) { + // [range, version, loose] + // Version should NOT be greater than range + [ + ['~0.6.1-1', '0.6.1-1'], + ['1.0.0 - 2.0.0', '1.2.3'], + ['1.0.0 - 2.0.0', '0.9.9'], + ['1.0.0', '1.0.0'], + ['>=*', '0.2.4'], + ['', '1.0.0', true], + ['*', '1.2.3'], + ['*', 'v1.2.3-foo'], + ['>=1.0.0', '1.0.0'], + ['>=1.0.0', '1.0.1'], + ['>=1.0.0', '1.1.0'], + ['>1.0.0', '1.0.1'], + ['>1.0.0', '1.1.0'], + ['<=2.0.0', '2.0.0'], + ['<=2.0.0', '1.9999.9999'], + ['<=2.0.0', '0.2.9'], + ['<2.0.0', '1.9999.9999'], + ['<2.0.0', '0.2.9'], + ['>= 1.0.0', '1.0.0'], + ['>= 1.0.0', '1.0.1'], + ['>= 1.0.0', '1.1.0'], + ['> 1.0.0', '1.0.1'], + ['> 1.0.0', '1.1.0'], + ['<= 2.0.0', '2.0.0'], + ['<= 2.0.0', '1.9999.9999'], + ['<= 2.0.0', '0.2.9'], + ['< 2.0.0', '1.9999.9999'], + ['<\t2.0.0', '0.2.9'], + ['>=0.1.97', 'v0.1.97'], + ['>=0.1.97', '0.1.97'], + ['0.1.20 || 1.2.4', '1.2.4'], + ['0.1.20 || >1.2.4', '1.2.4'], + ['0.1.20 || 1.2.4', '1.2.3'], + ['0.1.20 || 1.2.4', '0.1.20'], + ['>=0.2.3 || <0.0.1', '0.0.0'], + ['>=0.2.3 || <0.0.1', '0.2.3'], + ['>=0.2.3 || <0.0.1', '0.2.4'], + ['||', '1.3.4'], + ['2.x.x', '2.1.3'], + ['1.2.x', '1.2.3'], + ['1.2.x || 2.x', '2.1.3'], + ['1.2.x || 2.x', '1.2.3'], + ['x', '1.2.3'], + ['2.*.*', '2.1.3'], + ['1.2.*', '1.2.3'], + ['1.2.* || 2.*', '2.1.3'], + ['1.2.* || 2.*', '1.2.3'], + ['1.2.* || 2.*', '1.2.3'], + ['*', '1.2.3'], + ['2', '2.1.2'], + ['2.3', '2.3.1'], + ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.4.5'], + ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0 + ['~1', '1.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '1.2.3'], + ['~> 1', '1.2.3'], + ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '1.0.2'], + ['>=1', '1.0.0'], + ['>= 1', '1.0.0'], + ['<1.2', '1.1.1'], + ['< 1.2', '1.1.1'], + ['1', '1.0.0beta', true], + ['~v0.5.4-pre', '0.5.5'], + ['~v0.5.4-pre', '0.5.4'], + ['=0.7.x', '0.7.2'], + ['>=0.7.x', '0.7.2'], + ['=0.7.x', '0.7.0-asdf'], + ['>=0.7.x', '0.7.0-asdf'], + ['<=0.7.x', '0.6.2'], + ['>0.2.3 >0.2.4 <=0.2.5', '0.2.5'], + ['>=0.2.3 <=0.2.4', '0.2.4'], + ['1.0.0 - 2.0.0', '2.0.0'], + ['^1', '0.0.0-0'], + ['^3.0.0', '2.0.0'], + ['^1.0.0 || ~2.0.1', '2.0.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '3.2.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '1.0.0beta', true], + ['^0.1.0 || ~3.0.1 || 5.0.0', '5.0.0-0', true], + ['^0.1.0 || ~3.0.1 || >4 <=5.0.0', '3.5.0'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = '!gtr(' + version + ', ' + range + ', ' + loose + ')'; + t.notOk(gtr(version, range, loose), msg); + }); + t.end(); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/index.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/index.js new file mode 100644 index 0000000..47c3f5f --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/index.js @@ -0,0 +1,698 @@ +'use strict'; + +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var eq = semver.eq; +var gt = semver.gt; +var lt = semver.lt; +var neq = semver.neq; +var cmp = semver.cmp; +var gte = semver.gte; +var lte = semver.lte; +var satisfies = semver.satisfies; +var validRange = semver.validRange; +var inc = semver.inc; +var diff = semver.diff; +var replaceStars = semver.replaceStars; +var toComparators = semver.toComparators; +var SemVer = semver.SemVer; +var Range = semver.Range; + +test('\ncomparison tests', function(t) { + // [version1, version2] + // version1 should be greater than version2 + [['0.0.0', '0.0.0-foo'], + ['0.0.1', '0.0.0'], + ['1.0.0', '0.9.9'], + ['0.10.0', '0.9.0'], + ['0.99.0', '0.10.0'], + ['2.0.0', '1.2.3'], + ['v0.0.0', '0.0.0-foo', true], + ['v0.0.1', '0.0.0', true], + ['v1.0.0', '0.9.9', true], + ['v0.10.0', '0.9.0', true], + ['v0.99.0', '0.10.0', true], + ['v2.0.0', '1.2.3', true], + ['0.0.0', 'v0.0.0-foo', true], + ['0.0.1', 'v0.0.0', true], + ['1.0.0', 'v0.9.9', true], + ['0.10.0', 'v0.9.0', true], + ['0.99.0', 'v0.10.0', true], + ['2.0.0', 'v1.2.3', true], + ['1.2.3', '1.2.3-asdf'], + ['1.2.3', '1.2.3-4'], + ['1.2.3', '1.2.3-4-foo'], + ['1.2.3-5-foo', '1.2.3-5'], + ['1.2.3-5', '1.2.3-4'], + ['1.2.3-5-foo', '1.2.3-5-Foo'], + ['3.0.0', '2.7.2+asdf'], + ['1.2.3-a.10', '1.2.3-a.5'], + ['1.2.3-a.b', '1.2.3-a.5'], + ['1.2.3-a.b', '1.2.3-a'], + ['1.2.3-a.b.c.10.d.5', '1.2.3-a.b.c.5.d.100'], + ['1.2.3-r2', '1.2.3-r100'], + ['1.2.3-r100', '1.2.3-R2'] + ].forEach(function(v) { + var v0 = v[0]; + var v1 = v[1]; + var loose = v[2]; + t.ok(gt(v0, v1, loose), "gt('" + v0 + "', '" + v1 + "')"); + t.ok(lt(v1, v0, loose), "lt('" + v1 + "', '" + v0 + "')"); + t.ok(!gt(v1, v0, loose), "!gt('" + v1 + "', '" + v0 + "')"); + t.ok(!lt(v0, v1, loose), "!lt('" + v0 + "', '" + v1 + "')"); + t.ok(eq(v0, v0, loose), "eq('" + v0 + "', '" + v0 + "')"); + t.ok(eq(v1, v1, loose), "eq('" + v1 + "', '" + v1 + "')"); + t.ok(neq(v0, v1, loose), "neq('" + v0 + "', '" + v1 + "')"); + t.ok(cmp(v1, '==', v1, loose), "cmp('" + v1 + "' == '" + v1 + "')"); + t.ok(cmp(v0, '>=', v1, loose), "cmp('" + v0 + "' >= '" + v1 + "')"); + t.ok(cmp(v1, '<=', v0, loose), "cmp('" + v1 + "' <= '" + v0 + "')"); + t.ok(cmp(v0, '!=', v1, loose), "cmp('" + v0 + "' != '" + v1 + "')"); + }); + t.end(); +}); + +test('\nequality tests', function(t) { + // [version1, version2] + // version1 should be equivalent to version2 + [['1.2.3', 'v1.2.3', true], + ['1.2.3', '=1.2.3', true], + ['1.2.3', 'v 1.2.3', true], + ['1.2.3', '= 1.2.3', true], + ['1.2.3', ' v1.2.3', true], + ['1.2.3', ' =1.2.3', true], + ['1.2.3', ' v 1.2.3', true], + ['1.2.3', ' = 1.2.3', true], + ['1.2.3-0', 'v1.2.3-0', true], + ['1.2.3-0', '=1.2.3-0', true], + ['1.2.3-0', 'v 1.2.3-0', true], + ['1.2.3-0', '= 1.2.3-0', true], + ['1.2.3-0', ' v1.2.3-0', true], + ['1.2.3-0', ' =1.2.3-0', true], + ['1.2.3-0', ' v 1.2.3-0', true], + ['1.2.3-0', ' = 1.2.3-0', true], + ['1.2.3-1', 'v1.2.3-1', true], + ['1.2.3-1', '=1.2.3-1', true], + ['1.2.3-1', 'v 1.2.3-1', true], + ['1.2.3-1', '= 1.2.3-1', true], + ['1.2.3-1', ' v1.2.3-1', true], + ['1.2.3-1', ' =1.2.3-1', true], + ['1.2.3-1', ' v 1.2.3-1', true], + ['1.2.3-1', ' = 1.2.3-1', true], + ['1.2.3-beta', 'v1.2.3-beta', true], + ['1.2.3-beta', '=1.2.3-beta', true], + ['1.2.3-beta', 'v 1.2.3-beta', true], + ['1.2.3-beta', '= 1.2.3-beta', true], + ['1.2.3-beta', ' v1.2.3-beta', true], + ['1.2.3-beta', ' =1.2.3-beta', true], + ['1.2.3-beta', ' v 1.2.3-beta', true], + ['1.2.3-beta', ' = 1.2.3-beta', true], + ['1.2.3-beta+build', ' = 1.2.3-beta+otherbuild', true], + ['1.2.3+build', ' = 1.2.3+otherbuild', true], + ['1.2.3-beta+build', '1.2.3-beta+otherbuild'], + ['1.2.3+build', '1.2.3+otherbuild'], + [' v1.2.3+build', '1.2.3+otherbuild'] + ].forEach(function(v) { + var v0 = v[0]; + var v1 = v[1]; + var loose = v[2]; + t.ok(eq(v0, v1, loose), "eq('" + v0 + "', '" + v1 + "')"); + t.ok(!neq(v0, v1, loose), "!neq('" + v0 + "', '" + v1 + "')"); + t.ok(cmp(v0, '==', v1, loose), 'cmp(' + v0 + '==' + v1 + ')'); + t.ok(!cmp(v0, '!=', v1, loose), '!cmp(' + v0 + '!=' + v1 + ')'); + t.ok(!cmp(v0, '===', v1, loose), '!cmp(' + v0 + '===' + v1 + ')'); + t.ok(cmp(v0, '!==', v1, loose), 'cmp(' + v0 + '!==' + v1 + ')'); + t.ok(!gt(v0, v1, loose), "!gt('" + v0 + "', '" + v1 + "')"); + t.ok(gte(v0, v1, loose), "gte('" + v0 + "', '" + v1 + "')"); + t.ok(!lt(v0, v1, loose), "!lt('" + v0 + "', '" + v1 + "')"); + t.ok(lte(v0, v1, loose), "lte('" + v0 + "', '" + v1 + "')"); + }); + t.end(); +}); + + +test('\nrange tests', function(t) { + // [range, version] + // version should be included by range + [['1.0.0 - 2.0.0', '1.2.3'], + ['^1.2.3+build', '1.2.3'], + ['^1.2.3+build', '1.3.0'], + ['1.2.3-pre+asdf - 2.4.3-pre+asdf', '1.2.3'], + ['1.2.3pre+asdf - 2.4.3-pre+asdf', '1.2.3', true], + ['1.2.3-pre+asdf - 2.4.3pre+asdf', '1.2.3', true], + ['1.2.3pre+asdf - 2.4.3pre+asdf', '1.2.3', true], + ['1.2.3-pre+asdf - 2.4.3-pre+asdf', '1.2.3-pre.2'], + ['1.2.3-pre+asdf - 2.4.3-pre+asdf', '2.4.3-alpha'], + ['1.2.3+asdf - 2.4.3+asdf', '1.2.3'], + ['1.0.0', '1.0.0'], + ['>=*', '0.2.4'], + ['', '1.0.0'], + ['*', '1.2.3'], + ['*', 'v1.2.3', true], + ['>=1.0.0', '1.0.0'], + ['>=1.0.0', '1.0.1'], + ['>=1.0.0', '1.1.0'], + ['>1.0.0', '1.0.1'], + ['>1.0.0', '1.1.0'], + ['<=2.0.0', '2.0.0'], + ['<=2.0.0', '1.9999.9999'], + ['<=2.0.0', '0.2.9'], + ['<2.0.0', '1.9999.9999'], + ['<2.0.0', '0.2.9'], + ['>= 1.0.0', '1.0.0'], + ['>= 1.0.0', '1.0.1'], + ['>= 1.0.0', '1.1.0'], + ['> 1.0.0', '1.0.1'], + ['> 1.0.0', '1.1.0'], + ['<= 2.0.0', '2.0.0'], + ['<= 2.0.0', '1.9999.9999'], + ['<= 2.0.0', '0.2.9'], + ['< 2.0.0', '1.9999.9999'], + ['<\t2.0.0', '0.2.9'], + ['>=0.1.97', 'v0.1.97', true], + ['>=0.1.97', '0.1.97'], + ['0.1.20 || 1.2.4', '1.2.4'], + ['>=0.2.3 || <0.0.1', '0.0.0'], + ['>=0.2.3 || <0.0.1', '0.2.3'], + ['>=0.2.3 || <0.0.1', '0.2.4'], + ['||', '1.3.4'], + ['2.x.x', '2.1.3'], + ['1.2.x', '1.2.3'], + ['1.2.x || 2.x', '2.1.3'], + ['1.2.x || 2.x', '1.2.3'], + ['x', '1.2.3'], + ['2.*.*', '2.1.3'], + ['1.2.*', '1.2.3'], + ['1.2.* || 2.*', '2.1.3'], + ['1.2.* || 2.*', '1.2.3'], + ['*', '1.2.3'], + ['2', '2.1.2'], + ['2.3', '2.3.1'], + ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.4.5'], + ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0, + ['~1', '1.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '1.2.3'], + ['~> 1', '1.2.3'], + ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0, + ['~ 1.0', '1.0.2'], + ['~ 1.0.3', '1.0.12'], + ['>=1', '1.0.0'], + ['>= 1', '1.0.0'], + ['<1.2', '1.1.1'], + ['< 1.2', '1.1.1'], + ['~v0.5.4-pre', '0.5.5'], + ['~v0.5.4-pre', '0.5.4'], + ['=0.7.x', '0.7.2'], + ['<=0.7.x', '0.7.2'], + ['>=0.7.x', '0.7.2'], + ['<=0.7.x', '0.6.2'], + ['~1.2.1 >=1.2.3', '1.2.3'], + ['~1.2.1 =1.2.3', '1.2.3'], + ['~1.2.1 1.2.3', '1.2.3'], + ['~1.2.1 >=1.2.3 1.2.3', '1.2.3'], + ['~1.2.1 1.2.3 >=1.2.3', '1.2.3'], + ['~1.2.1 1.2.3', '1.2.3'], + ['>=1.2.1 1.2.3', '1.2.3'], + ['1.2.3 >=1.2.1', '1.2.3'], + ['>=1.2.3 >=1.2.1', '1.2.3'], + ['>=1.2.1 >=1.2.3', '1.2.3'], + ['>=1.2', '1.2.8'], + ['^1.2.3', '1.8.1'], + ['^0.1.2', '0.1.2'], + ['^0.1', '0.1.2'], + ['^1.2', '1.4.2'], + ['^1.2 ^1', '1.4.2'], + ['^1.2.3-alpha', '1.2.3-pre'], + ['^1.2.0-alpha', '1.2.0-pre'], + ['^0.0.1-alpha', '0.0.1-beta'] + ].forEach(function(v) { + var range = v[0]; + var ver = v[1]; + var loose = v[2]; + t.ok(satisfies(ver, range, loose), range + ' satisfied by ' + ver); + }); + t.end(); +}); + +test('\nnegative range tests', function(t) { + // [range, version] + // version should not be included by range + [['1.0.0 - 2.0.0', '2.2.3'], + ['1.2.3+asdf - 2.4.3+asdf', '1.2.3-pre.2'], + ['1.2.3+asdf - 2.4.3+asdf', '2.4.3-alpha'], + ['^1.2.3+build', '2.0.0'], + ['^1.2.3+build', '1.2.0'], + ['^1.2.3', '1.2.3-pre'], + ['^1.2', '1.2.0-pre'], + ['>1.2', '1.3.0-beta'], + ['<=1.2.3', '1.2.3-beta'], + ['^1.2.3', '1.2.3-beta'], + ['=0.7.x', '0.7.0-asdf'], + ['>=0.7.x', '0.7.0-asdf'], + ['1', '1.0.0beta', true], + ['<1', '1.0.0beta', true], + ['< 1', '1.0.0beta', true], + ['1.0.0', '1.0.1'], + ['>=1.0.0', '0.0.0'], + ['>=1.0.0', '0.0.1'], + ['>=1.0.0', '0.1.0'], + ['>1.0.0', '0.0.1'], + ['>1.0.0', '0.1.0'], + ['<=2.0.0', '3.0.0'], + ['<=2.0.0', '2.9999.9999'], + ['<=2.0.0', '2.2.9'], + ['<2.0.0', '2.9999.9999'], + ['<2.0.0', '2.2.9'], + ['>=0.1.97', 'v0.1.93', true], + ['>=0.1.97', '0.1.93'], + ['0.1.20 || 1.2.4', '1.2.3'], + ['>=0.2.3 || <0.0.1', '0.0.3'], + ['>=0.2.3 || <0.0.1', '0.2.2'], + ['2.x.x', '1.1.3'], + ['2.x.x', '3.1.3'], + ['1.2.x', '1.3.3'], + ['1.2.x || 2.x', '3.1.3'], + ['1.2.x || 2.x', '1.1.3'], + ['2.*.*', '1.1.3'], + ['2.*.*', '3.1.3'], + ['1.2.*', '1.3.3'], + ['1.2.* || 2.*', '3.1.3'], + ['1.2.* || 2.*', '1.1.3'], + ['2', '1.1.2'], + ['2.3', '2.4.1'], + ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.3.9'], + ['~>3.2.1', '3.3.2'], // >=3.2.1 <3.3.0 + ['~>3.2.1', '3.2.0'], // >=3.2.1 <3.3.0 + ['~1', '0.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '2.2.3'], + ['~1.0', '1.1.0'], // >=1.0.0 <1.1.0 + ['<1', '1.0.0'], + ['>=1.2', '1.1.1'], + ['1', '2.0.0beta', true], + ['~v0.5.4-beta', '0.5.4-alpha'], + ['=0.7.x', '0.8.2'], + ['>=0.7.x', '0.6.2'], + ['<0.7.x', '0.7.2'], + ['<1.2.3', '1.2.3-beta'], + ['=1.2.3', '1.2.3-beta'], + ['>1.2', '1.2.8'], + ['^1.2.3', '2.0.0-alpha'], + ['^1.2.3', '1.2.2'], + ['^1.2', '1.1.9'], + ['*', 'v1.2.3-foo', true], + // invalid ranges never satisfied! + ['blerg', '1.2.3'], + ['git+https://user:password0123@github.com/foo', '123.0.0', true], + ['^1.2.3', '2.0.0-pre'] + ].forEach(function(v) { + var range = v[0]; + var ver = v[1]; + var loose = v[2]; + var found = satisfies(ver, range, loose); + t.ok(!found, ver + ' not satisfied by ' + range); + }); + t.end(); +}); + +test('\nincrement versions test', function(t) { +// [version, inc, result, identifier] +// inc(version, inc) -> result + [['1.2.3', 'major', '2.0.0'], + ['1.2.3', 'minor', '1.3.0'], + ['1.2.3', 'patch', '1.2.4'], + ['1.2.3tag', 'major', '2.0.0', true], + ['1.2.3-tag', 'major', '2.0.0'], + ['1.2.3', 'fake', null], + ['1.2.0-0', 'patch', '1.2.0'], + ['fake', 'major', null], + ['1.2.3-4', 'major', '2.0.0'], + ['1.2.3-4', 'minor', '1.3.0'], + ['1.2.3-4', 'patch', '1.2.3'], + ['1.2.3-alpha.0.beta', 'major', '2.0.0'], + ['1.2.3-alpha.0.beta', 'minor', '1.3.0'], + ['1.2.3-alpha.0.beta', 'patch', '1.2.3'], + ['1.2.4', 'prerelease', '1.2.5-0'], + ['1.2.3-0', 'prerelease', '1.2.3-1'], + ['1.2.3-alpha.0', 'prerelease', '1.2.3-alpha.1'], + ['1.2.3-alpha.1', 'prerelease', '1.2.3-alpha.2'], + ['1.2.3-alpha.2', 'prerelease', '1.2.3-alpha.3'], + ['1.2.3-alpha.0.beta', 'prerelease', '1.2.3-alpha.1.beta'], + ['1.2.3-alpha.1.beta', 'prerelease', '1.2.3-alpha.2.beta'], + ['1.2.3-alpha.2.beta', 'prerelease', '1.2.3-alpha.3.beta'], + ['1.2.3-alpha.10.0.beta', 'prerelease', '1.2.3-alpha.10.1.beta'], + ['1.2.3-alpha.10.1.beta', 'prerelease', '1.2.3-alpha.10.2.beta'], + ['1.2.3-alpha.10.2.beta', 'prerelease', '1.2.3-alpha.10.3.beta'], + ['1.2.3-alpha.10.beta.0', 'prerelease', '1.2.3-alpha.10.beta.1'], + ['1.2.3-alpha.10.beta.1', 'prerelease', '1.2.3-alpha.10.beta.2'], + ['1.2.3-alpha.10.beta.2', 'prerelease', '1.2.3-alpha.10.beta.3'], + ['1.2.3-alpha.9.beta', 'prerelease', '1.2.3-alpha.10.beta'], + ['1.2.3-alpha.10.beta', 'prerelease', '1.2.3-alpha.11.beta'], + ['1.2.3-alpha.11.beta', 'prerelease', '1.2.3-alpha.12.beta'], + ['1.2.0', 'prepatch', '1.2.1-0'], + ['1.2.0-1', 'prepatch', '1.2.1-0'], + ['1.2.0', 'preminor', '1.3.0-0'], + ['1.2.3-1', 'preminor', '1.3.0-0'], + ['1.2.0', 'premajor', '2.0.0-0'], + ['1.2.3-1', 'premajor', '2.0.0-0'], + ['1.2.0-1', 'minor', '1.2.0'], + ['1.0.0-1', 'major', '1.0.0'], + + ['1.2.3', 'major', '2.0.0', false, 'dev'], + ['1.2.3', 'minor', '1.3.0', false, 'dev'], + ['1.2.3', 'patch', '1.2.4', false, 'dev'], + ['1.2.3tag', 'major', '2.0.0', true, 'dev'], + ['1.2.3-tag', 'major', '2.0.0', false, 'dev'], + ['1.2.3', 'fake', null, false, 'dev'], + ['1.2.0-0', 'patch', '1.2.0', false, 'dev'], + ['fake', 'major', null, false, 'dev'], + ['1.2.3-4', 'major', '2.0.0', false, 'dev'], + ['1.2.3-4', 'minor', '1.3.0', false, 'dev'], + ['1.2.3-4', 'patch', '1.2.3', false, 'dev'], + ['1.2.3-alpha.0.beta', 'major', '2.0.0', false, 'dev'], + ['1.2.3-alpha.0.beta', 'minor', '1.3.0', false, 'dev'], + ['1.2.3-alpha.0.beta', 'patch', '1.2.3', false, 'dev'], + ['1.2.4', 'prerelease', '1.2.5-dev.0', false, 'dev'], + ['1.2.3-0', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.0', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.0', 'prerelease', '1.2.3-alpha.1', false, 'alpha'], + ['1.2.3-alpha.0.beta', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.0.beta', 'prerelease', '1.2.3-alpha.1.beta', false, 'alpha'], + ['1.2.3-alpha.10.0.beta', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.10.0.beta', 'prerelease', '1.2.3-alpha.10.1.beta', false, 'alpha'], + ['1.2.3-alpha.10.1.beta', 'prerelease', '1.2.3-alpha.10.2.beta', false, 'alpha'], + ['1.2.3-alpha.10.2.beta', 'prerelease', '1.2.3-alpha.10.3.beta', false, 'alpha'], + ['1.2.3-alpha.10.beta.0', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.10.beta.0', 'prerelease', '1.2.3-alpha.10.beta.1', false, 'alpha'], + ['1.2.3-alpha.10.beta.1', 'prerelease', '1.2.3-alpha.10.beta.2', false, 'alpha'], + ['1.2.3-alpha.10.beta.2', 'prerelease', '1.2.3-alpha.10.beta.3', false, 'alpha'], + ['1.2.3-alpha.9.beta', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.9.beta', 'prerelease', '1.2.3-alpha.10.beta', false, 'alpha'], + ['1.2.3-alpha.10.beta', 'prerelease', '1.2.3-alpha.11.beta', false, 'alpha'], + ['1.2.3-alpha.11.beta', 'prerelease', '1.2.3-alpha.12.beta', false, 'alpha'], + ['1.2.0', 'prepatch', '1.2.1-dev.0', false, 'dev'], + ['1.2.0-1', 'prepatch', '1.2.1-dev.0', false, 'dev'], + ['1.2.0', 'preminor', '1.3.0-dev.0', false, 'dev'], + ['1.2.3-1', 'preminor', '1.3.0-dev.0', false, 'dev'], + ['1.2.0', 'premajor', '2.0.0-dev.0', false, 'dev'], + ['1.2.3-1', 'premajor', '2.0.0-dev.0', false, 'dev'], + ['1.2.0-1', 'minor', '1.2.0', false, 'dev'], + ['1.0.0-1', 'major', '1.0.0', false, 'dev'], + ['1.2.3-dev.bar', 'prerelease', '1.2.3-dev.0', false, 'dev'] + + ].forEach(function(v) { + var pre = v[0]; + var what = v[1]; + var wanted = v[2]; + var loose = v[3]; + var id = v[4]; + var found = inc(pre, what, loose, id); + var cmd = 'inc(' + pre + ', ' + what + ', ' + id + ')'; + t.equal(found, wanted, cmd + ' === ' + wanted); + + var parsed = semver.parse(pre, loose); + if (wanted) { + parsed.inc(what, id); + t.equal(parsed.version, wanted, cmd + ' object version updated'); + t.equal(parsed.raw, wanted, cmd + ' object raw field updated'); + } else if (parsed) { + t.throws(function () { + parsed.inc(what, id) + }) + } else { + t.equal(parsed, null) + } + }); + + t.end(); +}); + +test('\ndiff versions test', function(t) { +// [version1, version2, result] +// diff(version1, version2) -> result + [['1.2.3', '0.2.3', 'major'], + ['1.4.5', '0.2.3', 'major'], + ['1.2.3', '2.0.0-pre', 'premajor'], + ['1.2.3', '1.3.3', 'minor'], + ['1.0.1', '1.1.0-pre', 'preminor'], + ['1.2.3', '1.2.4', 'patch'], + ['1.2.3', '1.2.4-pre', 'prepatch'], + ['0.0.1', '0.0.1-pre', 'prerelease'], + ['0.0.1', '0.0.1-pre-2', 'prerelease'], + ['1.1.0', '1.1.0-pre', 'prerelease'], + ['1.1.0-pre-1', '1.1.0-pre-2', 'prerelease'], + ['1.0.0', '1.0.0', null] + + ].forEach(function(v) { + var version1 = v[0]; + var version2 = v[1]; + var wanted = v[2]; + var found = diff(version1, version2); + var cmd = 'diff(' + version1 + ', ' + version2 + ')'; + t.equal(found, wanted, cmd + ' === ' + wanted); + }); + + t.end(); +}); + +test('\nvalid range test', function(t) { + // [range, result] + // validRange(range) -> result + // translate ranges into their canonical form + [['1.0.0 - 2.0.0', '>=1.0.0 <=2.0.0'], + ['1.0.0', '1.0.0'], + ['>=*', '*'], + ['', '*'], + ['*', '*'], + ['*', '*'], + ['>=1.0.0', '>=1.0.0'], + ['>1.0.0', '>1.0.0'], + ['<=2.0.0', '<=2.0.0'], + ['1', '>=1.0.0 <2.0.0'], + ['<=2.0.0', '<=2.0.0'], + ['<=2.0.0', '<=2.0.0'], + ['<2.0.0', '<2.0.0'], + ['<2.0.0', '<2.0.0'], + ['>= 1.0.0', '>=1.0.0'], + ['>= 1.0.0', '>=1.0.0'], + ['>= 1.0.0', '>=1.0.0'], + ['> 1.0.0', '>1.0.0'], + ['> 1.0.0', '>1.0.0'], + ['<= 2.0.0', '<=2.0.0'], + ['<= 2.0.0', '<=2.0.0'], + ['<= 2.0.0', '<=2.0.0'], + ['< 2.0.0', '<2.0.0'], + ['< 2.0.0', '<2.0.0'], + ['>=0.1.97', '>=0.1.97'], + ['>=0.1.97', '>=0.1.97'], + ['0.1.20 || 1.2.4', '0.1.20||1.2.4'], + ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1'], + ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1'], + ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1'], + ['||', '||'], + ['2.x.x', '>=2.0.0 <3.0.0'], + ['1.2.x', '>=1.2.0 <1.3.0'], + ['1.2.x || 2.x', '>=1.2.0 <1.3.0||>=2.0.0 <3.0.0'], + ['1.2.x || 2.x', '>=1.2.0 <1.3.0||>=2.0.0 <3.0.0'], + ['x', '*'], + ['2.*.*', '>=2.0.0 <3.0.0'], + ['1.2.*', '>=1.2.0 <1.3.0'], + ['1.2.* || 2.*', '>=1.2.0 <1.3.0||>=2.0.0 <3.0.0'], + ['*', '*'], + ['2', '>=2.0.0 <3.0.0'], + ['2.3', '>=2.3.0 <2.4.0'], + ['~2.4', '>=2.4.0 <2.5.0'], + ['~2.4', '>=2.4.0 <2.5.0'], + ['~>3.2.1', '>=3.2.1 <3.3.0'], + ['~1', '>=1.0.0 <2.0.0'], + ['~>1', '>=1.0.0 <2.0.0'], + ['~> 1', '>=1.0.0 <2.0.0'], + ['~1.0', '>=1.0.0 <1.1.0'], + ['~ 1.0', '>=1.0.0 <1.1.0'], + ['^0', '>=0.0.0 <1.0.0'], + ['^ 1', '>=1.0.0 <2.0.0'], + ['^0.1', '>=0.1.0 <0.2.0'], + ['^1.0', '>=1.0.0 <2.0.0'], + ['^1.2', '>=1.2.0 <2.0.0'], + ['^0.0.1', '>=0.0.1 <0.0.2'], + ['^0.0.1-beta', '>=0.0.1-beta <0.0.2'], + ['^0.1.2', '>=0.1.2 <0.2.0'], + ['^1.2.3', '>=1.2.3 <2.0.0'], + ['^1.2.3-beta.4', '>=1.2.3-beta.4 <2.0.0'], + ['<1', '<1.0.0'], + ['< 1', '<1.0.0'], + ['>=1', '>=1.0.0'], + ['>= 1', '>=1.0.0'], + ['<1.2', '<1.2.0'], + ['< 1.2', '<1.2.0'], + ['1', '>=1.0.0 <2.0.0'], + ['>01.02.03', '>1.2.3', true], + ['>01.02.03', null], + ['~1.2.3beta', '>=1.2.3-beta <1.3.0', true], + ['~1.2.3beta', null], + ['^ 1.2 ^ 1', '>=1.2.0 <2.0.0 >=1.0.0 <2.0.0'] + ].forEach(function(v) { + var pre = v[0]; + var wanted = v[1]; + var loose = v[2]; + var found = validRange(pre, loose); + + t.equal(found, wanted, 'validRange(' + pre + ') === ' + wanted); + }); + + t.end(); +}); + +test('\ncomparators test', function(t) { + // [range, comparators] + // turn range into a set of individual comparators + [['1.0.0 - 2.0.0', [['>=1.0.0', '<=2.0.0']]], + ['1.0.0', [['1.0.0']]], + ['>=*', [['']]], + ['', [['']]], + ['*', [['']]], + ['*', [['']]], + ['>=1.0.0', [['>=1.0.0']]], + ['>=1.0.0', [['>=1.0.0']]], + ['>=1.0.0', [['>=1.0.0']]], + ['>1.0.0', [['>1.0.0']]], + ['>1.0.0', [['>1.0.0']]], + ['<=2.0.0', [['<=2.0.0']]], + ['1', [['>=1.0.0', '<2.0.0']]], + ['<=2.0.0', [['<=2.0.0']]], + ['<=2.0.0', [['<=2.0.0']]], + ['<2.0.0', [['<2.0.0']]], + ['<2.0.0', [['<2.0.0']]], + ['>= 1.0.0', [['>=1.0.0']]], + ['>= 1.0.0', [['>=1.0.0']]], + ['>= 1.0.0', [['>=1.0.0']]], + ['> 1.0.0', [['>1.0.0']]], + ['> 1.0.0', [['>1.0.0']]], + ['<= 2.0.0', [['<=2.0.0']]], + ['<= 2.0.0', [['<=2.0.0']]], + ['<= 2.0.0', [['<=2.0.0']]], + ['< 2.0.0', [['<2.0.0']]], + ['<\t2.0.0', [['<2.0.0']]], + ['>=0.1.97', [['>=0.1.97']]], + ['>=0.1.97', [['>=0.1.97']]], + ['0.1.20 || 1.2.4', [['0.1.20'], ['1.2.4']]], + ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1']]], + ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1']]], + ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1']]], + ['||', [[''], ['']]], + ['2.x.x', [['>=2.0.0', '<3.0.0']]], + ['1.2.x', [['>=1.2.0', '<1.3.0']]], + ['1.2.x || 2.x', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['1.2.x || 2.x', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['x', [['']]], + ['2.*.*', [['>=2.0.0', '<3.0.0']]], + ['1.2.*', [['>=1.2.0', '<1.3.0']]], + ['1.2.* || 2.*', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['1.2.* || 2.*', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['*', [['']]], + ['2', [['>=2.0.0', '<3.0.0']]], + ['2.3', [['>=2.3.0', '<2.4.0']]], + ['~2.4', [['>=2.4.0', '<2.5.0']]], + ['~2.4', [['>=2.4.0', '<2.5.0']]], + ['~>3.2.1', [['>=3.2.1', '<3.3.0']]], + ['~1', [['>=1.0.0', '<2.0.0']]], + ['~>1', [['>=1.0.0', '<2.0.0']]], + ['~> 1', [['>=1.0.0', '<2.0.0']]], + ['~1.0', [['>=1.0.0', '<1.1.0']]], + ['~ 1.0', [['>=1.0.0', '<1.1.0']]], + ['~ 1.0.3', [['>=1.0.3', '<1.1.0']]], + ['~> 1.0.3', [['>=1.0.3', '<1.1.0']]], + ['<1', [['<1.0.0']]], + ['< 1', [['<1.0.0']]], + ['>=1', [['>=1.0.0']]], + ['>= 1', [['>=1.0.0']]], + ['<1.2', [['<1.2.0']]], + ['< 1.2', [['<1.2.0']]], + ['1', [['>=1.0.0', '<2.0.0']]], + ['1 2', [['>=1.0.0', '<2.0.0', '>=2.0.0', '<3.0.0']]], + ['1.2 - 3.4.5', [['>=1.2.0', '<=3.4.5']]], + ['1.2.3 - 3.4', [['>=1.2.3', '<3.5.0']]], + ['1.2.3 - 3', [['>=1.2.3', '<4.0.0']]], + ['>*', [['<0.0.0']]], + ['<*', [['<0.0.0']]] + ].forEach(function(v) { + var pre = v[0]; + var wanted = v[1]; + var found = toComparators(v[0]); + var jw = JSON.stringify(wanted); + t.equivalent(found, wanted, 'toComparators(' + pre + ') === ' + jw); + }); + + t.end(); +}); + +test('\ninvalid version numbers', function(t) { + ['1.2.3.4', + 'NOT VALID', + 1.2, + null, + 'Infinity.NaN.Infinity' + ].forEach(function(v) { + t.throws(function() { + new SemVer(v); + }, {name:'TypeError', message:'Invalid Version: ' + v}); + }); + + t.end(); +}); + +test('\nstrict vs loose version numbers', function(t) { + [['=1.2.3', '1.2.3'], + ['01.02.03', '1.2.3'], + ['1.2.3-beta.01', '1.2.3-beta.1'], + [' =1.2.3', '1.2.3'], + ['1.2.3foo', '1.2.3-foo'] + ].forEach(function(v) { + var loose = v[0]; + var strict = v[1]; + t.throws(function() { + new SemVer(loose); + }); + var lv = new SemVer(loose, true); + t.equal(lv.version, strict); + t.ok(eq(loose, strict, true)); + t.throws(function() { + eq(loose, strict); + }); + t.throws(function() { + new SemVer(strict).compare(loose); + }); + }); + t.end(); +}); + +test('\nstrict vs loose ranges', function(t) { + [['>=01.02.03', '>=1.2.3'], + ['~1.02.03beta', '>=1.2.3-beta <1.3.0'] + ].forEach(function(v) { + var loose = v[0]; + var comps = v[1]; + t.throws(function() { + new Range(loose); + }); + t.equal(new Range(loose, true).range, comps); + }); + t.end(); +}); + +test('\nmax satisfying', function(t) { + [[['1.2.3', '1.2.4'], '1.2', '1.2.4'], + [['1.2.4', '1.2.3'], '1.2', '1.2.4'], + [['1.2.3', '1.2.4', '1.2.5', '1.2.6'], '~1.2.3', '1.2.6'], + [['1.1.0', '1.2.0', '1.2.1', '1.3.0', '2.0.0b1', '2.0.0b2', '2.0.0b3', '2.0.0', '2.1.0'], '~2.0.0', '2.0.0', true] + ].forEach(function(v) { + var versions = v[0]; + var range = v[1]; + var expect = v[2]; + var loose = v[3]; + var actual = semver.maxSatisfying(versions, range, loose); + t.equal(actual, expect); + }); + t.end(); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/ltr.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/ltr.js new file mode 100644 index 0000000..0f7167d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/ltr.js @@ -0,0 +1,181 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var ltr = semver.ltr; + +test('\nltr tests', function(t) { + // [range, version, loose] + // Version should be less than range + [ + ['~1.2.2', '1.2.1'], + ['~0.6.1-1', '0.6.1-0'], + ['1.0.0 - 2.0.0', '0.0.1'], + ['1.0.0-beta.2', '1.0.0-beta.1'], + ['1.0.0', '0.0.0'], + ['>=2.0.0', '1.1.1'], + ['>=2.0.0', '1.2.9'], + ['>2.0.0', '2.0.0'], + ['0.1.20 || 1.2.4', '0.1.5'], + ['2.x.x', '1.0.0'], + ['1.2.x', '1.1.0'], + ['1.2.x || 2.x', '1.0.0'], + ['2.*.*', '1.0.1'], + ['1.2.*', '1.1.3'], + ['1.2.* || 2.*', '1.1.9999'], + ['2', '1.0.0'], + ['2.3', '2.2.2'], + ['~2.4', '2.3.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.3.5'], + ['~>3.2.1', '3.2.0'], // >=3.2.1 <3.3.0 + ['~1', '0.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '0.2.4'], + ['~> 1', '0.2.3'], + ['~1.0', '0.1.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '0.1.0'], + ['>1.2', '1.2.0'], + ['> 1.2', '1.2.1'], + ['1', '0.0.0beta', true], + ['~v0.5.4-pre', '0.5.4-alpha'], + ['~v0.5.4-pre', '0.5.4-alpha'], + ['=0.7.x', '0.6.0'], + ['=0.7.x', '0.6.0-asdf'], + ['>=0.7.x', '0.6.0'], + ['~1.2.2', '1.2.1'], + ['1.0.0 - 2.0.0', '0.2.3'], + ['1.0.0', '0.0.1'], + ['>=2.0.0', '1.0.0'], + ['>=2.0.0', '1.9999.9999'], + ['>=2.0.0', '1.2.9'], + ['>2.0.0', '2.0.0'], + ['>2.0.0', '1.2.9'], + ['2.x.x', '1.1.3'], + ['1.2.x', '1.1.3'], + ['1.2.x || 2.x', '1.1.3'], + ['2.*.*', '1.1.3'], + ['1.2.*', '1.1.3'], + ['1.2.* || 2.*', '1.1.3'], + ['2', '1.9999.9999'], + ['2.3', '2.2.1'], + ['~2.4', '2.3.0'], // >=2.4.0 <2.5.0 + ['~>3.2.1', '2.3.2'], // >=3.2.1 <3.3.0 + ['~1', '0.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '0.2.3'], + ['~1.0', '0.0.0'], // >=1.0.0 <1.1.0 + ['>1', '1.0.0'], + ['2', '1.0.0beta', true], + ['>1', '1.0.0beta', true], + ['> 1', '1.0.0beta', true], + ['=0.7.x', '0.6.2'], + ['=0.7.x', '0.7.0-asdf'], + ['^1', '1.0.0-0'], + ['>=0.7.x', '0.7.0-asdf'], + ['1', '1.0.0beta', true], + ['>=0.7.x', '0.6.2'], + ['>1.2.3', '1.3.0-alpha'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'ltr(' + version + ', ' + range + ', ' + loose + ')'; + t.ok(ltr(version, range, loose), msg); + }); + t.end(); +}); + +test('\nnegative ltr tests', function(t) { + // [range, version, loose] + // Version should NOT be less than range + [ + ['~ 1.0', '1.1.0'], + ['~0.6.1-1', '0.6.1-1'], + ['1.0.0 - 2.0.0', '1.2.3'], + ['1.0.0 - 2.0.0', '2.9.9'], + ['1.0.0', '1.0.0'], + ['>=*', '0.2.4'], + ['', '1.0.0', true], + ['*', '1.2.3'], + ['>=1.0.0', '1.0.0'], + ['>=1.0.0', '1.0.1'], + ['>=1.0.0', '1.1.0'], + ['>1.0.0', '1.0.1'], + ['>1.0.0', '1.1.0'], + ['<=2.0.0', '2.0.0'], + ['<=2.0.0', '1.9999.9999'], + ['<=2.0.0', '0.2.9'], + ['<2.0.0', '1.9999.9999'], + ['<2.0.0', '0.2.9'], + ['>= 1.0.0', '1.0.0'], + ['>= 1.0.0', '1.0.1'], + ['>= 1.0.0', '1.1.0'], + ['> 1.0.0', '1.0.1'], + ['> 1.0.0', '1.1.0'], + ['<= 2.0.0', '2.0.0'], + ['<= 2.0.0', '1.9999.9999'], + ['<= 2.0.0', '0.2.9'], + ['< 2.0.0', '1.9999.9999'], + ['<\t2.0.0', '0.2.9'], + ['>=0.1.97', 'v0.1.97'], + ['>=0.1.97', '0.1.97'], + ['0.1.20 || 1.2.4', '1.2.4'], + ['0.1.20 || >1.2.4', '1.2.4'], + ['0.1.20 || 1.2.4', '1.2.3'], + ['0.1.20 || 1.2.4', '0.1.20'], + ['>=0.2.3 || <0.0.1', '0.0.0'], + ['>=0.2.3 || <0.0.1', '0.2.3'], + ['>=0.2.3 || <0.0.1', '0.2.4'], + ['||', '1.3.4'], + ['2.x.x', '2.1.3'], + ['1.2.x', '1.2.3'], + ['1.2.x || 2.x', '2.1.3'], + ['1.2.x || 2.x', '1.2.3'], + ['x', '1.2.3'], + ['2.*.*', '2.1.3'], + ['1.2.*', '1.2.3'], + ['1.2.* || 2.*', '2.1.3'], + ['1.2.* || 2.*', '1.2.3'], + ['1.2.* || 2.*', '1.2.3'], + ['*', '1.2.3'], + ['2', '2.1.2'], + ['2.3', '2.3.1'], + ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.4.5'], + ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0 + ['~1', '1.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '1.2.3'], + ['~> 1', '1.2.3'], + ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '1.0.2'], + ['>=1', '1.0.0'], + ['>= 1', '1.0.0'], + ['<1.2', '1.1.1'], + ['< 1.2', '1.1.1'], + ['~v0.5.4-pre', '0.5.5'], + ['~v0.5.4-pre', '0.5.4'], + ['=0.7.x', '0.7.2'], + ['>=0.7.x', '0.7.2'], + ['<=0.7.x', '0.6.2'], + ['>0.2.3 >0.2.4 <=0.2.5', '0.2.5'], + ['>=0.2.3 <=0.2.4', '0.2.4'], + ['1.0.0 - 2.0.0', '2.0.0'], + ['^3.0.0', '4.0.0'], + ['^1.0.0 || ~2.0.1', '2.0.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '3.2.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '1.0.0beta', true], + ['^0.1.0 || ~3.0.1 || 5.0.0', '5.0.0-0', true], + ['^0.1.0 || ~3.0.1 || >4 <=5.0.0', '3.5.0'], + ['^1.0.0alpha', '1.0.0beta', true], + ['~1.0.0alpha', '1.0.0beta', true], + ['^1.0.0-alpha', '1.0.0beta', true], + ['~1.0.0-alpha', '1.0.0beta', true], + ['^1.0.0-alpha', '1.0.0-beta'], + ['~1.0.0-alpha', '1.0.0-beta'], + ['=0.1.0', '1.0.0'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = '!ltr(' + version + ', ' + range + ', ' + loose + ')'; + t.notOk(ltr(version, range, loose), msg); + }); + t.end(); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/major-minor-patch.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/major-minor-patch.js new file mode 100644 index 0000000..e9d4039 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/major-minor-patch.js @@ -0,0 +1,72 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); + +test('\nmajor tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.2.3', 1], + [' 1.2.3 ', 1], + [' 2.2.3-4 ', 2], + [' 3.2.3-pre ', 3], + ['v5.2.3', 5], + [' v8.2.3 ', 8], + ['\t13.2.3', 13], + ['=21.2.3', 21, true], + ['v=34.2.3', 34, true] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'major(' + range + ') = ' + version; + t.equal(semver.major(range, loose), version, msg); + }); + t.end(); +}); + +test('\nminor tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.1.3', 1], + [' 1.1.3 ', 1], + [' 1.2.3-4 ', 2], + [' 1.3.3-pre ', 3], + ['v1.5.3', 5], + [' v1.8.3 ', 8], + ['\t1.13.3', 13], + ['=1.21.3', 21, true], + ['v=1.34.3', 34, true] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'minor(' + range + ') = ' + version; + t.equal(semver.minor(range, loose), version, msg); + }); + t.end(); +}); + +test('\npatch tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.2.1', 1], + [' 1.2.1 ', 1], + [' 1.2.2-4 ', 2], + [' 1.2.3-pre ', 3], + ['v1.2.5', 5], + [' v1.2.8 ', 8], + ['\t1.2.13', 13], + ['=1.2.21', 21, true], + ['v=1.2.34', 34, true] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'patch(' + range + ') = ' + version; + t.equal(semver.patch(range, loose), version, msg); + }); + t.end(); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/package.json new file mode 100644 index 0000000..57bd9bd --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/package.json @@ -0,0 +1,68 @@ +{ + "name": "require_optional", + "version": "1.0.0", + "description": "Allows you declare optionalPeerDependencies that can be satisfied by the top level module but ignored if they are not.", + "main": "index.js", + "scripts": { + "test": "mocha" + }, + "repository": { + "type": "git", + "url": "https://github.com/christkv/require_optional.git" + }, + "keywords": [ + "optional", + "require", + "optionalPeerDependencies" + ], + "author": { + "name": "Christian Kvalheim Amor" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/christkv/require_optional/issues" + }, + "homepage": "https://github.com/christkv/require_optional", + "dependencies": { + "semver": "^5.1.0", + "resolve-from": "^2.0.0" + }, + "devDependencies": { + "bson": "0.4.21", + "co": "4.6.0", + "es6-promise": "^3.0.2", + "mocha": "^2.4.5" + }, + "peerOptionalDependencies": { + "co": ">=5.6.0", + "es6-promise": "^3.0.2", + "es6-promise2": "^4.0.2", + "bson": "0.4.21" + }, + "gitHead": "8eac964c8e31166a8fb483d0d56025b185cee03f", + "_id": "require_optional@1.0.0", + "_shasum": "52a86137a849728eb60a55533617f8f914f59abf", + "_from": "require_optional@>=1.0.0 <1.1.0", + "_npmVersion": "2.14.12", + "_nodeVersion": "4.2.4", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "52a86137a849728eb60a55533617f8f914f59abf", + "tarball": "http://registry.npmjs.org/require_optional/-/require_optional-1.0.0.tgz" + }, + "_npmOperationalInternal": { + "host": "packages-5-east.internal.npmjs.com", + "tmp": "tmp/require_optional-1.0.0.tgz_1454503936164_0.7571216486394405" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.0.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/test/require_optional_tests.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/test/require_optional_tests.js new file mode 100644 index 0000000..181d834 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/test/require_optional_tests.js @@ -0,0 +1,42 @@ +var assert = require('assert'), + require_optional = require('../'); + +describe('Require Optional', function() { + describe('top level require', function() { + it('should correctly require co library', function() { + var promise = require_optional('es6-promise'); + assert.ok(promise); + }); + + it('should fail to require es6-promise library', function() { + try { + require_optional('co'); + } catch(e) { + assert.equal('OPTIONAL_MODULE_NOT_FOUND', e.code); + return; + } + + assert.ok(false); + }); + + it('should ignore optional library not defined', function() { + assert.equal(undefined, require_optional('es6-promise2')); + }); + }); + + describe('internal module file require', function() { + it('should correctly require co library', function() { + var Long = require_optional('bson/lib/bson/long.js'); + assert.ok(Long); + }); + }); + + describe('top level resolve', function() { + it('should correctly use exists method', function() { + assert.equal(false, require_optional.exists('co')); + assert.equal(true, require_optional.exists('es6-promise')); + assert.equal(true, require_optional.exists('bson/lib/bson/long.js')); + assert.equal(false, require_optional.exists('es6-promise2')); + }); + }); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/package.json new file mode 100644 index 0000000..41e354b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/package.json @@ -0,0 +1,74 @@ +{ + "name": "mongodb-core", + "version": "1.3.1", + "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", + "main": "index.js", + "scripts": { + "test": "node test/runner.js -t functional", + "coverage": "nyc node test/runner.js -t functional && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls" + }, + "repository": { + "type": "git", + "url": "git://github.com/christkv/mongodb-core.git" + }, + "keywords": [ + "mongodb", + "core" + ], + "dependencies": { + "bson": "~0.4.21", + "require_optional": "~1.0.0" + }, + "devDependencies": { + "co": "4.5.4", + "coveralls": "^2.11.6", + "es6-promise": "^3.0.2", + "gleak": "0.5.0", + "integra": "0.1.8", + "jsdoc": "3.3.0-alpha8", + "mkdirp": "0.5.0", + "mongodb-topology-manager": "1.0.x", + "mongodb-version-manager": "^1.x", + "nyc": "^5.5.0", + "optimist": "latest", + "rimraf": "2.2.6", + "semver": "4.1.0" + }, + "peerOptionalDependencies": { + "kerberos": "~0.0" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/christkv/mongodb-core/issues" + }, + "homepage": "https://github.com/christkv/mongodb-core", + "gitHead": "c1308710fb5f091ddbf6c9e18cfa292d7e951dd5", + "_id": "mongodb-core@1.3.1", + "_shasum": "c504b45e42300741ebf0b4b1d12d3c1073994588", + "_from": "mongodb-core@1.3.1", + "_npmVersion": "2.14.12", + "_nodeVersion": "4.2.4", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "c504b45e42300741ebf0b4b1d12d3c1073994588", + "tarball": "http://registry.npmjs.org/mongodb-core/-/mongodb-core-1.3.1.tgz" + }, + "_npmOperationalInternal": { + "host": "packages-5-east.internal.npmjs.com", + "tmp": "tmp/mongodb-core-1.3.1.tgz_1454648311034_0.9954264361876994" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-1.3.1.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat new file mode 100644 index 0000000..25ccf0b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat @@ -0,0 +1,11000 @@ +1 2 +2 1 +3 0 +4 0 +5 1 +6 0 +7 0 +8 0 +9 0 +10 1 +11 0 +12 0 +13 0 +14 1 +15 0 +16 0 +17 0 +18 1 +19 0 +20 0 +21 0 +22 1 +23 0 +24 0 +25 0 +26 0 +27 1 +28 0 +29 0 +30 0 +31 1 +32 0 +33 0 +34 0 +35 0 +36 0 +37 1 +38 0 +39 0 +40 0 +41 0 +42 0 +43 1 +44 0 +45 0 +46 0 +47 0 +48 0 +49 0 +50 0 +51 0 +52 0 +53 0 +54 0 +55 0 +56 0 +57 0 +58 0 +59 1 +60 0 +61 2 +62 0 +63 0 +64 1 +65 0 +66 0 +67 0 +68 1 +69 0 +70 0 +71 0 +72 0 +73 1 +74 0 +75 0 +76 0 +77 0 +78 0 +79 1 +80 0 +81 0 +82 0 +83 0 +84 0 +85 0 +86 1 +87 0 +88 0 +89 0 +90 0 +91 0 +92 0 +93 1 +94 0 +95 0 +96 0 +97 0 +98 0 +99 0 +100 0 +101 1 +102 0 +103 0 +104 0 +105 0 +106 0 +107 0 +108 1 +109 0 +110 0 +111 0 +112 0 +113 0 +114 0 +115 1 +116 0 +117 0 +118 0 +119 1 +120 0 +121 0 +122 0 +123 0 +124 0 +125 0 +126 1 +127 0 +128 1 +129 0 +130 0 +131 0 +132 1 +133 1 +134 0 +135 0 +136 0 +137 1 +138 0 +139 0 +140 0 +141 0 +142 0 +143 0 +144 1 +145 0 +146 0 +147 0 +148 0 +149 0 +150 0 +151 0 +152 0 +153 1 +154 0 +155 0 +156 0 +157 0 +158 0 +159 0 +160 0 +161 0 +162 0 +163 0 +164 0 +165 0 +166 0 +167 0 +168 0 +169 0 +170 1 +171 0 +172 0 +173 0 +174 0 +175 0 +176 0 +177 0 +178 1 +179 0 +180 0 +181 0 +182 0 +183 0 +184 0 +185 0 +186 1 +187 0 +188 0 +189 0 +190 0 +191 0 +192 1 +193 0 +194 0 +195 0 +196 1 +197 0 +198 0 +199 0 +200 1 +201 0 +202 0 +203 0 +204 0 +205 0 +206 0 +207 1 +208 0 +209 0 +210 0 +211 0 +212 0 +213 0 +214 0 +215 1 +216 0 +217 0 +218 0 +219 0 +220 0 +221 0 +222 0 +223 1 +224 0 +225 0 +226 0 +227 0 +228 0 +229 0 +230 1 +231 0 +232 0 +233 0 +234 0 +235 0 +236 0 +237 1 +238 0 +239 0 +240 0 +241 0 +242 0 +243 0 +244 0 +245 1 +246 0 +247 0 +248 0 +249 0 +250 0 +251 0 +252 0 +253 0 +254 1 +255 0 +256 0 +257 0 +258 0 +259 1 +260 0 +261 0 +262 0 +263 0 +264 0 +265 1 +266 0 +267 0 +268 0 +269 0 +270 0 +271 0 +272 1 +273 0 +274 0 +275 0 +276 0 +277 0 +278 0 +279 0 +280 0 +281 1 +282 0 +283 1 +284 0 +285 0 +286 1 +287 0 +288 0 +289 0 +290 0 +291 1 +292 0 +293 0 +294 0 +295 0 +296 1 +297 0 +298 0 +299 0 +300 0 +301 0 +302 0 +303 1 +304 0 +305 0 +306 0 +307 0 +308 0 +309 1 +310 0 +311 0 +312 0 +313 0 +314 0 +315 0 +316 1 +317 0 +318 0 +319 0 +320 0 +321 0 +322 0 +323 0 +324 0 +325 1 +326 0 +327 0 +328 0 +329 0 +330 0 +331 0 +332 0 +333 0 +334 1 +335 0 +336 0 +337 0 +338 0 +339 0 +340 0 +341 0 +342 0 +343 1 +344 0 +345 0 +346 0 +347 0 +348 0 +349 0 +350 0 +351 0 +352 1 +353 0 +354 0 +355 0 +356 0 +357 0 +358 0 +359 0 +360 0 +361 1 +362 0 +363 0 +364 0 +365 0 +366 0 +367 0 +368 0 +369 1 +370 0 +371 0 +372 0 +373 0 +374 0 +375 0 +376 0 +377 1 +378 0 +379 0 +380 0 +381 0 +382 0 +383 0 +384 0 +385 1 +386 0 +387 0 +388 0 +389 0 +390 1 +391 0 +392 0 +393 0 +394 0 +395 0 +396 0 +397 0 +398 0 +399 0 +400 0 +401 0 +402 1 +403 0 +404 0 +405 0 +406 0 +407 0 +408 0 +409 0 +410 1 +411 0 +412 0 +413 0 +414 0 +415 0 +416 0 +417 0 +418 0 +419 1 +420 0 +421 0 +422 0 +423 0 +424 0 +425 0 +426 0 +427 1 +428 0 +429 0 +430 0 +431 0 +432 0 +433 0 +434 0 +435 1 +436 0 +437 0 +438 0 +439 0 +440 0 +441 0 +442 0 +443 1 +444 0 +445 0 +446 0 +447 0 +448 0 +449 0 +450 1 +451 0 +452 0 +453 0 +454 0 +455 0 +456 1 +457 0 +458 0 +459 0 +460 0 +461 0 +462 0 +463 0 +464 1 +465 0 +466 0 +467 0 +468 0 +469 0 +470 0 +471 0 +472 0 +473 1 +474 0 +475 0 +476 0 +477 0 +478 0 +479 0 +480 0 +481 1 +482 0 +483 0 +484 0 +485 0 +486 0 +487 0 +488 0 +489 0 +490 1 +491 0 +492 0 +493 0 +494 0 +495 0 +496 0 +497 0 +498 0 +499 0 +500 0 +501 0 +502 0 +503 0 +504 1 +505 0 +506 0 +507 0 +508 0 +509 0 +510 0 +511 0 +512 1 +513 0 +514 0 +515 0 +516 0 +517 0 +518 0 +519 4 +520 0 +521 1 +522 0 +523 0 +524 0 +525 1 +526 0 +527 0 +528 0 +529 0 +530 1 +531 0 +532 0 +533 0 +534 1 +535 0 +536 0 +537 0 +538 0 +539 1 +540 0 +541 0 +542 0 +543 0 +544 0 +545 1 +546 0 +547 0 +548 0 +549 0 +550 0 +551 1 +552 0 +553 0 +554 0 +555 0 +556 0 +557 0 +558 0 +559 1 +560 0 +561 0 +562 0 +563 0 +564 0 +565 0 +566 0 +567 1 +568 0 +569 0 +570 0 +571 0 +572 0 +573 0 +574 0 +575 0 +576 1 +577 0 +578 0 +579 0 +580 0 +581 0 +582 0 +583 0 +584 0 +585 0 +586 0 +587 0 +588 0 +589 0 +590 0 +591 0 +592 0 +593 1 +594 0 +595 0 +596 0 +597 0 +598 0 +599 0 +600 0 +601 0 +602 1 +603 0 +604 0 +605 0 +606 0 +607 0 +608 0 +609 0 +610 0 +611 1 +612 0 +613 0 +614 0 +615 0 +616 0 +617 0 +618 0 +619 0 +620 1 +621 0 +622 0 +623 0 +624 0 +625 0 +626 0 +627 0 +628 0 +629 1 +630 0 +631 0 +632 0 +633 0 +634 0 +635 0 +636 0 +637 0 +638 0 +639 1 +640 0 +641 0 +642 0 +643 0 +644 0 +645 0 +646 1 +647 0 +648 0 +649 0 +650 0 +651 0 +652 1 +653 1 +654 0 +655 0 +656 1 +657 0 +658 1 +659 0 +660 0 +661 0 +662 0 +663 0 +664 1 +665 0 +666 0 +667 0 +668 0 +669 0 +670 0 +671 0 +672 0 +673 0 +674 0 +675 0 +676 0 +677 1 +678 0 +679 0 +680 0 +681 0 +682 0 +683 0 +684 0 +685 0 +686 1 +687 0 +688 0 +689 0 +690 0 +691 0 +692 0 +693 0 +694 0 +695 1 +696 0 +697 0 +698 0 +699 0 +700 0 +701 0 +702 0 +703 1 +704 0 +705 0 +706 0 +707 0 +708 0 +709 0 +710 0 +711 0 +712 1 +713 0 +714 0 +715 0 +716 0 +717 0 +718 0 +719 0 +720 1 +721 0 +722 0 +723 0 +724 0 +725 0 +726 0 +727 0 +728 1 +729 0 +730 0 +731 0 +732 0 +733 0 +734 0 +735 0 +736 0 +737 1 +738 0 +739 0 +740 0 +741 0 +742 0 +743 0 +744 0 +745 1 +746 0 +747 0 +748 0 +749 0 +750 0 +751 0 +752 0 +753 1 +754 0 +755 0 +756 0 +757 0 +758 0 +759 0 +760 0 +761 1 +762 0 +763 0 +764 0 +765 0 +766 0 +767 0 +768 1 +769 0 +770 0 +771 0 +772 0 +773 0 +774 0 +775 0 +776 0 +777 1 +778 0 +779 0 +780 0 +781 0 +782 0 +783 0 +784 0 +785 0 +786 1 +787 0 +788 0 +789 0 +790 0 +791 0 +792 1 +793 0 +794 0 +795 0 +796 0 +797 0 +798 0 +799 0 +800 0 +801 1 +802 0 +803 0 +804 0 +805 0 +806 0 +807 0 +808 0 +809 0 +810 0 +811 0 +812 0 +813 0 +814 0 +815 0 +816 0 +817 0 +818 0 +819 0 +820 1 +821 0 +822 0 +823 0 +824 0 +825 0 +826 0 +827 0 +828 0 +829 1 +830 0 +831 0 +832 0 +833 0 +834 0 +835 0 +836 0 +837 1 +838 0 +839 0 +840 0 +841 0 +842 0 +843 0 +844 0 +845 0 +846 1 +847 0 +848 0 +849 0 +850 0 +851 0 +852 0 +853 0 +854 0 +855 2 +856 0 +857 0 +858 0 +859 0 +860 0 +861 0 +862 1 +863 0 +864 0 +865 0 +866 0 +867 0 +868 0 +869 0 +870 0 +871 1 +872 0 +873 0 +874 0 +875 0 +876 0 +877 0 +878 1 +879 0 +880 0 +881 0 +882 0 +883 0 +884 0 +885 0 +886 0 +887 0 +888 0 +889 0 +890 0 +891 0 +892 0 +893 0 +894 0 +895 0 +896 1 +897 0 +898 0 +899 0 +900 0 +901 0 +902 0 +903 0 +904 0 +905 0 +906 1 +907 0 +908 0 +909 0 +910 0 +911 0 +912 0 +913 0 +914 0 +915 1 +916 0 +917 0 +918 0 +919 0 +920 0 +921 0 +922 1 +923 0 +924 0 +925 0 +926 0 +927 0 +928 0 +929 0 +930 1 +931 0 +932 0 +933 0 +934 0 +935 0 +936 0 +937 0 +938 0 +939 1 +940 0 +941 0 +942 0 +943 0 +944 0 +945 0 +946 0 +947 0 +948 0 +949 1 +950 0 +951 0 +952 0 +953 0 +954 0 +955 0 +956 0 +957 0 +958 1 +959 0 +960 0 +961 0 +962 0 +963 0 +964 0 +965 0 +966 0 +967 0 +968 1 +969 0 +970 0 +971 0 +972 0 +973 0 +974 0 +975 0 +976 0 +977 0 +978 1 +979 0 +980 0 +981 0 +982 0 +983 0 +984 0 +985 0 +986 0 +987 0 +988 1 +989 0 +990 0 +991 0 +992 0 +993 0 +994 0 +995 0 +996 0 +997 1 +998 0 +999 0 +1000 0 +1001 0 +1002 0 +1003 0 +1004 0 +1005 1 +1006 0 +1007 0 +1008 0 +1009 0 +1010 0 +1011 0 +1012 1 +1013 0 +1014 0 +1015 0 +1016 0 +1017 0 +1018 0 +1019 0 +1020 0 +1021 0 +1022 0 +1023 0 +1024 0 +1025 0 +1026 0 +1027 0 +1028 0 +1029 0 +1030 0 +1031 1 +1032 0 +1033 0 +1034 0 +1035 0 +1036 0 +1037 0 +1038 0 +1039 0 +1040 0 +1041 0 +1042 1 +1043 0 +1044 0 +1045 0 +1046 0 +1047 0 +1048 0 +1049 0 +1050 1 +1051 0 +1052 0 +1053 0 +1054 0 +1055 0 +1056 0 +1057 1 +1058 0 +1059 0 +1060 0 +1061 0 +1062 0 +1063 0 +1064 0 +1065 0 +1066 0 +1067 1 +1068 0 +1069 0 +1070 0 +1071 0 +1072 0 +1073 0 +1074 0 +1075 0 +1076 0 +1077 1 +1078 0 +1079 0 +1080 0 +1081 0 +1082 0 +1083 0 +1084 0 +1085 0 +1086 0 +1087 1 +1088 0 +1089 0 +1090 0 +1091 0 +1092 0 +1093 0 +1094 1 +1095 0 +1096 0 +1097 0 +1098 0 +1099 0 +1100 0 +1101 0 +1102 1 +1103 0 +1104 0 +1105 0 +1106 0 +1107 0 +1108 0 +1109 0 +1110 0 +1111 1 +1112 0 +1113 0 +1114 0 +1115 0 +1116 0 +1117 0 +1118 0 +1119 0 +1120 1 +1121 0 +1122 0 +1123 0 +1124 0 +1125 0 +1126 0 +1127 0 +1128 0 +1129 0 +1130 1 +1131 0 +1132 0 +1133 0 +1134 0 +1135 0 +1136 0 +1137 0 +1138 0 +1139 0 +1140 1 +1141 0 +1142 0 +1143 0 +1144 0 +1145 0 +1146 0 +1147 0 +1148 0 +1149 0 +1150 0 +1151 1 +1152 0 +1153 0 +1154 0 +1155 0 +1156 0 +1157 0 +1158 0 +1159 0 +1160 1 +1161 0 +1162 0 +1163 0 +1164 0 +1165 0 +1166 0 +1167 1 +1168 0 +1169 0 +1170 0 +1171 0 +1172 0 +1173 0 +1174 0 +1175 0 +1176 1 +1177 0 +1178 0 +1179 0 +1180 0 +1181 0 +1182 1 +1183 0 +1184 0 +1185 0 +1186 0 +1187 0 +1188 0 +1189 0 +1190 1 +1191 0 +1192 0 +1193 0 +1194 0 +1195 0 +1196 0 +1197 0 +1198 1 +1199 0 +1200 0 +1201 0 +1202 0 +1203 0 +1204 0 +1205 0 +1206 1 +1207 0 +1208 0 +1209 0 +1210 0 +1211 0 +1212 0 +1213 0 +1214 0 +1215 0 +1216 1 +1217 0 +1218 0 +1219 0 +1220 0 +1221 0 +1222 0 +1223 0 +1224 0 +1225 0 +1226 1 +1227 0 +1228 0 +1229 0 +1230 0 +1231 0 +1232 0 +1233 0 +1234 0 +1235 0 +1236 0 +1237 0 +1238 0 +1239 1 +1240 0 +1241 0 +1242 0 +1243 0 +1244 0 +1245 0 +1246 0 +1247 0 +1248 1 +1249 0 +1250 0 +1251 0 +1252 0 +1253 0 +1254 0 +1255 0 +1256 0 +1257 1 +1258 0 +1259 0 +1260 0 +1261 0 +1262 0 +1263 0 +1264 0 +1265 0 +1266 1 +1267 0 +1268 0 +1269 0 +1270 0 +1271 0 +1272 0 +1273 0 +1274 0 +1275 1 +1276 0 +1277 0 +1278 0 +1279 0 +1280 0 +1281 0 +1282 0 +1283 0 +1284 0 +1285 0 +1286 0 +1287 0 +1288 0 +1289 0 +1290 0 +1291 0 +1292 0 +1293 1 +1294 0 +1295 0 +1296 0 +1297 0 +1298 0 +1299 0 +1300 0 +1301 0 +1302 0 +1303 0 +1304 0 +1305 0 +1306 0 +1307 0 +1308 0 +1309 0 +1310 1 +1311 0 +1312 0 +1313 0 +1314 0 +1315 0 +1316 0 +1317 0 +1318 1 +1319 0 +1320 0 +1321 0 +1322 0 +1323 0 +1324 0 +1325 0 +1326 0 +1327 1 +1328 0 +1329 0 +1330 0 +1331 0 +1332 0 +1333 0 +1334 0 +1335 0 +1336 1 +1337 0 +1338 0 +1339 0 +1340 0 +1341 0 +1342 0 +1343 0 +1344 0 +1345 0 +1346 1 +1347 0 +1348 0 +1349 0 +1350 0 +1351 0 +1352 0 +1353 0 +1354 0 +1355 0 +1356 1 +1357 0 +1358 0 +1359 0 +1360 0 +1361 0 +1362 0 +1363 0 +1364 0 +1365 1 +1366 0 +1367 0 +1368 0 +1369 0 +1370 0 +1371 0 +1372 0 +1373 1 +1374 0 +1375 0 +1376 0 +1377 0 +1378 0 +1379 0 +1380 0 +1381 0 +1382 0 +1383 1 +1384 0 +1385 0 +1386 0 +1387 0 +1388 0 +1389 0 +1390 0 +1391 0 +1392 1 +1393 0 +1394 0 +1395 0 +1396 0 +1397 0 +1398 0 +1399 0 +1400 1 +1401 0 +1402 0 +1403 0 +1404 0 +1405 0 +1406 0 +1407 0 +1408 0 +1409 0 +1410 1 +1411 0 +1412 0 +1413 0 +1414 0 +1415 0 +1416 0 +1417 0 +1418 0 +1419 0 +1420 1 +1421 0 +1422 0 +1423 0 +1424 0 +1425 0 +1426 0 +1427 0 +1428 0 +1429 0 +1430 0 +1431 1 +1432 0 +1433 0 +1434 0 +1435 0 +1436 0 +1437 0 +1438 0 +1439 0 +1440 0 +1441 1 +1442 0 +1443 0 +1444 0 +1445 0 +1446 0 +1447 2 +1448 0 +1449 0 +1450 0 +1451 0 +1452 0 +1453 0 +1454 0 +1455 1 +1456 0 +1457 0 +1458 0 +1459 0 +1460 0 +1461 0 +1462 0 +1463 0 +1464 0 +1465 1 +1466 0 +1467 0 +1468 0 +1469 0 +1470 0 +1471 0 +1472 0 +1473 0 +1474 0 +1475 1 +1476 0 +1477 0 +1478 0 +1479 0 +1480 0 +1481 0 +1482 0 +1483 0 +1484 0 +1485 1 +1486 0 +1487 0 +1488 0 +1489 0 +1490 0 +1491 0 +1492 0 +1493 0 +1494 1 +1495 0 +1496 0 +1497 0 +1498 0 +1499 0 +1500 0 +1501 0 +1502 0 +1503 1 +1504 0 +1505 0 +1506 0 +1507 0 +1508 0 +1509 0 +1510 0 +1511 0 +1512 0 +1513 0 +1514 0 +1515 0 +1516 0 +1517 0 +1518 0 +1519 0 +1520 1 +1521 0 +1522 0 +1523 0 +1524 0 +1525 0 +1526 0 +1527 0 +1528 0 +1529 1 +1530 0 +1531 0 +1532 0 +1533 0 +1534 0 +1535 0 +1536 0 +1537 0 +1538 0 +1539 1 +1540 0 +1541 0 +1542 0 +1543 0 +1544 0 +1545 0 +1546 0 +1547 0 +1548 1 +1549 0 +1550 0 +1551 0 +1552 0 +1553 0 +1554 0 +1555 0 +1556 0 +1557 1 +1558 0 +1559 0 +1560 0 +1561 0 +1562 0 +1563 0 +1564 0 +1565 0 +1566 0 +1567 1 +1568 0 +1569 0 +1570 0 +1571 0 +1572 0 +1573 0 +1574 0 +1575 1 +1576 0 +1577 0 +1578 0 +1579 0 +1580 0 +1581 0 +1582 0 +1583 0 +1584 1 +1585 0 +1586 0 +1587 0 +1588 0 +1589 0 +1590 0 +1591 0 +1592 0 +1593 1 +1594 0 +1595 0 +1596 0 +1597 0 +1598 0 +1599 0 +1600 0 +1601 0 +1602 1 +1603 0 +1604 0 +1605 0 +1606 0 +1607 0 +1608 0 +1609 0 +1610 0 +1611 1 +1612 0 +1613 0 +1614 0 +1615 0 +1616 0 +1617 0 +1618 0 +1619 0 +1620 0 +1621 1 +1622 0 +1623 0 +1624 0 +1625 0 +1626 0 +1627 0 +1628 0 +1629 0 +1630 0 +1631 1 +1632 0 +1633 0 +1634 0 +1635 0 +1636 0 +1637 0 +1638 0 +1639 0 +1640 1 +1641 0 +1642 0 +1643 0 +1644 0 +1645 0 +1646 0 +1647 0 +1648 0 +1649 0 +1650 1 +1651 0 +1652 0 +1653 0 +1654 0 +1655 0 +1656 0 +1657 0 +1658 0 +1659 0 +1660 1 +1661 0 +1662 0 +1663 0 +1664 0 +1665 0 +1666 0 +1667 0 +1668 0 +1669 0 +1670 1 +1671 0 +1672 0 +1673 0 +1674 0 +1675 0 +1676 0 +1677 0 +1678 0 +1679 0 +1680 1 +1681 0 +1682 0 +1683 0 +1684 0 +1685 0 +1686 0 +1687 0 +1688 0 +1689 0 +1690 1 +1691 0 +1692 0 +1693 0 +1694 0 +1695 0 +1696 0 +1697 0 +1698 0 +1699 0 +1700 0 +1701 1 +1702 0 +1703 0 +1704 0 +1705 0 +1706 0 +1707 0 +1708 1 +1709 0 +1710 0 +1711 0 +1712 0 +1713 0 +1714 0 +1715 0 +1716 1 +1717 0 +1718 0 +1719 0 +1720 0 +1721 0 +1722 0 +1723 0 +1724 0 +1725 0 +1726 0 +1727 0 +1728 0 +1729 0 +1730 0 +1731 0 +1732 0 +1733 0 +1734 1 +1735 0 +1736 0 +1737 0 +1738 0 +1739 0 +1740 0 +1741 0 +1742 0 +1743 1 +1744 0 +1745 0 +1746 0 +1747 0 +1748 0 +1749 0 +1750 0 +1751 0 +1752 0 +1753 1 +1754 0 +1755 0 +1756 0 +1757 0 +1758 0 +1759 0 +1760 0 +1761 0 +1762 0 +1763 1 +1764 0 +1765 0 +1766 0 +1767 0 +1768 0 +1769 0 +1770 0 +1771 0 +1772 0 +1773 1 +1774 0 +1775 0 +1776 0 +1777 0 +1778 0 +1779 0 +1780 0 +1781 0 +1782 0 +1783 1 +1784 0 +1785 0 +1786 0 +1787 0 +1788 0 +1789 0 +1790 0 +1791 0 +1792 0 +1793 1 +1794 0 +1795 0 +1796 0 +1797 0 +1798 0 +1799 0 +1800 0 +1801 0 +1802 0 +1803 1 +1804 0 +1805 0 +1806 0 +1807 0 +1808 0 +1809 0 +1810 0 +1811 0 +1812 0 +1813 1 +1814 0 +1815 0 +1816 0 +1817 0 +1818 0 +1819 0 +1820 0 +1821 0 +1822 1 +1823 0 +1824 0 +1825 0 +1826 0 +1827 0 +1828 0 +1829 1 +1830 0 +1831 0 +1832 0 +1833 0 +1834 0 +1835 0 +1836 0 +1837 0 +1838 0 +1839 1 +1840 0 +1841 0 +1842 0 +1843 0 +1844 0 +1845 0 +1846 0 +1847 0 +1848 0 +1849 1 +1850 0 +1851 0 +1852 0 +1853 0 +1854 0 +1855 0 +1856 0 +1857 0 +1858 0 +1859 1 +1860 0 +1861 0 +1862 0 +1863 0 +1864 0 +1865 0 +1866 0 +1867 0 +1868 0 +1869 1 +1870 0 +1871 0 +1872 0 +1873 0 +1874 0 +1875 0 +1876 0 +1877 0 +1878 0 +1879 1 +1880 0 +1881 0 +1882 0 +1883 0 +1884 0 +1885 0 +1886 0 +1887 0 +1888 0 +1889 1 +1890 0 +1891 0 +1892 0 +1893 0 +1894 0 +1895 0 +1896 0 +1897 0 +1898 0 +1899 0 +1900 0 +1901 0 +1902 0 +1903 0 +1904 0 +1905 0 +1906 0 +1907 0 +1908 0 +1909 0 +1910 1 +1911 0 +1912 0 +1913 0 +1914 0 +1915 0 +1916 0 +1917 0 +1918 0 +1919 0 +1920 0 +1921 0 +1922 0 +1923 0 +1924 0 +1925 0 +1926 0 +1927 0 +1928 0 +1929 0 +1930 1 +1931 0 +1932 0 +1933 0 +1934 0 +1935 0 +1936 0 +1937 0 +1938 0 +1939 1 +1940 0 +1941 0 +1942 0 +1943 0 +1944 0 +1945 0 +1946 0 +1947 0 +1948 0 +1949 1 +1950 0 +1951 0 +1952 0 +1953 0 +1954 0 +1955 0 +1956 0 +1957 0 +1958 1 +1959 0 +1960 0 +1961 0 +1962 0 +1963 0 +1964 0 +1965 0 +1966 0 +1967 0 +1968 1 +1969 0 +1970 0 +1971 0 +1972 0 +1973 0 +1974 0 +1975 0 +1976 0 +1977 0 +1978 1 +1979 0 +1980 0 +1981 0 +1982 0 +1983 0 +1984 0 +1985 0 +1986 0 +1987 0 +1988 1 +1989 0 +1990 0 +1991 0 +1992 0 +1993 0 +1994 0 +1995 0 +1996 1 +1997 0 +1998 0 +1999 0 +2000 0 +2001 0 +2002 0 +2003 0 +2004 1 +2005 0 +2006 0 +2007 0 +2008 0 +2009 0 +2010 0 +2011 0 +2012 0 +2013 0 +2014 1 +2015 0 +2016 0 +2017 0 +2018 0 +2019 0 +2020 0 +2021 0 +2022 0 +2023 0 +2024 1 +2025 0 +2026 0 +2027 0 +2028 0 +2029 0 +2030 0 +2031 0 +2032 0 +2033 1 +2034 0 +2035 0 +2036 0 +2037 0 +2038 0 +2039 0 +2040 0 +2041 2 +2042 0 +2043 0 +2044 0 +2045 0 +2046 0 +2047 0 +2048 0 +2049 1 +2050 0 +2051 0 +2052 0 +2053 0 +2054 0 +2055 0 +2056 0 +2057 0 +2058 0 +2059 0 +2060 0 +2061 0 +2062 0 +2063 0 +2064 0 +2065 0 +2066 0 +2067 1 +2068 0 +2069 0 +2070 0 +2071 0 +2072 0 +2073 0 +2074 0 +2075 0 +2076 1 +2077 0 +2078 0 +2079 0 +2080 0 +2081 0 +2082 0 +2083 0 +2084 0 +2085 0 +2086 1 +2087 0 +2088 0 +2089 0 +2090 0 +2091 0 +2092 0 +2093 0 +2094 0 +2095 0 +2096 1 +2097 0 +2098 0 +2099 0 +2100 0 +2101 0 +2102 0 +2103 0 +2104 0 +2105 1 +2106 0 +2107 0 +2108 0 +2109 0 +2110 0 +2111 0 +2112 0 +2113 0 +2114 0 +2115 0 +2116 1 +2117 0 +2118 0 +2119 0 +2120 0 +2121 0 +2122 0 +2123 0 +2124 0 +2125 1 +2126 0 +2127 0 +2128 0 +2129 0 +2130 0 +2131 0 +2132 0 +2133 1 +2134 0 +2135 0 +2136 0 +2137 0 +2138 0 +2139 0 +2140 0 +2141 1 +2142 0 +2143 0 +2144 0 +2145 0 +2146 0 +2147 0 +2148 0 +2149 0 +2150 1 +2151 0 +2152 0 +2153 0 +2154 0 +2155 0 +2156 0 +2157 0 +2158 0 +2159 1 +2160 0 +2161 0 +2162 0 +2163 0 +2164 0 +2165 0 +2166 0 +2167 0 +2168 0 +2169 1 +2170 0 +2171 0 +2172 0 +2173 0 +2174 0 +2175 0 +2176 0 +2177 1 +2178 0 +2179 0 +2180 0 +2181 0 +2182 0 +2183 0 +2184 0 +2185 0 +2186 0 +2187 1 +2188 0 +2189 0 +2190 0 +2191 0 +2192 0 +2193 0 +2194 0 +2195 0 +2196 1 +2197 0 +2198 0 +2199 0 +2200 0 +2201 0 +2202 0 +2203 0 +2204 1 +2205 0 +2206 0 +2207 0 +2208 0 +2209 0 +2210 0 +2211 0 +2212 0 +2213 0 +2214 1 +2215 0 +2216 0 +2217 0 +2218 0 +2219 0 +2220 0 +2221 0 +2222 0 +2223 0 +2224 1 +2225 0 +2226 0 +2227 0 +2228 0 +2229 0 +2230 0 +2231 0 +2232 0 +2233 1 +2234 0 +2235 0 +2236 0 +2237 0 +2238 0 +2239 0 +2240 0 +2241 0 +2242 1 +2243 0 +2244 0 +2245 0 +2246 0 +2247 0 +2248 0 +2249 0 +2250 1 +2251 0 +2252 0 +2253 0 +2254 0 +2255 0 +2256 0 +2257 0 +2258 0 +2259 0 +2260 1 +2261 0 +2262 0 +2263 0 +2264 0 +2265 0 +2266 0 +2267 0 +2268 0 +2269 0 +2270 1 +2271 0 +2272 0 +2273 0 +2274 0 +2275 0 +2276 0 +2277 0 +2278 0 +2279 0 +2280 1 +2281 0 +2282 0 +2283 0 +2284 0 +2285 0 +2286 0 +2287 0 +2288 0 +2289 0 +2290 1 +2291 0 +2292 0 +2293 0 +2294 0 +2295 0 +2296 0 +2297 0 +2298 1 +2299 0 +2300 0 +2301 0 +2302 0 +2303 0 +2304 0 +2305 0 +2306 1 +2307 0 +2308 0 +2309 0 +2310 0 +2311 0 +2312 0 +2313 0 +2314 0 +2315 1 +2316 0 +2317 0 +2318 0 +2319 0 +2320 0 +2321 0 +2322 0 +2323 0 +2324 0 +2325 1 +2326 0 +2327 0 +2328 0 +2329 0 +2330 0 +2331 0 +2332 0 +2333 0 +2334 0 +2335 1 +2336 0 +2337 0 +2338 0 +2339 0 +2340 0 +2341 0 +2342 0 +2343 0 +2344 0 +2345 1 +2346 0 +2347 0 +2348 0 +2349 0 +2350 0 +2351 0 +2352 0 +2353 1 +2354 0 +2355 0 +2356 0 +2357 0 +2358 0 +2359 0 +2360 0 +2361 1 +2362 0 +2363 0 +2364 0 +2365 0 +2366 0 +2367 0 +2368 0 +2369 0 +2370 0 +2371 1 +2372 0 +2373 0 +2374 0 +2375 0 +2376 0 +2377 0 +2378 0 +2379 0 +2380 0 +2381 1 +2382 0 +2383 0 +2384 0 +2385 0 +2386 0 +2387 0 +2388 0 +2389 0 +2390 1 +2391 0 +2392 0 +2393 0 +2394 0 +2395 0 +2396 0 +2397 0 +2398 0 +2399 0 +2400 0 +2401 0 +2402 0 +2403 0 +2404 0 +2405 0 +2406 0 +2407 0 +2408 0 +2409 0 +2410 0 +2411 1 +2412 0 +2413 0 +2414 0 +2415 0 +2416 0 +2417 0 +2418 0 +2419 0 +2420 0 +2421 1 +2422 0 +2423 0 +2424 0 +2425 0 +2426 0 +2427 0 +2428 0 +2429 0 +2430 0 +2431 0 +2432 0 +2433 0 +2434 0 +2435 0 +2436 0 +2437 0 +2438 0 +2439 0 +2440 1 +2441 0 +2442 0 +2443 0 +2444 0 +2445 0 +2446 0 +2447 0 +2448 0 +2449 0 +2450 0 +2451 1 +2452 0 +2453 0 +2454 0 +2455 0 +2456 0 +2457 0 +2458 0 +2459 0 +2460 0 +2461 1 +2462 0 +2463 0 +2464 0 +2465 0 +2466 0 +2467 0 +2468 0 +2469 1 +2470 0 +2471 0 +2472 0 +2473 0 +2474 0 +2475 0 +2476 0 +2477 1 +2478 0 +2479 0 +2480 0 +2481 0 +2482 0 +2483 0 +2484 0 +2485 0 +2486 1 +2487 0 +2488 0 +2489 0 +2490 0 +2491 0 +2492 0 +2493 0 +2494 0 +2495 0 +2496 1 +2497 0 +2498 0 +2499 0 +2500 0 +2501 0 +2502 0 +2503 0 +2504 0 +2505 0 +2506 1 +2507 0 +2508 0 +2509 0 +2510 0 +2511 0 +2512 0 +2513 0 +2514 0 +2515 0 +2516 1 +2517 0 +2518 0 +2519 0 +2520 0 +2521 0 +2522 0 +2523 0 +2524 0 +2525 0 +2526 0 +2527 1 +2528 0 +2529 0 +2530 0 +2531 0 +2532 0 +2533 0 +2534 0 +2535 0 +2536 0 +2537 1 +2538 0 +2539 0 +2540 0 +2541 0 +2542 0 +2543 0 +2544 0 +2545 0 +2546 0 +2547 0 +2548 0 +2549 0 +2550 0 +2551 0 +2552 0 +2553 0 +2554 0 +2555 0 +2556 0 +2557 1 +2558 0 +2559 0 +2560 0 +2561 0 +2562 0 +2563 0 +2564 0 +2565 0 +2566 1 +2567 0 +2568 0 +2569 0 +2570 0 +2571 0 +2572 0 +2573 0 +2574 0 +2575 1 +2576 0 +2577 0 +2578 0 +2579 0 +2580 0 +2581 0 +2582 0 +2583 0 +2584 1 +2585 0 +2586 0 +2587 0 +2588 0 +2589 0 +2590 0 +2591 0 +2592 0 +2593 0 +2594 0 +2595 1 +2596 0 +2597 0 +2598 0 +2599 0 +2600 0 +2601 0 +2602 0 +2603 0 +2604 0 +2605 1 +2606 0 +2607 0 +2608 0 +2609 0 +2610 0 +2611 0 +2612 0 +2613 0 +2614 0 +2615 0 +2616 0 +2617 0 +2618 0 +2619 0 +2620 0 +2621 0 +2622 0 +2623 0 +2624 0 +2625 1 +2626 0 +2627 0 +2628 0 +2629 0 +2630 0 +2631 0 +2632 0 +2633 0 +2634 0 +2635 1 +2636 0 +2637 0 +2638 0 +2639 1 +2640 0 +2641 0 +2642 0 +2643 1 +2644 0 +2645 0 +2646 0 +2647 0 +2648 0 +2649 0 +2650 0 +2651 0 +2652 0 +2653 1 +2654 0 +2655 0 +2656 0 +2657 0 +2658 0 +2659 0 +2660 0 +2661 0 +2662 0 +2663 1 +2664 0 +2665 0 +2666 0 +2667 0 +2668 0 +2669 0 +2670 0 +2671 1 +2672 0 +2673 0 +2674 0 +2675 0 +2676 0 +2677 0 +2678 0 +2679 1 +2680 0 +2681 0 +2682 0 +2683 0 +2684 0 +2685 0 +2686 0 +2687 0 +2688 0 +2689 1 +2690 0 +2691 0 +2692 0 +2693 0 +2694 0 +2695 0 +2696 0 +2697 0 +2698 0 +2699 1 +2700 0 +2701 0 +2702 0 +2703 0 +2704 0 +2705 0 +2706 0 +2707 0 +2708 0 +2709 1 +2710 0 +2711 0 +2712 0 +2713 0 +2714 0 +2715 0 +2716 1 +2717 0 +2718 0 +2719 0 +2720 0 +2721 0 +2722 0 +2723 0 +2724 1 +2725 0 +2726 0 +2727 0 +2728 0 +2729 0 +2730 0 +2731 0 +2732 0 +2733 0 +2734 1 +2735 0 +2736 0 +2737 0 +2738 0 +2739 0 +2740 0 +2741 0 +2742 0 +2743 0 +2744 1 +2745 0 +2746 0 +2747 0 +2748 0 +2749 0 +2750 0 +2751 0 +2752 0 +2753 1 +2754 0 +2755 0 +2756 0 +2757 0 +2758 0 +2759 0 +2760 0 +2761 0 +2762 0 +2763 1 +2764 0 +2765 0 +2766 0 +2767 0 +2768 0 +2769 0 +2770 0 +2771 0 +2772 0 +2773 1 +2774 0 +2775 0 +2776 0 +2777 0 +2778 0 +2779 0 +2780 0 +2781 0 +2782 0 +2783 1 +2784 0 +2785 0 +2786 0 +2787 0 +2788 0 +2789 0 +2790 0 +2791 0 +2792 1 +2793 0 +2794 0 +2795 0 +2796 0 +2797 0 +2798 0 +2799 0 +2800 0 +2801 0 +2802 0 +2803 0 +2804 0 +2805 0 +2806 0 +2807 0 +2808 0 +2809 0 +2810 0 +2811 0 +2812 0 +2813 0 +2814 0 +2815 0 +2816 0 +2817 0 +2818 0 +2819 0 +2820 0 +2821 1 +2822 0 +2823 0 +2824 0 +2825 0 +2826 0 +2827 0 +2828 0 +2829 0 +2830 0 +2831 1 +2832 0 +2833 0 +2834 0 +2835 0 +2836 0 +2837 0 +2838 0 +2839 0 +2840 0 +2841 1 +2842 0 +2843 0 +2844 0 +2845 0 +2846 0 +2847 0 +2848 0 +2849 0 +2850 0 +2851 1 +2852 0 +2853 0 +2854 0 +2855 0 +2856 0 +2857 0 +2858 0 +2859 0 +2860 0 +2861 1 +2862 0 +2863 0 +2864 0 +2865 0 +2866 0 +2867 0 +2868 0 +2869 0 +2870 0 +2871 1 +2872 0 +2873 0 +2874 0 +2875 0 +2876 0 +2877 0 +2878 0 +2879 0 +2880 1 +2881 0 +2882 0 +2883 0 +2884 0 +2885 0 +2886 0 +2887 0 +2888 1 +2889 0 +2890 0 +2891 0 +2892 0 +2893 0 +2894 0 +2895 0 +2896 0 +2897 1 +2898 0 +2899 0 +2900 0 +2901 0 +2902 0 +2903 0 +2904 0 +2905 0 +2906 1 +2907 0 +2908 0 +2909 0 +2910 0 +2911 0 +2912 0 +2913 0 +2914 1 +2915 0 +2916 0 +2917 0 +2918 0 +2919 0 +2920 0 +2921 0 +2922 1 +2923 0 +2924 0 +2925 0 +2926 0 +2927 0 +2928 0 +2929 0 +2930 0 +2931 0 +2932 0 +2933 0 +2934 0 +2935 0 +2936 0 +2937 0 +2938 1 +2939 0 +2940 0 +2941 0 +2942 0 +2943 0 +2944 0 +2945 0 +2946 0 +2947 0 +2948 0 +2949 1 +2950 0 +2951 0 +2952 0 +2953 0 +2954 0 +2955 0 +2956 0 +2957 0 +2958 0 +2959 1 +2960 0 +2961 0 +2962 0 +2963 0 +2964 0 +2965 0 +2966 0 +2967 0 +2968 1 +2969 0 +2970 0 +2971 0 +2972 0 +2973 0 +2974 0 +2975 0 +2976 0 +2977 1 +2978 0 +2979 0 +2980 0 +2981 0 +2982 0 +2983 0 +2984 0 +2985 0 +2986 0 +2987 1 +2988 0 +2989 0 +2990 0 +2991 0 +2992 0 +2993 0 +2994 0 +2995 0 +2996 0 +2997 1 +2998 0 +2999 0 +3000 0 +3001 0 +3002 0 +3003 0 +3004 0 +3005 0 +3006 0 +3007 0 +3008 0 +3009 0 +3010 0 +3011 0 +3012 0 +3013 0 +3014 0 +3015 1 +3016 0 +3017 0 +3018 0 +3019 0 +3020 0 +3021 0 +3022 0 +3023 0 +3024 0 +3025 1 +3026 0 +3027 0 +3028 0 +3029 0 +3030 0 +3031 0 +3032 0 +3033 0 +3034 1 +3035 0 +3036 0 +3037 0 +3038 0 +3039 0 +3040 0 +3041 0 +3042 1 +3043 0 +3044 0 +3045 0 +3046 0 +3047 0 +3048 0 +3049 0 +3050 0 +3051 0 +3052 1 +3053 0 +3054 0 +3055 0 +3056 0 +3057 0 +3058 0 +3059 0 +3060 0 +3061 0 +3062 1 +3063 0 +3064 0 +3065 0 +3066 0 +3067 0 +3068 0 +3069 0 +3070 0 +3071 0 +3072 1 +3073 0 +3074 0 +3075 0 +3076 0 +3077 0 +3078 0 +3079 0 +3080 0 +3081 0 +3082 1 +3083 0 +3084 0 +3085 0 +3086 0 +3087 0 +3088 0 +3089 0 +3090 0 +3091 0 +3092 1 +3093 0 +3094 0 +3095 0 +3096 0 +3097 0 +3098 0 +3099 0 +3100 0 +3101 0 +3102 1 +3103 0 +3104 0 +3105 0 +3106 0 +3107 0 +3108 0 +3109 0 +3110 0 +3111 0 +3112 1 +3113 0 +3114 0 +3115 0 +3116 0 +3117 0 +3118 0 +3119 0 +3120 1 +3121 0 +3122 0 +3123 0 +3124 0 +3125 0 +3126 0 +3127 0 +3128 0 +3129 1 +3130 0 +3131 0 +3132 0 +3133 0 +3134 0 +3135 0 +3136 0 +3137 0 +3138 0 +3139 1 +3140 0 +3141 0 +3142 0 +3143 0 +3144 0 +3145 0 +3146 0 +3147 0 +3148 0 +3149 1 +3150 0 +3151 0 +3152 0 +3153 0 +3154 0 +3155 0 +3156 0 +3157 1 +3158 0 +3159 0 +3160 0 +3161 0 +3162 0 +3163 0 +3164 0 +3165 1 +3166 0 +3167 0 +3168 0 +3169 0 +3170 0 +3171 0 +3172 0 +3173 0 +3174 0 +3175 1 +3176 0 +3177 0 +3178 0 +3179 0 +3180 0 +3181 0 +3182 0 +3183 0 +3184 0 +3185 1 +3186 0 +3187 0 +3188 0 +3189 0 +3190 0 +3191 0 +3192 0 +3193 0 +3194 0 +3195 0 +3196 1 +3197 0 +3198 0 +3199 0 +3200 0 +3201 0 +3202 0 +3203 0 +3204 0 +3205 0 +3206 0 +3207 1 +3208 0 +3209 0 +3210 0 +3211 0 +3212 0 +3213 0 +3214 0 +3215 1 +3216 0 +3217 0 +3218 0 +3219 0 +3220 0 +3221 0 +3222 0 +3223 1 +3224 0 +3225 0 +3226 0 +3227 0 +3228 0 +3229 0 +3230 0 +3231 0 +3232 1 +3233 0 +3234 1 +3235 0 +3236 0 +3237 0 +3238 0 +3239 1 +3240 0 +3241 0 +3242 0 +3243 0 +3244 0 +3245 0 +3246 0 +3247 0 +3248 1 +3249 0 +3250 0 +3251 0 +3252 0 +3253 0 +3254 0 +3255 0 +3256 0 +3257 0 +3258 1 +3259 0 +3260 0 +3261 0 +3262 0 +3263 0 +3264 0 +3265 0 +3266 0 +3267 0 +3268 0 +3269 1 +3270 0 +3271 0 +3272 0 +3273 0 +3274 0 +3275 0 +3276 0 +3277 0 +3278 1 +3279 0 +3280 0 +3281 0 +3282 0 +3283 0 +3284 0 +3285 0 +3286 0 +3287 1 +3288 0 +3289 0 +3290 0 +3291 0 +3292 0 +3293 0 +3294 0 +3295 0 +3296 0 +3297 1 +3298 0 +3299 0 +3300 0 +3301 0 +3302 0 +3303 0 +3304 0 +3305 0 +3306 0 +3307 1 +3308 0 +3309 0 +3310 0 +3311 0 +3312 0 +3313 0 +3314 0 +3315 0 +3316 0 +3317 1 +3318 0 +3319 0 +3320 0 +3321 0 +3322 0 +3323 0 +3324 0 +3325 1 +3326 0 +3327 0 +3328 0 +3329 0 +3330 0 +3331 0 +3332 0 +3333 0 +3334 0 +3335 1 +3336 0 +3337 0 +3338 0 +3339 0 +3340 0 +3341 0 +3342 0 +3343 0 +3344 1 +3345 0 +3346 0 +3347 0 +3348 0 +3349 0 +3350 0 +3351 0 +3352 0 +3353 0 +3354 1 +3355 0 +3356 0 +3357 0 +3358 0 +3359 0 +3360 0 +3361 0 +3362 0 +3363 0 +3364 0 +3365 1 +3366 0 +3367 0 +3368 0 +3369 0 +3370 0 +3371 0 +3372 0 +3373 0 +3374 0 +3375 1 +3376 0 +3377 0 +3378 0 +3379 0 +3380 0 +3381 0 +3382 0 +3383 0 +3384 0 +3385 0 +3386 1 +3387 0 +3388 0 +3389 0 +3390 0 +3391 0 +3392 0 +3393 0 +3394 0 +3395 0 +3396 0 +3397 1 +3398 0 +3399 0 +3400 0 +3401 0 +3402 0 +3403 0 +3404 0 +3405 0 +3406 0 +3407 1 +3408 0 +3409 0 +3410 0 +3411 0 +3412 0 +3413 0 +3414 0 +3415 0 +3416 0 +3417 1 +3418 0 +3419 0 +3420 0 +3421 0 +3422 0 +3423 0 +3424 0 +3425 0 +3426 0 +3427 0 +3428 1 +3429 0 +3430 0 +3431 0 +3432 0 +3433 0 +3434 0 +3435 0 +3436 0 +3437 1 +3438 0 +3439 0 +3440 0 +3441 0 +3442 0 +3443 0 +3444 0 +3445 1 +3446 0 +3447 0 +3448 0 +3449 0 +3450 0 +3451 0 +3452 0 +3453 0 +3454 1 +3455 0 +3456 0 +3457 0 +3458 0 +3459 0 +3460 0 +3461 0 +3462 0 +3463 0 +3464 1 +3465 0 +3466 0 +3467 0 +3468 0 +3469 0 +3470 0 +3471 0 +3472 0 +3473 0 +3474 1 +3475 0 +3476 0 +3477 0 +3478 0 +3479 0 +3480 0 +3481 0 +3482 0 +3483 0 +3484 1 +3485 0 +3486 0 +3487 0 +3488 0 +3489 0 +3490 0 +3491 0 +3492 0 +3493 0 +3494 1 +3495 0 +3496 0 +3497 0 +3498 0 +3499 0 +3500 0 +3501 0 +3502 0 +3503 0 +3504 1 +3505 0 +3506 0 +3507 0 +3508 0 +3509 0 +3510 0 +3511 0 +3512 0 +3513 0 +3514 1 +3515 0 +3516 0 +3517 0 +3518 0 +3519 0 +3520 0 +3521 0 +3522 0 +3523 0 +3524 1 +3525 0 +3526 0 +3527 0 +3528 0 +3529 0 +3530 0 +3531 0 +3532 0 +3533 1 +3534 0 +3535 0 +3536 0 +3537 0 +3538 0 +3539 0 +3540 0 +3541 0 +3542 0 +3543 0 +3544 0 +3545 0 +3546 0 +3547 0 +3548 0 +3549 0 +3550 0 +3551 1 +3552 0 +3553 0 +3554 0 +3555 0 +3556 0 +3557 0 +3558 0 +3559 0 +3560 0 +3561 1 +3562 0 +3563 0 +3564 0 +3565 0 +3566 0 +3567 0 +3568 0 +3569 0 +3570 1 +3571 0 +3572 0 +3573 0 +3574 0 +3575 0 +3576 0 +3577 0 +3578 0 +3579 0 +3580 1 +3581 0 +3582 0 +3583 0 +3584 0 +3585 0 +3586 0 +3587 0 +3588 0 +3589 0 +3590 1 +3591 0 +3592 0 +3593 0 +3594 0 +3595 0 +3596 0 +3597 0 +3598 0 +3599 1 +3600 0 +3601 0 +3602 0 +3603 0 +3604 0 +3605 0 +3606 0 +3607 0 +3608 0 +3609 1 +3610 0 +3611 0 +3612 0 +3613 0 +3614 0 +3615 0 +3616 0 +3617 0 +3618 0 +3619 0 +3620 1 +3621 0 +3622 0 +3623 0 +3624 0 +3625 0 +3626 0 +3627 0 +3628 0 +3629 0 +3630 1 +3631 0 +3632 0 +3633 0 +3634 0 +3635 0 +3636 0 +3637 0 +3638 0 +3639 1 +3640 0 +3641 0 +3642 0 +3643 0 +3644 0 +3645 1 +3646 0 +3647 0 +3648 0 +3649 0 +3650 0 +3651 1 +3652 0 +3653 0 +3654 0 +3655 0 +3656 0 +3657 0 +3658 1 +3659 0 +3660 0 +3661 0 +3662 0 +3663 0 +3664 0 +3665 0 +3666 1 +3667 0 +3668 0 +3669 0 +3670 0 +3671 0 +3672 0 +3673 0 +3674 0 +3675 0 +3676 1 +3677 0 +3678 0 +3679 0 +3680 0 +3681 0 +3682 0 +3683 0 +3684 0 +3685 1 +3686 0 +3687 0 +3688 0 +3689 0 +3690 0 +3691 0 +3692 0 +3693 0 +3694 0 +3695 1 +3696 0 +3697 0 +3698 0 +3699 0 +3700 0 +3701 0 +3702 0 +3703 0 +3704 0 +3705 0 +3706 1 +3707 0 +3708 0 +3709 0 +3710 0 +3711 0 +3712 0 +3713 0 +3714 0 +3715 0 +3716 1 +3717 0 +3718 0 +3719 0 +3720 0 +3721 0 +3722 0 +3723 0 +3724 0 +3725 0 +3726 0 +3727 0 +3728 0 +3729 0 +3730 0 +3731 0 +3732 0 +3733 0 +3734 0 +3735 0 +3736 1 +3737 0 +3738 0 +3739 0 +3740 0 +3741 0 +3742 0 +3743 0 +3744 0 +3745 0 +3746 1 +3747 0 +3748 0 +3749 0 +3750 0 +3751 0 +3752 0 +3753 0 +3754 0 +3755 0 +3756 1 +3757 0 +3758 0 +3759 0 +3760 0 +3761 0 +3762 0 +3763 1 +3764 0 +3765 0 +3766 0 +3767 0 +3768 0 +3769 0 +3770 0 +3771 1 +3772 0 +3773 0 +3774 0 +3775 0 +3776 0 +3777 0 +3778 1 +3779 0 +3780 0 +3781 0 +3782 0 +3783 0 +3784 0 +3785 0 +3786 0 +3787 0 +3788 0 +3789 0 +3790 0 +3791 0 +3792 0 +3793 0 +3794 0 +3795 0 +3796 0 +3797 1 +3798 0 +3799 0 +3800 0 +3801 0 +3802 0 +3803 0 +3804 0 +3805 0 +3806 1 +3807 0 +3808 0 +3809 0 +3810 0 +3811 0 +3812 0 +3813 0 +3814 0 +3815 0 +3816 0 +3817 1 +3818 0 +3819 0 +3820 0 +3821 0 +3822 0 +3823 0 +3824 0 +3825 0 +3826 0 +3827 1 +3828 0 +3829 1 +3830 0 +3831 0 +3832 0 +3833 0 +3834 1 +3835 0 +3836 0 +3837 0 +3838 0 +3839 0 +3840 0 +3841 0 +3842 0 +3843 0 +3844 0 +3845 1 +3846 0 +3847 0 +3848 0 +3849 0 +3850 0 +3851 0 +3852 0 +3853 0 +3854 0 +3855 1 +3856 0 +3857 0 +3858 0 +3859 0 +3860 0 +3861 0 +3862 0 +3863 1 +3864 0 +3865 0 +3866 0 +3867 0 +3868 0 +3869 0 +3870 0 +3871 0 +3872 0 +3873 1 +3874 0 +3875 0 +3876 0 +3877 0 +3878 0 +3879 0 +3880 0 +3881 0 +3882 0 +3883 1 +3884 0 +3885 0 +3886 0 +3887 0 +3888 0 +3889 0 +3890 0 +3891 0 +3892 0 +3893 0 +3894 1 +3895 0 +3896 0 +3897 0 +3898 0 +3899 0 +3900 0 +3901 0 +3902 0 +3903 0 +3904 0 +3905 1 +3906 0 +3907 0 +3908 0 +3909 0 +3910 0 +3911 0 +3912 0 +3913 0 +3914 1 +3915 0 +3916 0 +3917 0 +3918 0 +3919 0 +3920 0 +3921 0 +3922 0 +3923 0 +3924 0 +3925 1 +3926 0 +3927 0 +3928 0 +3929 0 +3930 0 +3931 0 +3932 0 +3933 0 +3934 1 +3935 0 +3936 0 +3937 0 +3938 0 +3939 0 +3940 0 +3941 0 +3942 0 +3943 0 +3944 0 +3945 1 +3946 0 +3947 0 +3948 0 +3949 0 +3950 0 +3951 0 +3952 0 +3953 0 +3954 0 +3955 1 +3956 0 +3957 0 +3958 0 +3959 0 +3960 0 +3961 0 +3962 0 +3963 0 +3964 0 +3965 0 +3966 1 +3967 0 +3968 0 +3969 0 +3970 0 +3971 0 +3972 0 +3973 0 +3974 0 +3975 1 +3976 0 +3977 0 +3978 0 +3979 0 +3980 0 +3981 0 +3982 0 +3983 0 +3984 1 +3985 0 +3986 0 +3987 0 +3988 0 +3989 0 +3990 0 +3991 0 +3992 0 +3993 0 +3994 1 +3995 0 +3996 0 +3997 0 +3998 0 +3999 0 +4000 0 +4001 0 +4002 0 +4003 0 +4004 0 +4005 0 +4006 0 +4007 0 +4008 0 +4009 0 +4010 0 +4011 0 +4012 0 +4013 0 +4014 1 +4015 0 +4016 0 +4017 0 +4018 0 +4019 0 +4020 0 +4021 0 +4022 0 +4023 0 +4024 1 +4025 0 +4026 0 +4027 0 +4028 0 +4029 0 +4030 0 +4031 0 +4032 0 +4033 0 +4034 0 +4035 1 +4036 0 +4037 0 +4038 0 +4039 0 +4040 0 +4041 0 +4042 0 +4043 0 +4044 0 +4045 1 +4046 0 +4047 0 +4048 0 +4049 0 +4050 0 +4051 0 +4052 0 +4053 0 +4054 0 +4055 0 +4056 1 +4057 0 +4058 0 +4059 0 +4060 0 +4061 0 +4062 0 +4063 0 +4064 0 +4065 0 +4066 1 +4067 0 +4068 0 +4069 0 +4070 0 +4071 0 +4072 0 +4073 0 +4074 1 +4075 0 +4076 0 +4077 0 +4078 0 +4079 0 +4080 0 +4081 0 +4082 0 +4083 0 +4084 1 +4085 0 +4086 0 +4087 0 +4088 0 +4089 0 +4090 0 +4091 0 +4092 0 +4093 1 +4094 0 +4095 0 +4096 0 +4097 0 +4098 0 +4099 0 +4100 0 +4101 0 +4102 1 +4103 0 +4104 0 +4105 0 +4106 0 +4107 0 +4108 0 +4109 0 +4110 0 +4111 0 +4112 1 +4113 0 +4114 0 +4115 0 +4116 0 +4117 0 +4118 0 +4119 0 +4120 0 +4121 0 +4122 1 +4123 0 +4124 0 +4125 0 +4126 0 +4127 0 +4128 0 +4129 0 +4130 0 +4131 0 +4132 0 +4133 1 +4134 0 +4135 0 +4136 0 +4137 0 +4138 0 +4139 0 +4140 0 +4141 0 +4142 0 +4143 0 +4144 1 +4145 0 +4146 0 +4147 0 +4148 0 +4149 0 +4150 0 +4151 0 +4152 0 +4153 0 +4154 1 +4155 0 +4156 0 +4157 0 +4158 0 +4159 0 +4160 0 +4161 0 +4162 0 +4163 0 +4164 0 +4165 1 +4166 0 +4167 0 +4168 0 +4169 0 +4170 0 +4171 0 +4172 0 +4173 0 +4174 0 +4175 0 +4176 1 +4177 0 +4178 0 +4179 0 +4180 0 +4181 0 +4182 0 +4183 0 +4184 0 +4185 1 +4186 0 +4187 0 +4188 0 +4189 0 +4190 0 +4191 0 +4192 0 +4193 0 +4194 0 +4195 1 +4196 0 +4197 0 +4198 0 +4199 0 +4200 0 +4201 0 +4202 0 +4203 0 +4204 0 +4205 0 +4206 0 +4207 0 +4208 0 +4209 0 +4210 0 +4211 0 +4212 1 +4213 0 +4214 0 +4215 0 +4216 0 +4217 0 +4218 0 +4219 0 +4220 0 +4221 1 +4222 0 +4223 0 +4224 0 +4225 0 +4226 0 +4227 0 +4228 0 +4229 0 +4230 1 +4231 0 +4232 0 +4233 0 +4234 0 +4235 0 +4236 0 +4237 0 +4238 0 +4239 1 +4240 0 +4241 0 +4242 0 +4243 0 +4244 0 +4245 0 +4246 0 +4247 0 +4248 0 +4249 1 +4250 0 +4251 0 +4252 0 +4253 0 +4254 0 +4255 0 +4256 0 +4257 0 +4258 1 +4259 0 +4260 0 +4261 0 +4262 0 +4263 0 +4264 0 +4265 0 +4266 0 +4267 0 +4268 1 +4269 0 +4270 0 +4271 0 +4272 0 +4273 0 +4274 0 +4275 0 +4276 0 +4277 0 +4278 1 +4279 0 +4280 0 +4281 0 +4282 0 +4283 0 +4284 0 +4285 0 +4286 0 +4287 0 +4288 0 +4289 1 +4290 0 +4291 0 +4292 0 +4293 0 +4294 0 +4295 0 +4296 0 +4297 0 +4298 0 +4299 1 +4300 0 +4301 0 +4302 0 +4303 0 +4304 0 +4305 0 +4306 0 +4307 0 +4308 0 +4309 1 +4310 0 +4311 0 +4312 0 +4313 0 +4314 0 +4315 0 +4316 0 +4317 0 +4318 1 +4319 0 +4320 0 +4321 0 +4322 0 +4323 0 +4324 0 +4325 0 +4326 0 +4327 1 +4328 0 +4329 0 +4330 0 +4331 0 +4332 0 +4333 0 +4334 0 +4335 0 +4336 0 +4337 1 +4338 0 +4339 0 +4340 0 +4341 0 +4342 0 +4343 0 +4344 0 +4345 0 +4346 0 +4347 1 +4348 0 +4349 0 +4350 0 +4351 0 +4352 0 +4353 0 +4354 0 +4355 1 +4356 0 +4357 0 +4358 0 +4359 0 +4360 0 +4361 0 +4362 0 +4363 0 +4364 0 +4365 0 +4366 0 +4367 0 +4368 0 +4369 0 +4370 0 +4371 0 +4372 0 +4373 0 +4374 1 +4375 0 +4376 0 +4377 0 +4378 0 +4379 0 +4380 0 +4381 0 +4382 0 +4383 0 +4384 1 +4385 0 +4386 0 +4387 0 +4388 0 +4389 0 +4390 0 +4391 0 +4392 0 +4393 1 +4394 0 +4395 0 +4396 0 +4397 0 +4398 0 +4399 0 +4400 0 +4401 0 +4402 0 +4403 1 +4404 0 +4405 0 +4406 0 +4407 0 +4408 0 +4409 0 +4410 0 +4411 0 +4412 1 +4413 0 +4414 0 +4415 0 +4416 0 +4417 0 +4418 0 +4419 0 +4420 0 +4421 0 +4422 0 +4423 1 +4424 0 +4425 0 +4426 0 +4427 0 +4428 0 +4429 0 +4430 2 +4431 0 +4432 0 +4433 0 +4434 0 +4435 0 +4436 0 +4437 1 +4438 0 +4439 0 +4440 0 +4441 0 +4442 0 +4443 0 +4444 0 +4445 1 +4446 0 +4447 0 +4448 0 +4449 0 +4450 0 +4451 0 +4452 0 +4453 0 +4454 1 +4455 0 +4456 0 +4457 0 +4458 0 +4459 0 +4460 0 +4461 0 +4462 1 +4463 0 +4464 0 +4465 0 +4466 0 +4467 0 +4468 0 +4469 0 +4470 0 +4471 1 +4472 0 +4473 0 +4474 0 +4475 0 +4476 0 +4477 0 +4478 0 +4479 0 +4480 1 +4481 0 +4482 0 +4483 0 +4484 0 +4485 0 +4486 0 +4487 0 +4488 1 +4489 0 +4490 0 +4491 0 +4492 0 +4493 0 +4494 0 +4495 0 +4496 0 +4497 1 +4498 0 +4499 0 +4500 0 +4501 0 +4502 0 +4503 0 +4504 0 +4505 1 +4506 0 +4507 0 +4508 0 +4509 0 +4510 0 +4511 0 +4512 0 +4513 1 +4514 0 +4515 0 +4516 0 +4517 0 +4518 0 +4519 0 +4520 1 +4521 0 +4522 0 +4523 0 +4524 0 +4525 0 +4526 0 +4527 0 +4528 0 +4529 1 +4530 0 +4531 0 +4532 0 +4533 0 +4534 0 +4535 0 +4536 0 +4537 0 +4538 1 +4539 0 +4540 0 +4541 0 +4542 0 +4543 0 +4544 0 +4545 0 +4546 1 +4547 0 +4548 0 +4549 0 +4550 0 +4551 0 +4552 1 +4553 0 +4554 0 +4555 0 +4556 0 +4557 0 +4558 0 +4559 1 +4560 0 +4561 0 +4562 0 +4563 0 +4564 0 +4565 0 +4566 0 +4567 1 +4568 0 +4569 0 +4570 0 +4571 0 +4572 0 +4573 0 +4574 0 +4575 1 +4576 0 +4577 0 +4578 0 +4579 0 +4580 0 +4581 0 +4582 0 +4583 1 +4584 0 +4585 0 +4586 0 +4587 0 +4588 0 +4589 0 +4590 0 +4591 1 +4592 0 +4593 0 +4594 0 +4595 0 +4596 0 +4597 0 +4598 0 +4599 0 +4600 1 +4601 0 +4602 0 +4603 0 +4604 0 +4605 0 +4606 0 +4607 1 +4608 0 +4609 0 +4610 0 +4611 0 +4612 0 +4613 0 +4614 0 +4615 0 +4616 1 +4617 0 +4618 0 +4619 0 +4620 0 +4621 0 +4622 0 +4623 0 +4624 0 +4625 1 +4626 0 +4627 0 +4628 0 +4629 0 +4630 0 +4631 0 +4632 0 +4633 0 +4634 1 +4635 0 +4636 0 +4637 0 +4638 0 +4639 0 +4640 0 +4641 0 +4642 0 +4643 0 +4644 0 +4645 0 +4646 0 +4647 0 +4648 0 +4649 0 +4650 0 +4651 0 +4652 1 +4653 0 +4654 0 +4655 0 +4656 0 +4657 0 +4658 0 +4659 0 +4660 0 +4661 1 +4662 0 +4663 0 +4664 0 +4665 1 +4666 0 +4667 0 +4668 0 +4669 0 +4670 0 +4671 0 +4672 1 +4673 0 +4674 0 +4675 0 +4676 0 +4677 0 +4678 1 +4679 0 +4680 0 +4681 0 +4682 0 +4683 0 +4684 0 +4685 0 +4686 1 +4687 0 +4688 0 +4689 0 +4690 0 +4691 0 +4692 0 +4693 0 +4694 1 +4695 0 +4696 0 +4697 0 +4698 0 +4699 0 +4700 0 +4701 0 +4702 1 +4703 0 +4704 0 +4705 0 +4706 0 +4707 0 +4708 0 +4709 1 +4710 0 +4711 0 +4712 0 +4713 0 +4714 0 +4715 0 +4716 0 +4717 1 +4718 0 +4719 0 +4720 0 +4721 0 +4722 0 +4723 0 +4724 0 +4725 1 +4726 0 +4727 0 +4728 0 +4729 0 +4730 0 +4731 0 +4732 0 +4733 0 +4734 1 +4735 0 +4736 0 +4737 0 +4738 0 +4739 0 +4740 0 +4741 0 +4742 0 +4743 0 +4744 1 +4745 0 +4746 0 +4747 0 +4748 0 +4749 0 +4750 0 +4751 0 +4752 1 +4753 0 +4754 0 +4755 0 +4756 0 +4757 0 +4758 0 +4759 0 +4760 1 +4761 0 +4762 0 +4763 0 +4764 0 +4765 0 +4766 0 +4767 0 +4768 0 +4769 1 +4770 0 +4771 0 +4772 0 +4773 0 +4774 0 +4775 0 +4776 0 +4777 0 +4778 1 +4779 0 +4780 0 +4781 0 +4782 0 +4783 0 +4784 0 +4785 0 +4786 1 +4787 0 +4788 0 +4789 0 +4790 0 +4791 0 +4792 0 +4793 0 +4794 0 +4795 0 +4796 1 +4797 0 +4798 0 +4799 0 +4800 0 +4801 0 +4802 0 +4803 0 +4804 1 +4805 0 +4806 0 +4807 0 +4808 0 +4809 0 +4810 0 +4811 0 +4812 0 +4813 1 +4814 0 +4815 0 +4816 0 +4817 0 +4818 0 +4819 0 +4820 0 +4821 0 +4822 1 +4823 0 +4824 0 +4825 0 +4826 0 +4827 0 +4828 0 +4829 0 +4830 0 +4831 1 +4832 0 +4833 0 +4834 0 +4835 0 +4836 0 +4837 0 +4838 0 +4839 0 +4840 0 +4841 0 +4842 0 +4843 0 +4844 0 +4845 0 +4846 0 +4847 0 +4848 0 +4849 0 +4850 0 +4851 0 +4852 0 +4853 0 +4854 0 +4855 0 +4856 0 +4857 0 +4858 0 +4859 0 +4860 0 +4861 0 +4862 0 +4863 0 +4864 0 +4865 1 +4866 0 +4867 0 +4868 0 +4869 0 +4870 0 +4871 0 +4872 1 +4873 0 +4874 0 +4875 0 +4876 0 +4877 0 +4878 0 +4879 0 +4880 1 +4881 0 +4882 0 +4883 0 +4884 0 +4885 0 +4886 0 +4887 0 +4888 0 +4889 0 +4890 1 +4891 0 +4892 0 +4893 0 +4894 0 +4895 0 +4896 0 +4897 0 +4898 1 +4899 0 +4900 0 +4901 0 +4902 0 +4903 0 +4904 0 +4905 1 +4906 0 +4907 0 +4908 0 +4909 0 +4910 0 +4911 0 +4912 0 +4913 1 +4914 0 +4915 0 +4916 0 +4917 0 +4918 0 +4919 0 +4920 0 +4921 0 +4922 0 +4923 1 +4924 0 +4925 0 +4926 0 +4927 0 +4928 0 +4929 0 +4930 0 +4931 0 +4932 0 +4933 1 +4934 0 +4935 0 +4936 0 +4937 0 +4938 0 +4939 0 +4940 0 +4941 0 +4942 0 +4943 0 +4944 0 +4945 0 +4946 0 +4947 0 +4948 1 +4949 0 +4950 0 +4951 0 +4952 0 +4953 0 +4954 0 +4955 0 +4956 1 +4957 0 +4958 0 +4959 0 +4960 0 +4961 0 +4962 0 +4963 0 +4964 1 +4965 0 +4966 0 +4967 0 +4968 0 +4969 0 +4970 0 +4971 0 +4972 1 +4973 0 +4974 0 +4975 0 +4976 0 +4977 0 +4978 0 +4979 1 +4980 0 +4981 0 +4982 0 +4983 0 +4984 0 +4985 0 +4986 0 +4987 1 +4988 0 +4989 0 +4990 0 +4991 0 +4992 0 +4993 0 +4994 1 +4995 0 +4996 0 +4997 0 +4998 0 +4999 0 +5000 0 +5001 0 +5002 0 +5003 1 +5004 0 +5005 0 +5006 0 +5007 0 +5008 0 +5009 0 +5010 0 +5011 0 +5012 1 +5013 0 +5014 0 +5015 0 +5016 0 +5017 0 +5018 0 +5019 0 +5020 1 +5021 0 +5022 0 +5023 0 +5024 0 +5025 0 +5026 0 +5027 0 +5028 0 +5029 1 +5030 0 +5031 0 +5032 0 +5033 0 +5034 0 +5035 0 +5036 0 +5037 1 +5038 0 +5039 0 +5040 0 +5041 0 +5042 0 +5043 0 +5044 0 +5045 1 +5046 0 +5047 0 +5048 0 +5049 0 +5050 0 +5051 0 +5052 0 +5053 1 +5054 0 +5055 0 +5056 0 +5057 0 +5058 0 +5059 0 +5060 0 +5061 0 +5062 1 +5063 0 +5064 0 +5065 0 +5066 0 +5067 0 +5068 0 +5069 0 +5070 0 +5071 0 +5072 0 +5073 0 +5074 0 +5075 0 +5076 0 +5077 0 +5078 0 +5079 1 +5080 0 +5081 0 +5082 0 +5083 0 +5084 0 +5085 0 +5086 1 +5087 0 +5088 0 +5089 0 +5090 0 +5091 0 +5092 0 +5093 0 +5094 1 +5095 0 +5096 0 +5097 0 +5098 0 +5099 0 +5100 0 +5101 0 +5102 0 +5103 1 +5104 0 +5105 0 +5106 0 +5107 0 +5108 0 +5109 0 +5110 1 +5111 0 +5112 0 +5113 0 +5114 0 +5115 0 +5116 0 +5117 0 +5118 1 +5119 0 +5120 0 +5121 0 +5122 0 +5123 0 +5124 0 +5125 0 +5126 0 +5127 1 +5128 0 +5129 0 +5130 0 +5131 0 +5132 0 +5133 0 +5134 1 +5135 0 +5136 0 +5137 0 +5138 0 +5139 0 +5140 0 +5141 1 +5142 0 +5143 0 +5144 0 +5145 0 +5146 0 +5147 0 +5148 0 +5149 1 +5150 0 +5151 0 +5152 0 +5153 0 +5154 0 +5155 0 +5156 0 +5157 0 +5158 1 +5159 0 +5160 0 +5161 0 +5162 0 +5163 0 +5164 0 +5165 0 +5166 0 +5167 1 +5168 0 +5169 0 +5170 0 +5171 0 +5172 0 +5173 0 +5174 0 +5175 1 +5176 0 +5177 0 +5178 0 +5179 0 +5180 0 +5181 0 +5182 1 +5183 0 +5184 0 +5185 0 +5186 0 +5187 0 +5188 0 +5189 0 +5190 1 +5191 0 +5192 0 +5193 0 +5194 0 +5195 0 +5196 0 +5197 0 +5198 0 +5199 1 +5200 0 +5201 0 +5202 0 +5203 0 +5204 0 +5205 0 +5206 0 +5207 0 +5208 1 +5209 0 +5210 0 +5211 0 +5212 0 +5213 0 +5214 0 +5215 0 +5216 0 +5217 0 +5218 1 +5219 0 +5220 0 +5221 0 +5222 0 +5223 0 +5224 0 +5225 0 +5226 1 +5227 0 +5228 0 +5229 0 +5230 0 +5231 0 +5232 0 +5233 0 +5234 1 +5235 0 +5236 0 +5237 0 +5238 0 +5239 0 +5240 0 +5241 0 +5242 1 +5243 0 +5244 0 +5245 0 +5246 0 +5247 0 +5248 0 +5249 0 +5250 0 +5251 1 +5252 0 +5253 0 +5254 0 +5255 0 +5256 0 +5257 0 +5258 0 +5259 0 +5260 0 +5261 0 +5262 0 +5263 0 +5264 0 +5265 0 +5266 0 +5267 0 +5268 1 +5269 0 +5270 0 +5271 0 +5272 0 +5273 0 +5274 0 +5275 0 +5276 1 +5277 0 +5278 0 +5279 0 +5280 0 +5281 0 +5282 0 +5283 1 +5284 0 +5285 0 +5286 0 +5287 0 +5288 0 +5289 0 +5290 0 +5291 0 +5292 0 +5293 1 +5294 0 +5295 0 +5296 0 +5297 0 +5298 0 +5299 0 +5300 0 +5301 1 +5302 0 +5303 0 +5304 0 +5305 0 +5306 0 +5307 0 +5308 0 +5309 0 +5310 1 +5311 0 +5312 0 +5313 0 +5314 0 +5315 0 +5316 0 +5317 0 +5318 1 +5319 0 +5320 0 +5321 0 +5322 0 +5323 0 +5324 0 +5325 1 +5326 0 +5327 0 +5328 0 +5329 0 +5330 0 +5331 0 +5332 0 +5333 0 +5334 0 +5335 0 +5336 0 +5337 0 +5338 0 +5339 0 +5340 0 +5341 0 +5342 1 +5343 0 +5344 0 +5345 0 +5346 0 +5347 0 +5348 0 +5349 1 +5350 0 +5351 0 +5352 0 +5353 0 +5354 0 +5355 0 +5356 0 +5357 0 +5358 1 +5359 0 +5360 0 +5361 0 +5362 0 +5363 0 +5364 0 +5365 0 +5366 1 +5367 0 +5368 0 +5369 0 +5370 0 +5371 0 +5372 0 +5373 1 +5374 0 +5375 0 +5376 0 +5377 0 +5378 0 +5379 0 +5380 0 +5381 1 +5382 0 +5383 0 +5384 0 +5385 0 +5386 0 +5387 0 +5388 0 +5389 0 +5390 1 +5391 0 +5392 0 +5393 0 +5394 0 +5395 0 +5396 0 +5397 0 +5398 1 +5399 0 +5400 0 +5401 0 +5402 0 +5403 0 +5404 0 +5405 0 +5406 1 +5407 0 +5408 0 +5409 0 +5410 0 +5411 0 +5412 0 +5413 0 +5414 1 +5415 0 +5416 0 +5417 0 +5418 0 +5419 0 +5420 0 +5421 0 +5422 1 +5423 0 +5424 0 +5425 0 +5426 0 +5427 0 +5428 0 +5429 0 +5430 0 +5431 0 +5432 0 +5433 0 +5434 0 +5435 0 +5436 0 +5437 0 +5438 1 +5439 0 +5440 0 +5441 0 +5442 0 +5443 0 +5444 0 +5445 0 +5446 0 +5447 1 +5448 0 +5449 0 +5450 0 +5451 0 +5452 0 +5453 0 +5454 0 +5455 0 +5456 1 +5457 0 +5458 0 +5459 0 +5460 0 +5461 0 +5462 0 +5463 0 +5464 1 +5465 0 +5466 0 +5467 0 +5468 0 +5469 0 +5470 0 +5471 0 +5472 1 +5473 0 +5474 0 +5475 0 +5476 0 +5477 0 +5478 0 +5479 0 +5480 0 +5481 1 +5482 0 +5483 0 +5484 0 +5485 0 +5486 0 +5487 0 +5488 0 +5489 1 +5490 0 +5491 0 +5492 0 +5493 0 +5494 0 +5495 0 +5496 0 +5497 0 +5498 1 +5499 0 +5500 0 +5501 0 +5502 0 +5503 0 +5504 0 +5505 0 +5506 1 +5507 0 +5508 0 +5509 0 +5510 0 +5511 0 +5512 0 +5513 0 +5514 1 +5515 0 +5516 0 +5517 0 +5518 0 +5519 0 +5520 0 +5521 0 +5522 0 +5523 1 +5524 0 +5525 0 +5526 0 +5527 0 +5528 0 +5529 0 +5530 0 +5531 1 +5532 0 +5533 0 +5534 0 +5535 0 +5536 0 +5537 0 +5538 0 +5539 0 +5540 1 +5541 0 +5542 0 +5543 0 +5544 0 +5545 0 +5546 0 +5547 0 +5548 0 +5549 1 +5550 0 +5551 0 +5552 0 +5553 0 +5554 0 +5555 0 +5556 0 +5557 0 +5558 0 +5559 0 +5560 0 +5561 0 +5562 0 +5563 0 +5564 0 +5565 1 +5566 0 +5567 0 +5568 0 +5569 0 +5570 0 +5571 1 +5572 0 +5573 0 +5574 0 +5575 0 +5576 0 +5577 0 +5578 0 +5579 1 +5580 0 +5581 0 +5582 0 +5583 0 +5584 0 +5585 0 +5586 0 +5587 0 +5588 1 +5589 0 +5590 0 +5591 0 +5592 0 +5593 0 +5594 0 +5595 0 +5596 1 +5597 0 +5598 0 +5599 0 +5600 0 +5601 0 +5602 0 +5603 0 +5604 0 +5605 0 +5606 1 +5607 0 +5608 0 +5609 0 +5610 0 +5611 0 +5612 0 +5613 0 +5614 1 +5615 0 +5616 0 +5617 0 +5618 0 +5619 0 +5620 0 +5621 0 +5622 1 +5623 0 +5624 0 +5625 0 +5626 0 +5627 0 +5628 0 +5629 0 +5630 0 +5631 0 +5632 0 +5633 0 +5634 0 +5635 0 +5636 0 +5637 0 +5638 1 +5639 0 +5640 0 +5641 0 +5642 0 +5643 0 +5644 0 +5645 0 +5646 0 +5647 1 +5648 0 +5649 0 +5650 0 +5651 0 +5652 0 +5653 0 +5654 1 +5655 0 +5656 0 +5657 0 +5658 0 +5659 0 +5660 0 +5661 0 +5662 1 +5663 0 +5664 0 +5665 0 +5666 0 +5667 0 +5668 0 +5669 0 +5670 1 +5671 0 +5672 0 +5673 0 +5674 0 +5675 0 +5676 0 +5677 0 +5678 0 +5679 1 +5680 2 +5681 1 +5682 0 +5683 0 +5684 0 +5685 0 +5686 0 +5687 1 +5688 0 +5689 0 +5690 0 +5691 0 +5692 1 +5693 0 +5694 0 +5695 0 +5696 0 +5697 1 +5698 0 +5699 0 +5700 0 +5701 0 +5702 0 +5703 0 +5704 0 +5705 1 +5706 0 +5707 0 +5708 0 +5709 0 +5710 0 +5711 1 +5712 0 +5713 0 +5714 0 +5715 0 +5716 0 +5717 0 +5718 0 +5719 0 +5720 0 +5721 0 +5722 0 +5723 0 +5724 0 +5725 0 +5726 1 +5727 0 +5728 0 +5729 0 +5730 0 +5731 0 +5732 0 +5733 0 +5734 1 +5735 0 +5736 0 +5737 0 +5738 0 +5739 0 +5740 0 +5741 0 +5742 1 +5743 0 +5744 0 +5745 0 +5746 0 +5747 0 +5748 0 +5749 0 +5750 0 +5751 1 +5752 0 +5753 0 +5754 0 +5755 0 +5756 0 +5757 0 +5758 0 +5759 1 +5760 0 +5761 0 +5762 0 +5763 0 +5764 0 +5765 0 +5766 1 +5767 0 +5768 0 +5769 0 +5770 0 +5771 0 +5772 0 +5773 0 +5774 1 +5775 0 +5776 0 +5777 0 +5778 0 +5779 0 +5780 0 +5781 0 +5782 1 +5783 0 +5784 0 +5785 0 +5786 0 +5787 0 +5788 0 +5789 0 +5790 0 +5791 1 +5792 0 +5793 0 +5794 0 +5795 0 +5796 0 +5797 0 +5798 0 +5799 0 +5800 1 +5801 0 +5802 0 +5803 0 +5804 0 +5805 0 +5806 0 +5807 0 +5808 0 +5809 1 +5810 0 +5811 0 +5812 0 +5813 0 +5814 0 +5815 0 +5816 1 +5817 0 +5818 0 +5819 0 +5820 0 +5821 0 +5822 0 +5823 0 +5824 0 +5825 1 +5826 0 +5827 0 +5828 0 +5829 0 +5830 0 +5831 0 +5832 0 +5833 0 +5834 1 +5835 0 +5836 0 +5837 0 +5838 0 +5839 0 +5840 0 +5841 0 +5842 1 +5843 0 +5844 0 +5845 0 +5846 0 +5847 0 +5848 0 +5849 0 +5850 1 +5851 0 +5852 0 +5853 0 +5854 0 +5855 0 +5856 0 +5857 0 +5858 1 +5859 0 +5860 0 +5861 0 +5862 0 +5863 0 +5864 0 +5865 0 +5866 0 +5867 1 +5868 0 +5869 0 +5870 0 +5871 0 +5872 0 +5873 0 +5874 0 +5875 1 +5876 0 +5877 0 +5878 0 +5879 0 +5880 0 +5881 0 +5882 0 +5883 0 +5884 1 +5885 0 +5886 0 +5887 0 +5888 0 +5889 0 +5890 0 +5891 1 +5892 0 +5893 0 +5894 0 +5895 0 +5896 0 +5897 0 +5898 0 +5899 0 +5900 1 +5901 0 +5902 0 +5903 0 +5904 0 +5905 0 +5906 0 +5907 0 +5908 0 +5909 1 +5910 0 +5911 0 +5912 0 +5913 0 +5914 0 +5915 0 +5916 0 +5917 1 +5918 0 +5919 0 +5920 0 +5921 0 +5922 0 +5923 0 +5924 0 +5925 0 +5926 1 +5927 0 +5928 0 +5929 0 +5930 0 +5931 0 +5932 0 +5933 0 +5934 1 +5935 0 +5936 0 +5937 0 +5938 0 +5939 0 +5940 0 +5941 0 +5942 0 +5943 0 +5944 1 +5945 0 +5946 0 +5947 0 +5948 0 +5949 0 +5950 0 +5951 0 +5952 0 +5953 0 +5954 0 +5955 0 +5956 0 +5957 0 +5958 0 +5959 0 +5960 0 +5961 0 +5962 0 +5963 0 +5964 0 +5965 0 +5966 0 +5967 0 +5968 0 +5969 0 +5970 1 +5971 0 +5972 0 +5973 0 +5974 0 +5975 0 +5976 0 +5977 0 +5978 1 +5979 0 +5980 0 +5981 0 +5982 0 +5983 0 +5984 0 +5985 0 +5986 0 +5987 1 +5988 0 +5989 0 +5990 0 +5991 0 +5992 0 +5993 0 +5994 0 +5995 0 +5996 1 +5997 0 +5998 0 +5999 0 +6000 0 +6001 0 +6002 0 +6003 0 +6004 0 +6005 0 +6006 1 +6007 0 +6008 0 +6009 0 +6010 0 +6011 0 +6012 0 +6013 0 +6014 1 +6015 0 +6016 0 +6017 0 +6018 0 +6019 0 +6020 0 +6021 0 +6022 0 +6023 1 +6024 0 +6025 0 +6026 0 +6027 0 +6028 0 +6029 0 +6030 0 +6031 1 +6032 0 +6033 0 +6034 0 +6035 0 +6036 0 +6037 0 +6038 1 +6039 0 +6040 0 +6041 0 +6042 0 +6043 0 +6044 0 +6045 0 +6046 0 +6047 0 +6048 1 +6049 0 +6050 0 +6051 0 +6052 0 +6053 0 +6054 0 +6055 1 +6056 0 +6057 0 +6058 0 +6059 0 +6060 0 +6061 1 +6062 0 +6063 0 +6064 0 +6065 0 +6066 0 +6067 0 +6068 1 +6069 0 +6070 0 +6071 0 +6072 0 +6073 0 +6074 0 +6075 0 +6076 1 +6077 0 +6078 0 +6079 0 +6080 0 +6081 0 +6082 0 +6083 0 +6084 0 +6085 1 +6086 0 +6087 0 +6088 0 +6089 0 +6090 0 +6091 0 +6092 0 +6093 0 +6094 0 +6095 1 +6096 0 +6097 0 +6098 0 +6099 0 +6100 0 +6101 0 +6102 0 +6103 0 +6104 1 +6105 0 +6106 0 +6107 0 +6108 0 +6109 0 +6110 0 +6111 0 +6112 1 +6113 0 +6114 0 +6115 0 +6116 0 +6117 0 +6118 0 +6119 0 +6120 0 +6121 0 +6122 0 +6123 0 +6124 0 +6125 1 +6126 0 +6127 0 +6128 0 +6129 0 +6130 0 +6131 0 +6132 0 +6133 0 +6134 0 +6135 0 +6136 0 +6137 0 +6138 0 +6139 0 +6140 0 +6141 0 +6142 1 +6143 0 +6144 0 +6145 0 +6146 0 +6147 0 +6148 0 +6149 0 +6150 1 +6151 0 +6152 0 +6153 0 +6154 0 +6155 0 +6156 0 +6157 0 +6158 0 +6159 1 +6160 0 +6161 0 +6162 0 +6163 0 +6164 0 +6165 0 +6166 0 +6167 1 +6168 0 +6169 0 +6170 0 +6171 0 +6172 0 +6173 0 +6174 0 +6175 1 +6176 0 +6177 0 +6178 0 +6179 0 +6180 0 +6181 0 +6182 0 +6183 1 +6184 0 +6185 0 +6186 0 +6187 0 +6188 0 +6189 0 +6190 0 +6191 0 +6192 1 +6193 0 +6194 0 +6195 0 +6196 0 +6197 0 +6198 0 +6199 0 +6200 0 +6201 1 +6202 0 +6203 0 +6204 0 +6205 0 +6206 0 +6207 0 +6208 0 +6209 0 +6210 1 +6211 0 +6212 0 +6213 0 +6214 0 +6215 0 +6216 0 +6217 1 +6218 0 +6219 0 +6220 0 +6221 0 +6222 0 +6223 0 +6224 0 +6225 1 +6226 0 +6227 0 +6228 0 +6229 0 +6230 0 +6231 0 +6232 0 +6233 0 +6234 1 +6235 0 +6236 0 +6237 0 +6238 0 +6239 0 +6240 0 +6241 1 +6242 0 +6243 0 +6244 0 +6245 0 +6246 0 +6247 0 +6248 0 +6249 0 +6250 1 +6251 0 +6252 0 +6253 0 +6254 0 +6255 0 +6256 0 +6257 0 +6258 1 +6259 0 +6260 0 +6261 0 +6262 0 +6263 0 +6264 0 +6265 0 +6266 0 +6267 0 +6268 1 +6269 0 +6270 0 +6271 0 +6272 0 +6273 0 +6274 0 +6275 0 +6276 0 +6277 1 +6278 0 +6279 0 +6280 0 +6281 0 +6282 0 +6283 0 +6284 0 +6285 1 +6286 0 +6287 0 +6288 0 +6289 0 +6290 0 +6291 0 +6292 1 +6293 0 +6294 0 +6295 0 +6296 0 +6297 0 +6298 0 +6299 1 +6300 0 +6301 0 +6302 0 +6303 0 +6304 0 +6305 0 +6306 0 +6307 1 +6308 0 +6309 0 +6310 0 +6311 0 +6312 0 +6313 0 +6314 0 +6315 1 +6316 0 +6317 0 +6318 0 +6319 0 +6320 0 +6321 0 +6322 0 +6323 0 +6324 1 +6325 0 +6326 0 +6327 0 +6328 0 +6329 0 +6330 0 +6331 0 +6332 1 +6333 0 +6334 0 +6335 0 +6336 0 +6337 0 +6338 0 +6339 0 +6340 0 +6341 1 +6342 0 +6343 0 +6344 0 +6345 0 +6346 0 +6347 0 +6348 0 +6349 0 +6350 1 +6351 0 +6352 0 +6353 0 +6354 0 +6355 0 +6356 0 +6357 0 +6358 1 +6359 0 +6360 0 +6361 0 +6362 0 +6363 0 +6364 0 +6365 0 +6366 1 +6367 0 +6368 0 +6369 0 +6370 0 +6371 0 +6372 0 +6373 0 +6374 0 +6375 1 +6376 0 +6377 0 +6378 0 +6379 0 +6380 0 +6381 0 +6382 0 +6383 1 +6384 0 +6385 0 +6386 0 +6387 0 +6388 0 +6389 0 +6390 0 +6391 4 +6392 0 +6393 1 +6394 0 +6395 0 +6396 0 +6397 1 +6398 0 +6399 0 +6400 0 +6401 0 +6402 1 +6403 0 +6404 0 +6405 0 +6406 0 +6407 1 +6408 0 +6409 0 +6410 0 +6411 0 +6412 1 +6413 0 +6414 0 +6415 0 +6416 0 +6417 0 +6418 1 +6419 0 +6420 0 +6421 0 +6422 0 +6423 0 +6424 0 +6425 1 +6426 0 +6427 0 +6428 0 +6429 0 +6430 0 +6431 0 +6432 0 +6433 0 +6434 1 +6435 0 +6436 0 +6437 0 +6438 0 +6439 0 +6440 0 +6441 0 +6442 0 +6443 1 +6444 0 +6445 0 +6446 0 +6447 0 +6448 0 +6449 0 +6450 0 +6451 0 +6452 1 +6453 0 +6454 0 +6455 0 +6456 0 +6457 0 +6458 0 +6459 0 +6460 0 +6461 0 +6462 0 +6463 1 +6464 0 +6465 0 +6466 0 +6467 0 +6468 0 +6469 0 +6470 0 +6471 0 +6472 1 +6473 0 +6474 0 +6475 0 +6476 0 +6477 0 +6478 0 +6479 0 +6480 0 +6481 0 +6482 1 +6483 0 +6484 0 +6485 0 +6486 0 +6487 0 +6488 0 +6489 0 +6490 0 +6491 0 +6492 1 +6493 0 +6494 0 +6495 0 +6496 0 +6497 0 +6498 0 +6499 0 +6500 0 +6501 0 +6502 0 +6503 0 +6504 0 +6505 0 +6506 0 +6507 0 +6508 0 +6509 0 +6510 0 +6511 0 +6512 1 +6513 0 +6514 0 +6515 0 +6516 0 +6517 0 +6518 0 +6519 0 +6520 0 +6521 1 +6522 0 +6523 0 +6524 0 +6525 0 +6526 0 +6527 0 +6528 0 +6529 0 +6530 0 +6531 1 +6532 0 +6533 0 +6534 0 +6535 0 +6536 0 +6537 0 +6538 0 +6539 0 +6540 1 +6541 0 +6542 0 +6543 0 +6544 0 +6545 0 +6546 0 +6547 0 +6548 0 +6549 0 +6550 1 +6551 0 +6552 0 +6553 0 +6554 0 +6555 0 +6556 0 +6557 0 +6558 0 +6559 0 +6560 1 +6561 0 +6562 0 +6563 0 +6564 0 +6565 0 +6566 0 +6567 0 +6568 0 +6569 1 +6570 0 +6571 0 +6572 0 +6573 0 +6574 0 +6575 0 +6576 0 +6577 1 +6578 0 +6579 0 +6580 0 +6581 0 +6582 0 +6583 0 +6584 0 +6585 0 +6586 1 +6587 0 +6588 0 +6589 0 +6590 0 +6591 0 +6592 0 +6593 0 +6594 0 +6595 1 +6596 0 +6597 0 +6598 0 +6599 0 +6600 0 +6601 0 +6602 0 +6603 0 +6604 1 +6605 0 +6606 0 +6607 0 +6608 0 +6609 0 +6610 0 +6611 0 +6612 0 +6613 1 +6614 0 +6615 0 +6616 0 +6617 0 +6618 0 +6619 0 +6620 0 +6621 0 +6622 1 +6623 0 +6624 0 +6625 0 +6626 0 +6627 0 +6628 0 +6629 0 +6630 0 +6631 1 +6632 0 +6633 0 +6634 0 +6635 0 +6636 0 +6637 0 +6638 0 +6639 0 +6640 1 +6641 0 +6642 0 +6643 0 +6644 0 +6645 0 +6646 0 +6647 0 +6648 0 +6649 0 +6650 1 +6651 0 +6652 0 +6653 0 +6654 0 +6655 0 +6656 0 +6657 0 +6658 0 +6659 0 +6660 1 +6661 0 +6662 0 +6663 0 +6664 0 +6665 0 +6666 0 +6667 0 +6668 0 +6669 1 +6670 0 +6671 0 +6672 0 +6673 0 +6674 0 +6675 0 +6676 0 +6677 0 +6678 0 +6679 1 +6680 0 +6681 0 +6682 0 +6683 0 +6684 0 +6685 0 +6686 0 +6687 0 +6688 1 +6689 0 +6690 0 +6691 0 +6692 0 +6693 0 +6694 0 +6695 0 +6696 0 +6697 0 +6698 1 +6699 0 +6700 0 +6701 0 +6702 0 +6703 0 +6704 0 +6705 0 +6706 1 +6707 0 +6708 0 +6709 0 +6710 0 +6711 0 +6712 0 +6713 0 +6714 0 +6715 0 +6716 1 +6717 0 +6718 0 +6719 0 +6720 0 +6721 0 +6722 0 +6723 0 +6724 0 +6725 0 +6726 1 +6727 0 +6728 0 +6729 0 +6730 0 +6731 0 +6732 0 +6733 0 +6734 0 +6735 0 +6736 0 +6737 1 +6738 0 +6739 0 +6740 0 +6741 0 +6742 0 +6743 0 +6744 0 +6745 0 +6746 1 +6747 0 +6748 0 +6749 0 +6750 0 +6751 0 +6752 0 +6753 0 +6754 0 +6755 0 +6756 1 +6757 0 +6758 0 +6759 0 +6760 0 +6761 0 +6762 0 +6763 0 +6764 0 +6765 0 +6766 1 +6767 0 +6768 0 +6769 0 +6770 0 +6771 0 +6772 0 +6773 0 +6774 0 +6775 1 +6776 0 +6777 0 +6778 0 +6779 0 +6780 0 +6781 0 +6782 0 +6783 0 +6784 1 +6785 0 +6786 0 +6787 0 +6788 0 +6789 0 +6790 0 +6791 0 +6792 0 +6793 0 +6794 1 +6795 0 +6796 0 +6797 0 +6798 0 +6799 0 +6800 0 +6801 0 +6802 0 +6803 1 +6804 0 +6805 0 +6806 0 +6807 0 +6808 0 +6809 0 +6810 0 +6811 0 +6812 0 +6813 1 +6814 0 +6815 0 +6816 0 +6817 0 +6818 0 +6819 0 +6820 0 +6821 0 +6822 0 +6823 0 +6824 1 +6825 0 +6826 0 +6827 0 +6828 0 +6829 0 +6830 0 +6831 0 +6832 1 +6833 0 +6834 0 +6835 0 +6836 0 +6837 0 +6838 0 +6839 0 +6840 0 +6841 0 +6842 1 +6843 0 +6844 0 +6845 0 +6846 0 +6847 0 +6848 0 +6849 0 +6850 0 +6851 1 +6852 0 +6853 0 +6854 0 +6855 0 +6856 0 +6857 0 +6858 0 +6859 0 +6860 0 +6861 0 +6862 1 +6863 0 +6864 0 +6865 0 +6866 0 +6867 0 +6868 0 +6869 0 +6870 0 +6871 1 +6872 0 +6873 0 +6874 0 +6875 0 +6876 0 +6877 0 +6878 0 +6879 1 +6880 0 +6881 0 +6882 0 +6883 0 +6884 0 +6885 0 +6886 1 +6887 0 +6888 0 +6889 0 +6890 0 +6891 0 +6892 0 +6893 0 +6894 0 +6895 1 +6896 0 +6897 0 +6898 0 +6899 0 +6900 0 +6901 0 +6902 0 +6903 0 +6904 0 +6905 0 +6906 0 +6907 0 +6908 0 +6909 0 +6910 0 +6911 0 +6912 0 +6913 0 +6914 1 +6915 0 +6916 0 +6917 0 +6918 0 +6919 0 +6920 0 +6921 0 +6922 0 +6923 1 +6924 0 +6925 0 +6926 0 +6927 0 +6928 0 +6929 0 +6930 0 +6931 0 +6932 0 +6933 0 +6934 1 +6935 0 +6936 0 +6937 0 +6938 0 +6939 0 +6940 0 +6941 0 +6942 0 +6943 0 +6944 1 +6945 0 +6946 0 +6947 0 +6948 0 +6949 0 +6950 0 +6951 0 +6952 0 +6953 0 +6954 1 +6955 0 +6956 0 +6957 0 +6958 0 +6959 0 +6960 0 +6961 0 +6962 0 +6963 0 +6964 1 +6965 0 +6966 0 +6967 0 +6968 0 +6969 0 +6970 0 +6971 0 +6972 0 +6973 0 +6974 1 +6975 0 +6976 0 +6977 0 +6978 0 +6979 0 +6980 0 +6981 0 +6982 0 +6983 1 +6984 0 +6985 0 +6986 0 +6987 0 +6988 0 +6989 0 +6990 0 +6991 0 +6992 1 +6993 0 +6994 0 +6995 0 +6996 0 +6997 0 +6998 0 +6999 0 +7000 0 +7001 1 +7002 0 +7003 0 +7004 0 +7005 0 +7006 0 +7007 0 +7008 0 +7009 0 +7010 1 +7011 0 +7012 0 +7013 0 +7014 0 +7015 0 +7016 0 +7017 0 +7018 0 +7019 0 +7020 1 +7021 0 +7022 0 +7023 0 +7024 0 +7025 0 +7026 0 +7027 0 +7028 0 +7029 0 +7030 1 +7031 0 +7032 0 +7033 0 +7034 0 +7035 0 +7036 0 +7037 0 +7038 0 +7039 1 +7040 0 +7041 0 +7042 0 +7043 0 +7044 0 +7045 0 +7046 0 +7047 0 +7048 1 +7049 0 +7050 0 +7051 0 +7052 0 +7053 0 +7054 0 +7055 0 +7056 0 +7057 0 +7058 0 +7059 1 +7060 0 +7061 0 +7062 0 +7063 0 +7064 0 +7065 0 +7066 0 +7067 0 +7068 0 +7069 1 +7070 0 +7071 0 +7072 0 +7073 0 +7074 0 +7075 0 +7076 0 +7077 0 +7078 0 +7079 1 +7080 0 +7081 0 +7082 0 +7083 0 +7084 0 +7085 0 +7086 0 +7087 1 +7088 0 +7089 0 +7090 0 +7091 0 +7092 0 +7093 0 +7094 0 +7095 0 +7096 0 +7097 1 +7098 0 +7099 0 +7100 0 +7101 0 +7102 0 +7103 0 +7104 0 +7105 1 +7106 0 +7107 0 +7108 0 +7109 0 +7110 0 +7111 0 +7112 0 +7113 0 +7114 1 +7115 0 +7116 0 +7117 0 +7118 0 +7119 0 +7120 0 +7121 0 +7122 0 +7123 0 +7124 1 +7125 0 +7126 0 +7127 0 +7128 0 +7129 0 +7130 0 +7131 0 +7132 0 +7133 0 +7134 1 +7135 0 +7136 0 +7137 0 +7138 0 +7139 0 +7140 0 +7141 0 +7142 0 +7143 1 +7144 0 +7145 0 +7146 0 +7147 0 +7148 0 +7149 0 +7150 0 +7151 0 +7152 1 +7153 0 +7154 0 +7155 0 +7156 0 +7157 0 +7158 0 +7159 0 +7160 0 +7161 0 +7162 1 +7163 0 +7164 0 +7165 0 +7166 0 +7167 0 +7168 0 +7169 0 +7170 0 +7171 0 +7172 1 +7173 0 +7174 0 +7175 0 +7176 0 +7177 0 +7178 0 +7179 0 +7180 0 +7181 0 +7182 1 +7183 0 +7184 0 +7185 0 +7186 0 +7187 0 +7188 0 +7189 0 +7190 0 +7191 0 +7192 0 +7193 1 +7194 0 +7195 0 +7196 0 +7197 0 +7198 0 +7199 0 +7200 0 +7201 0 +7202 0 +7203 1 +7204 0 +7205 0 +7206 0 +7207 0 +7208 0 +7209 0 +7210 0 +7211 0 +7212 0 +7213 0 +7214 0 +7215 0 +7216 0 +7217 0 +7218 0 +7219 0 +7220 0 +7221 0 +7222 1 +7223 0 +7224 0 +7225 0 +7226 0 +7227 0 +7228 0 +7229 0 +7230 0 +7231 0 +7232 1 +7233 0 +7234 0 +7235 0 +7236 0 +7237 0 +7238 0 +7239 0 +7240 0 +7241 0 +7242 0 +7243 1 +7244 0 +7245 0 +7246 0 +7247 0 +7248 0 +7249 0 +7250 0 +7251 0 +7252 0 +7253 1 +7254 0 +7255 0 +7256 0 +7257 0 +7258 0 +7259 0 +7260 0 +7261 0 +7262 0 +7263 0 +7264 1 +7265 0 +7266 0 +7267 0 +7268 0 +7269 0 +7270 0 +7271 0 +7272 0 +7273 0 +7274 1 +7275 0 +7276 0 +7277 0 +7278 0 +7279 0 +7280 0 +7281 0 +7282 0 +7283 0 +7284 0 +7285 1 +7286 0 +7287 0 +7288 0 +7289 0 +7290 0 +7291 0 +7292 0 +7293 0 +7294 0 +7295 0 +7296 0 +7297 0 +7298 0 +7299 0 +7300 0 +7301 0 +7302 0 +7303 0 +7304 1 +7305 0 +7306 0 +7307 0 +7308 0 +7309 0 +7310 0 +7311 0 +7312 0 +7313 0 +7314 0 +7315 1 +7316 0 +7317 0 +7318 0 +7319 0 +7320 0 +7321 0 +7322 0 +7323 0 +7324 1 +7325 0 +7326 0 +7327 0 +7328 0 +7329 0 +7330 0 +7331 0 +7332 0 +7333 1 +7334 0 +7335 0 +7336 0 +7337 0 +7338 0 +7339 0 +7340 0 +7341 0 +7342 1 +7343 0 +7344 0 +7345 0 +7346 0 +7347 0 +7348 0 +7349 0 +7350 0 +7351 0 +7352 1 +7353 0 +7354 0 +7355 0 +7356 0 +7357 0 +7358 0 +7359 0 +7360 0 +7361 0 +7362 0 +7363 1 +7364 0 +7365 0 +7366 0 +7367 0 +7368 0 +7369 0 +7370 0 +7371 0 +7372 1 +7373 0 +7374 0 +7375 0 +7376 0 +7377 0 +7378 0 +7379 0 +7380 0 +7381 0 +7382 1 +7383 0 +7384 0 +7385 0 +7386 0 +7387 0 +7388 0 +7389 0 +7390 0 +7391 1 +7392 0 +7393 0 +7394 0 +7395 0 +7396 0 +7397 0 +7398 0 +7399 0 +7400 0 +7401 1 +7402 0 +7403 0 +7404 0 +7405 0 +7406 0 +7407 0 +7408 0 +7409 0 +7410 0 +7411 0 +7412 1 +7413 0 +7414 0 +7415 0 +7416 0 +7417 0 +7418 0 +7419 0 +7420 0 +7421 0 +7422 1 +7423 0 +7424 0 +7425 0 +7426 0 +7427 0 +7428 0 +7429 0 +7430 0 +7431 0 +7432 1 +7433 0 +7434 0 +7435 0 +7436 0 +7437 0 +7438 0 +7439 0 +7440 0 +7441 1 +7442 0 +7443 0 +7444 0 +7445 0 +7446 0 +7447 0 +7448 0 +7449 1 +7450 0 +7451 0 +7452 0 +7453 0 +7454 0 +7455 0 +7456 0 +7457 0 +7458 0 +7459 0 +7460 1 +7461 0 +7462 0 +7463 0 +7464 0 +7465 0 +7466 0 +7467 0 +7468 0 +7469 1 +7470 0 +7471 0 +7472 0 +7473 0 +7474 0 +7475 0 +7476 0 +7477 0 +7478 1 +7479 0 +7480 0 +7481 0 +7482 0 +7483 0 +7484 0 +7485 0 +7486 0 +7487 1 +7488 0 +7489 0 +7490 0 +7491 0 +7492 0 +7493 0 +7494 0 +7495 0 +7496 0 +7497 1 +7498 0 +7499 0 +7500 0 +7501 0 +7502 0 +7503 0 +7504 0 +7505 0 +7506 0 +7507 0 +7508 1 +7509 0 +7510 0 +7511 0 +7512 0 +7513 0 +7514 0 +7515 0 +7516 0 +7517 0 +7518 1 +7519 0 +7520 0 +7521 0 +7522 0 +7523 0 +7524 0 +7525 0 +7526 0 +7527 0 +7528 0 +7529 0 +7530 0 +7531 0 +7532 0 +7533 0 +7534 0 +7535 0 +7536 0 +7537 0 +7538 0 +7539 1 +7540 0 +7541 0 +7542 0 +7543 0 +7544 0 +7545 0 +7546 0 +7547 0 +7548 0 +7549 2 +7550 0 +7551 0 +7552 0 +7553 0 +7554 0 +7555 0 +7556 0 +7557 1 +7558 0 +7559 0 +7560 0 +7561 0 +7562 0 +7563 0 +7564 0 +7565 0 +7566 0 +7567 0 +7568 1 +7569 0 +7570 0 +7571 0 +7572 0 +7573 0 +7574 0 +7575 0 +7576 0 +7577 0 +7578 0 +7579 0 +7580 0 +7581 0 +7582 0 +7583 0 +7584 0 +7585 0 +7586 0 +7587 0 +7588 1 +7589 0 +7590 0 +7591 0 +7592 0 +7593 0 +7594 0 +7595 0 +7596 0 +7597 0 +7598 0 +7599 1 +7600 0 +7601 0 +7602 0 +7603 0 +7604 0 +7605 0 +7606 0 +7607 0 +7608 0 +7609 0 +7610 1 +7611 0 +7612 0 +7613 0 +7614 0 +7615 0 +7616 0 +7617 0 +7618 0 +7619 0 +7620 0 +7621 1 +7622 0 +7623 0 +7624 0 +7625 0 +7626 0 +7627 1 +7628 0 +7629 0 +7630 0 +7631 0 +7632 0 +7633 0 +7634 1 +7635 0 +7636 0 +7637 0 +7638 0 +7639 0 +7640 0 +7641 1 +7642 0 +7643 0 +7644 0 +7645 0 +7646 0 +7647 0 +7648 0 +7649 1 +7650 0 +7651 0 +7652 0 +7653 0 +7654 0 +7655 0 +7656 0 +7657 0 +7658 0 +7659 0 +7660 1 +7661 0 +7662 0 +7663 0 +7664 0 +7665 0 +7666 0 +7667 0 +7668 0 +7669 0 +7670 1 +7671 0 +7672 0 +7673 0 +7674 0 +7675 0 +7676 0 +7677 0 +7678 0 +7679 0 +7680 0 +7681 1 +7682 0 +7683 0 +7684 0 +7685 0 +7686 0 +7687 0 +7688 0 +7689 0 +7690 0 +7691 1 +7692 0 +7693 0 +7694 0 +7695 0 +7696 0 +7697 0 +7698 0 +7699 0 +7700 0 +7701 0 +7702 1 +7703 0 +7704 0 +7705 0 +7706 0 +7707 0 +7708 0 +7709 0 +7710 0 +7711 0 +7712 1 +7713 0 +7714 0 +7715 0 +7716 0 +7717 0 +7718 0 +7719 0 +7720 0 +7721 0 +7722 1 +7723 0 +7724 0 +7725 0 +7726 0 +7727 0 +7728 0 +7729 0 +7730 0 +7731 0 +7732 1 +7733 0 +7734 0 +7735 0 +7736 0 +7737 0 +7738 0 +7739 0 +7740 0 +7741 0 +7742 1 +7743 0 +7744 0 +7745 0 +7746 0 +7747 0 +7748 0 +7749 0 +7750 0 +7751 0 +7752 1 +7753 0 +7754 0 +7755 0 +7756 0 +7757 0 +7758 0 +7759 0 +7760 0 +7761 1 +7762 0 +7763 0 +7764 0 +7765 0 +7766 0 +7767 0 +7768 0 +7769 0 +7770 1 +7771 0 +7772 0 +7773 0 +7774 0 +7775 0 +7776 0 +7777 0 +7778 0 +7779 1 +7780 0 +7781 0 +7782 0 +7783 0 +7784 0 +7785 0 +7786 0 +7787 0 +7788 0 +7789 1 +7790 0 +7791 0 +7792 0 +7793 0 +7794 0 +7795 0 +7796 0 +7797 0 +7798 0 +7799 1 +7800 0 +7801 0 +7802 0 +7803 0 +7804 0 +7805 0 +7806 0 +7807 0 +7808 0 +7809 0 +7810 1 +7811 0 +7812 0 +7813 0 +7814 0 +7815 0 +7816 0 +7817 0 +7818 0 +7819 1 +7820 0 +7821 0 +7822 0 +7823 0 +7824 0 +7825 0 +7826 0 +7827 0 +7828 1 +7829 0 +7830 0 +7831 0 +7832 0 +7833 0 +7834 0 +7835 0 +7836 0 +7837 0 +7838 0 +7839 1 +7840 0 +7841 0 +7842 0 +7843 0 +7844 0 +7845 0 +7846 0 +7847 0 +7848 0 +7849 1 +7850 0 +7851 0 +7852 0 +7853 0 +7854 0 +7855 0 +7856 0 +7857 0 +7858 1 +7859 0 +7860 0 +7861 0 +7862 0 +7863 0 +7864 0 +7865 0 +7866 0 +7867 0 +7868 1 +7869 0 +7870 0 +7871 0 +7872 0 +7873 0 +7874 0 +7875 0 +7876 0 +7877 0 +7878 0 +7879 0 +7880 0 +7881 0 +7882 0 +7883 0 +7884 0 +7885 0 +7886 0 +7887 1 +7888 0 +7889 0 +7890 0 +7891 0 +7892 0 +7893 0 +7894 0 +7895 0 +7896 0 +7897 0 +7898 1 +7899 0 +7900 0 +7901 0 +7902 0 +7903 0 +7904 0 +7905 0 +7906 0 +7907 0 +7908 1 +7909 0 +7910 0 +7911 0 +7912 0 +7913 0 +7914 0 +7915 0 +7916 0 +7917 0 +7918 1 +7919 0 +7920 0 +7921 0 +7922 0 +7923 0 +7924 0 +7925 0 +7926 0 +7927 0 +7928 1 +7929 0 +7930 0 +7931 0 +7932 0 +7933 0 +7934 0 +7935 0 +7936 0 +7937 0 +7938 1 +7939 0 +7940 0 +7941 0 +7942 0 +7943 0 +7944 0 +7945 0 +7946 0 +7947 0 +7948 1 +7949 0 +7950 0 +7951 0 +7952 0 +7953 0 +7954 0 +7955 0 +7956 0 +7957 0 +7958 1 +7959 0 +7960 0 +7961 0 +7962 0 +7963 0 +7964 0 +7965 0 +7966 0 +7967 0 +7968 1 +7969 0 +7970 0 +7971 0 +7972 0 +7973 0 +7974 0 +7975 0 +7976 0 +7977 0 +7978 1 +7979 0 +7980 0 +7981 0 +7982 0 +7983 0 +7984 0 +7985 1 +7986 0 +7987 0 +7988 0 +7989 0 +7990 0 +7991 0 +7992 0 +7993 0 +7994 0 +7995 1 +7996 0 +7997 0 +7998 0 +7999 0 +8000 0 +8001 0 +8002 0 +8003 0 +8004 0 +8005 0 +8006 1 +8007 0 +8008 0 +8009 0 +8010 0 +8011 0 +8012 0 +8013 0 +8014 0 +8015 1 +8016 0 +8017 0 +8018 0 +8019 0 +8020 0 +8021 0 +8022 0 +8023 0 +8024 0 +8025 1 +8026 0 +8027 0 +8028 0 +8029 0 +8030 0 +8031 0 +8032 0 +8033 0 +8034 0 +8035 0 +8036 1 +8037 0 +8038 0 +8039 0 +8040 0 +8041 0 +8042 0 +8043 0 +8044 0 +8045 0 +8046 1 +8047 0 +8048 0 +8049 0 +8050 0 +8051 0 +8052 0 +8053 0 +8054 0 +8055 0 +8056 0 +8057 1 +8058 0 +8059 0 +8060 0 +8061 0 +8062 0 +8063 0 +8064 0 +8065 0 +8066 0 +8067 1 +8068 0 +8069 0 +8070 0 +8071 0 +8072 0 +8073 0 +8074 0 +8075 0 +8076 0 +8077 0 +8078 1 +8079 0 +8080 0 +8081 0 +8082 0 +8083 0 +8084 0 +8085 0 +8086 0 +8087 0 +8088 1 +8089 0 +8090 0 +8091 0 +8092 0 +8093 0 +8094 0 +8095 0 +8096 0 +8097 0 +8098 1 +8099 0 +8100 0 +8101 0 +8102 0 +8103 0 +8104 0 +8105 1 +8106 0 +8107 0 +8108 0 +8109 0 +8110 0 +8111 0 +8112 0 +8113 0 +8114 0 +8115 1 +8116 0 +8117 0 +8118 0 +8119 0 +8120 0 +8121 0 +8122 0 +8123 0 +8124 0 +8125 1 +8126 0 +8127 0 +8128 0 +8129 0 +8130 0 +8131 0 +8132 0 +8133 0 +8134 1 +8135 0 +8136 0 +8137 0 +8138 0 +8139 0 +8140 0 +8141 0 +8142 0 +8143 0 +8144 0 +8145 1 +8146 0 +8147 0 +8148 0 +8149 0 +8150 0 +8151 0 +8152 0 +8153 0 +8154 0 +8155 0 +8156 1 +8157 0 +8158 0 +8159 0 +8160 0 +8161 0 +8162 0 +8163 0 +8164 0 +8165 0 +8166 1 +8167 0 +8168 0 +8169 0 +8170 0 +8171 0 +8172 0 +8173 0 +8174 0 +8175 0 +8176 1 +8177 0 +8178 0 +8179 0 +8180 0 +8181 0 +8182 0 +8183 0 +8184 0 +8185 0 +8186 1 +8187 0 +8188 0 +8189 0 +8190 0 +8191 0 +8192 0 +8193 0 +8194 0 +8195 0 +8196 0 +8197 1 +8198 0 +8199 0 +8200 0 +8201 0 +8202 0 +8203 0 +8204 0 +8205 0 +8206 0 +8207 1 +8208 0 +8209 0 +8210 0 +8211 0 +8212 0 +8213 0 +8214 0 +8215 0 +8216 1 +8217 0 +8218 0 +8219 0 +8220 0 +8221 0 +8222 0 +8223 0 +8224 0 +8225 1 +8226 0 +8227 0 +8228 0 +8229 0 +8230 0 +8231 0 +8232 0 +8233 0 +8234 0 +8235 1 +8236 0 +8237 0 +8238 0 +8239 0 +8240 0 +8241 0 +8242 0 +8243 0 +8244 1 +8245 0 +8246 0 +8247 0 +8248 0 +8249 0 +8250 0 +8251 0 +8252 0 +8253 0 +8254 1 +8255 0 +8256 0 +8257 0 +8258 0 +8259 0 +8260 0 +8261 0 +8262 0 +8263 0 +8264 0 +8265 1 +8266 0 +8267 0 +8268 0 +8269 0 +8270 0 +8271 0 +8272 0 +8273 0 +8274 0 +8275 1 +8276 0 +8277 0 +8278 0 +8279 0 +8280 0 +8281 0 +8282 0 +8283 0 +8284 0 +8285 0 +8286 1 +8287 0 +8288 0 +8289 0 +8290 0 +8291 0 +8292 0 +8293 0 +8294 0 +8295 0 +8296 1 +8297 0 +8298 0 +8299 0 +8300 0 +8301 0 +8302 0 +8303 0 +8304 1 +8305 0 +8306 0 +8307 0 +8308 0 +8309 0 +8310 0 +8311 0 +8312 0 +8313 0 +8314 1 +8315 0 +8316 0 +8317 0 +8318 0 +8319 0 +8320 0 +8321 0 +8322 0 +8323 0 +8324 1 +8325 0 +8326 0 +8327 0 +8328 0 +8329 0 +8330 0 +8331 0 +8332 0 +8333 0 +8334 0 +8335 0 +8336 0 +8337 0 +8338 0 +8339 0 +8340 0 +8341 0 +8342 1 +8343 0 +8344 0 +8345 0 +8346 0 +8347 0 +8348 0 +8349 0 +8350 0 +8351 1 +8352 0 +8353 0 +8354 0 +8355 0 +8356 0 +8357 0 +8358 0 +8359 0 +8360 0 +8361 1 +8362 0 +8363 0 +8364 0 +8365 0 +8366 0 +8367 0 +8368 0 +8369 0 +8370 0 +8371 1 +8372 0 +8373 0 +8374 0 +8375 0 +8376 0 +8377 0 +8378 0 +8379 0 +8380 1 +8381 0 +8382 0 +8383 0 +8384 0 +8385 0 +8386 0 +8387 0 +8388 0 +8389 1 +8390 0 +8391 0 +8392 0 +8393 0 +8394 0 +8395 0 +8396 0 +8397 0 +8398 0 +8399 1 +8400 0 +8401 0 +8402 0 +8403 0 +8404 0 +8405 0 +8406 0 +8407 0 +8408 0 +8409 1 +8410 0 +8411 0 +8412 0 +8413 0 +8414 0 +8415 0 +8416 0 +8417 0 +8418 0 +8419 1 +8420 0 +8421 0 +8422 0 +8423 0 +8424 0 +8425 0 +8426 0 +8427 0 +8428 0 +8429 0 +8430 1 +8431 0 +8432 0 +8433 0 +8434 0 +8435 0 +8436 0 +8437 0 +8438 1 +8439 0 +8440 0 +8441 0 +8442 0 +8443 0 +8444 0 +8445 0 +8446 0 +8447 1 +8448 0 +8449 0 +8450 0 +8451 0 +8452 0 +8453 0 +8454 0 +8455 0 +8456 0 +8457 1 +8458 0 +8459 0 +8460 0 +8461 0 +8462 0 +8463 0 +8464 0 +8465 0 +8466 0 +8467 1 +8468 0 +8469 0 +8470 0 +8471 0 +8472 0 +8473 0 +8474 0 +8475 0 +8476 0 +8477 1 +8478 0 +8479 0 +8480 0 +8481 0 +8482 0 +8483 0 +8484 0 +8485 0 +8486 1 +8487 0 +8488 0 +8489 0 +8490 0 +8491 0 +8492 0 +8493 0 +8494 0 +8495 0 +8496 0 +8497 0 +8498 0 +8499 0 +8500 0 +8501 0 +8502 0 +8503 0 +8504 0 +8505 0 +8506 1 +8507 0 +8508 0 +8509 0 +8510 0 +8511 0 +8512 0 +8513 0 +8514 0 +8515 0 +8516 0 +8517 0 +8518 0 +8519 0 +8520 0 +8521 0 +8522 0 +8523 1 +8524 0 +8525 0 +8526 0 +8527 0 +8528 0 +8529 0 +8530 0 +8531 0 +8532 1 +8533 0 +8534 0 +8535 0 +8536 0 +8537 0 +8538 0 +8539 0 +8540 0 +8541 1 +8542 0 +8543 0 +8544 0 +8545 0 +8546 0 +8547 0 +8548 0 +8549 1 +8550 0 +8551 0 +8552 0 +8553 0 +8554 0 +8555 0 +8556 0 +8557 0 +8558 0 +8559 1 +8560 0 +8561 0 +8562 0 +8563 0 +8564 0 +8565 0 +8566 0 +8567 0 +8568 1 +8569 0 +8570 0 +8571 0 +8572 0 +8573 0 +8574 0 +8575 0 +8576 0 +8577 1 +8578 0 +8579 0 +8580 0 +8581 0 +8582 0 +8583 0 +8584 0 +8585 0 +8586 1 +8587 0 +8588 0 +8589 0 +8590 0 +8591 0 +8592 0 +8593 0 +8594 0 +8595 0 +8596 1 +8597 0 +8598 0 +8599 0 +8600 0 +8601 0 +8602 0 +8603 0 +8604 0 +8605 0 +8606 1 +8607 0 +8608 0 +8609 0 +8610 0 +8611 0 +8612 0 +8613 0 +8614 0 +8615 0 +8616 1 +8617 0 +8618 0 +8619 0 +8620 0 +8621 0 +8622 0 +8623 0 +8624 0 +8625 1 +8626 0 +8627 0 +8628 0 +8629 0 +8630 0 +8631 0 +8632 0 +8633 1 +8634 0 +8635 0 +8636 0 +8637 0 +8638 0 +8639 0 +8640 0 +8641 0 +8642 0 +8643 1 +8644 0 +8645 0 +8646 0 +8647 0 +8648 0 +8649 0 +8650 0 +8651 1 +8652 0 +8653 0 +8654 0 +8655 0 +8656 0 +8657 0 +8658 0 +8659 0 +8660 1 +8661 0 +8662 0 +8663 0 +8664 0 +8665 0 +8666 0 +8667 0 +8668 0 +8669 1 +8670 0 +8671 0 +8672 0 +8673 0 +8674 0 +8675 0 +8676 0 +8677 1 +8678 0 +8679 0 +8680 0 +8681 0 +8682 0 +8683 0 +8684 0 +8685 0 +8686 1 +8687 0 +8688 0 +8689 0 +8690 0 +8691 0 +8692 0 +8693 0 +8694 0 +8695 0 +8696 1 +8697 0 +8698 0 +8699 0 +8700 0 +8701 0 +8702 0 +8703 0 +8704 0 +8705 1 +8706 0 +8707 0 +8708 0 +8709 0 +8710 0 +8711 0 +8712 0 +8713 0 +8714 0 +8715 1 +8716 0 +8717 0 +8718 0 +8719 0 +8720 0 +8721 0 +8722 0 +8723 0 +8724 0 +8725 1 +8726 0 +8727 0 +8728 0 +8729 0 +8730 0 +8731 0 +8732 0 +8733 0 +8734 0 +8735 1 +8736 0 +8737 0 +8738 0 +8739 0 +8740 0 +8741 0 +8742 0 +8743 0 +8744 0 +8745 1 +8746 0 +8747 0 +8748 0 +8749 0 +8750 0 +8751 0 +8752 0 +8753 0 +8754 0 +8755 1 +8756 0 +8757 0 +8758 0 +8759 0 +8760 0 +8761 0 +8762 0 +8763 1 +8764 0 +8765 0 +8766 0 +8767 0 +8768 0 +8769 0 +8770 1 +8771 0 +8772 0 +8773 0 +8774 0 +8775 0 +8776 0 +8777 0 +8778 0 +8779 0 +8780 1 +8781 0 +8782 0 +8783 0 +8784 0 +8785 0 +8786 0 +8787 0 +8788 0 +8789 1 +8790 0 +8791 0 +8792 0 +8793 0 +8794 0 +8795 0 +8796 0 +8797 0 +8798 1 +8799 0 +8800 0 +8801 0 +8802 0 +8803 0 +8804 0 +8805 0 +8806 0 +8807 3 +8808 0 +8809 0 +8810 1 +8811 0 +8812 0 +8813 0 +8814 0 +8815 1 +8816 0 +8817 0 +8818 0 +8819 0 +8820 1 +8821 0 +8822 0 +8823 0 +8824 1 +8825 0 +8826 0 +8827 0 +8828 0 +8829 0 +8830 1 +8831 0 +8832 0 +8833 0 +8834 0 +8835 0 +8836 0 +8837 1 +8838 0 +8839 0 +8840 0 +8841 0 +8842 0 +8843 0 +8844 0 +8845 1 +8846 0 +8847 0 +8848 0 +8849 0 +8850 0 +8851 0 +8852 0 +8853 0 +8854 0 +8855 1 +8856 0 +8857 0 +8858 0 +8859 0 +8860 0 +8861 0 +8862 0 +8863 0 +8864 0 +8865 1 +8866 0 +8867 0 +8868 0 +8869 0 +8870 0 +8871 0 +8872 1 +8873 0 +8874 0 +8875 0 +8876 0 +8877 0 +8878 0 +8879 0 +8880 1 +8881 0 +8882 0 +8883 0 +8884 0 +8885 0 +8886 0 +8887 0 +8888 1 +8889 0 +8890 0 +8891 0 +8892 0 +8893 0 +8894 0 +8895 0 +8896 0 +8897 0 +8898 0 +8899 0 +8900 0 +8901 0 +8902 0 +8903 0 +8904 0 +8905 1 +8906 0 +8907 0 +8908 0 +8909 0 +8910 0 +8911 0 +8912 1 +8913 0 +8914 0 +8915 0 +8916 0 +8917 0 +8918 0 +8919 0 +8920 1 +8921 0 +8922 0 +8923 0 +8924 0 +8925 0 +8926 0 +8927 0 +8928 0 +8929 1 +8930 0 +8931 0 +8932 0 +8933 0 +8934 0 +8935 0 +8936 0 +8937 0 +8938 0 +8939 1 +8940 0 +8941 0 +8942 0 +8943 0 +8944 0 +8945 0 +8946 0 +8947 0 +8948 0 +8949 1 +8950 0 +8951 0 +8952 0 +8953 0 +8954 0 +8955 0 +8956 0 +8957 0 +8958 0 +8959 1 +8960 0 +8961 0 +8962 0 +8963 0 +8964 0 +8965 0 +8966 0 +8967 0 +8968 0 +8969 1 +8970 0 +8971 0 +8972 0 +8973 0 +8974 0 +8975 0 +8976 0 +8977 0 +8978 1 +8979 0 +8980 0 +8981 0 +8982 0 +8983 0 +8984 0 +8985 0 +8986 0 +8987 1 +8988 0 +8989 0 +8990 0 +8991 0 +8992 0 +8993 0 +8994 0 +8995 0 +8996 0 +8997 1 +8998 0 +8999 0 +9000 0 +9001 0 +9002 0 +9003 0 +9004 0 +9005 0 +9006 1 +9007 0 +9008 0 +9009 0 +9010 0 +9011 0 +9012 0 +9013 0 +9014 1 +9015 0 +9016 0 +9017 0 +9018 0 +9019 0 +9020 0 +9021 0 +9022 1 +9023 0 +9024 0 +9025 0 +9026 0 +9027 0 +9028 0 +9029 0 +9030 1 +9031 0 +9032 0 +9033 0 +9034 0 +9035 0 +9036 0 +9037 0 +9038 1 +9039 0 +9040 0 +9041 0 +9042 0 +9043 0 +9044 0 +9045 0 +9046 0 +9047 1 +9048 0 +9049 0 +9050 0 +9051 0 +9052 0 +9053 0 +9054 0 +9055 1 +9056 0 +9057 0 +9058 0 +9059 0 +9060 0 +9061 0 +9062 0 +9063 1 +9064 0 +9065 0 +9066 0 +9067 0 +9068 0 +9069 0 +9070 0 +9071 0 +9072 0 +9073 1 +9074 0 +9075 0 +9076 0 +9077 0 +9078 0 +9079 0 +9080 0 +9081 0 +9082 0 +9083 0 +9084 0 +9085 0 +9086 0 +9087 0 +9088 0 +9089 0 +9090 0 +9091 0 +9092 1 +9093 0 +9094 0 +9095 0 +9096 0 +9097 0 +9098 0 +9099 0 +9100 1 +9101 0 +9102 0 +9103 0 +9104 0 +9105 0 +9106 0 +9107 0 +9108 1 +9109 0 +9110 0 +9111 0 +9112 0 +9113 0 +9114 0 +9115 0 +9116 0 +9117 1 +9118 0 +9119 0 +9120 0 +9121 0 +9122 0 +9123 0 +9124 0 +9125 0 +9126 1 +9127 0 +9128 0 +9129 0 +9130 0 +9131 0 +9132 0 +9133 0 +9134 0 +9135 1 +9136 0 +9137 0 +9138 0 +9139 0 +9140 0 +9141 0 +9142 0 +9143 1 +9144 0 +9145 0 +9146 0 +9147 0 +9148 0 +9149 0 +9150 0 +9151 0 +9152 1 +9153 0 +9154 0 +9155 0 +9156 0 +9157 0 +9158 0 +9159 0 +9160 0 +9161 1 +9162 0 +9163 0 +9164 0 +9165 0 +9166 0 +9167 0 +9168 0 +9169 1 +9170 0 +9171 0 +9172 0 +9173 0 +9174 0 +9175 0 +9176 0 +9177 0 +9178 1 +9179 0 +9180 0 +9181 0 +9182 0 +9183 0 +9184 0 +9185 0 +9186 0 +9187 0 +9188 1 +9189 0 +9190 0 +9191 0 +9192 0 +9193 0 +9194 0 +9195 0 +9196 0 +9197 1 +9198 0 +9199 0 +9200 0 +9201 0 +9202 0 +9203 0 +9204 0 +9205 0 +9206 0 +9207 0 +9208 0 +9209 0 +9210 0 +9211 0 +9212 0 +9213 0 +9214 0 +9215 0 +9216 0 +9217 0 +9218 0 +9219 0 +9220 0 +9221 1 +9222 0 +9223 0 +9224 0 +9225 0 +9226 0 +9227 0 +9228 1 +9229 0 +9230 0 +9231 0 +9232 0 +9233 0 +9234 0 +9235 0 +9236 0 +9237 1 +9238 0 +9239 0 +9240 0 +9241 0 +9242 0 +9243 0 +9244 0 +9245 0 +9246 1 +9247 0 +9248 0 +9249 0 +9250 0 +9251 0 +9252 0 +9253 0 +9254 0 +9255 1 +9256 0 +9257 0 +9258 0 +9259 0 +9260 0 +9261 1 +9262 0 +9263 0 +9264 0 +9265 0 +9266 0 +9267 0 +9268 0 +9269 0 +9270 0 +9271 0 +9272 0 +9273 0 +9274 0 +9275 0 +9276 1 +9277 0 +9278 0 +9279 0 +9280 0 +9281 0 +9282 0 +9283 0 +9284 0 +9285 0 +9286 0 +9287 0 +9288 0 +9289 0 +9290 1 +9291 0 +9292 0 +9293 0 +9294 0 +9295 0 +9296 0 +9297 0 +9298 0 +9299 0 +9300 1 +9301 0 +9302 0 +9303 0 +9304 0 +9305 0 +9306 0 +9307 0 +9308 1 +9309 0 +9310 0 +9311 0 +9312 0 +9313 0 +9314 0 +9315 0 +9316 1 +9317 0 +9318 0 +9319 0 +9320 0 +9321 0 +9322 0 +9323 1 +9324 0 +9325 0 +9326 0 +9327 0 +9328 0 +9329 0 +9330 0 +9331 1 +9332 0 +9333 0 +9334 0 +9335 0 +9336 0 +9337 0 +9338 1 +9339 0 +9340 0 +9341 0 +9342 0 +9343 0 +9344 0 +9345 1 +9346 0 +9347 0 +9348 0 +9349 0 +9350 0 +9351 0 +9352 0 +9353 0 +9354 0 +9355 1 +9356 0 +9357 0 +9358 0 +9359 0 +9360 0 +9361 0 +9362 0 +9363 1 +9364 0 +9365 0 +9366 0 +9367 0 +9368 0 +9369 0 +9370 1 +9371 0 +9372 0 +9373 0 +9374 0 +9375 0 +9376 0 +9377 0 +9378 1 +9379 0 +9380 0 +9381 0 +9382 0 +9383 0 +9384 0 +9385 0 +9386 0 +9387 0 +9388 0 +9389 0 +9390 0 +9391 0 +9392 0 +9393 0 +9394 0 +9395 1 +9396 0 +9397 0 +9398 0 +9399 0 +9400 0 +9401 0 +9402 0 +9403 1 +9404 0 +9405 0 +9406 0 +9407 0 +9408 0 +9409 0 +9410 0 +9411 0 +9412 1 +9413 0 +9414 0 +9415 0 +9416 0 +9417 0 +9418 0 +9419 0 +9420 1 +9421 0 +9422 0 +9423 0 +9424 0 +9425 0 +9426 0 +9427 0 +9428 0 +9429 1 +9430 0 +9431 0 +9432 0 +9433 0 +9434 0 +9435 0 +9436 0 +9437 0 +9438 0 +9439 1 +9440 0 +9441 0 +9442 0 +9443 0 +9444 0 +9445 0 +9446 0 +9447 0 +9448 0 +9449 1 +9450 0 +9451 0 +9452 0 +9453 0 +9454 0 +9455 0 +9456 0 +9457 1 +9458 0 +9459 0 +9460 0 +9461 0 +9462 0 +9463 0 +9464 1 +9465 0 +9466 0 +9467 0 +9468 0 +9469 0 +9470 0 +9471 0 +9472 0 +9473 1 +9474 0 +9475 0 +9476 0 +9477 0 +9478 0 +9479 0 +9480 0 +9481 1 +9482 0 +9483 0 +9484 0 +9485 0 +9486 0 +9487 0 +9488 1 +9489 0 +9490 0 +9491 0 +9492 0 +9493 0 +9494 0 +9495 0 +9496 0 +9497 1 +9498 0 +9499 0 +9500 0 +9501 0 +9502 0 +9503 0 +9504 0 +9505 0 +9506 0 +9507 0 +9508 0 +9509 0 +9510 0 +9511 0 +9512 0 +9513 0 +9514 1 +9515 0 +9516 0 +9517 0 +9518 0 +9519 0 +9520 0 +9521 0 +9522 1 +9523 0 +9524 0 +9525 0 +9526 0 +9527 0 +9528 0 +9529 0 +9530 1 +9531 0 +9532 0 +9533 0 +9534 0 +9535 0 +9536 0 +9537 0 +9538 1 +9539 0 +9540 0 +9541 0 +9542 0 +9543 0 +9544 0 +9545 0 +9546 0 +9547 1 +9548 0 +9549 0 +9550 0 +9551 0 +9552 0 +9553 0 +9554 0 +9555 1 +9556 0 +9557 0 +9558 0 +9559 0 +9560 0 +9561 0 +9562 0 +9563 1 +9564 0 +9565 0 +9566 0 +9567 0 +9568 0 +9569 0 +9570 0 +9571 0 +9572 1 +9573 0 +9574 0 +9575 0 +9576 0 +9577 0 +9578 0 +9579 0 +9580 1 +9581 0 +9582 0 +9583 0 +9584 0 +9585 0 +9586 0 +9587 0 +9588 0 +9589 1 +9590 0 +9591 0 +9592 0 +9593 0 +9594 0 +9595 0 +9596 0 +9597 0 +9598 0 +9599 0 +9600 0 +9601 0 +9602 0 +9603 0 +9604 0 +9605 0 +9606 0 +9607 0 +9608 1 +9609 0 +9610 0 +9611 0 +9612 0 +9613 0 +9614 0 +9615 1 +9616 0 +9617 0 +9618 0 +9619 0 +9620 0 +9621 0 +9622 1 +9623 0 +9624 0 +9625 0 +9626 0 +9627 0 +9628 0 +9629 0 +9630 1 +9631 0 +9632 0 +9633 0 +9634 0 +9635 0 +9636 0 +9637 0 +9638 0 +9639 1 +9640 0 +9641 0 +9642 0 +9643 0 +9644 0 +9645 0 +9646 0 +9647 0 +9648 1 +9649 0 +9650 0 +9651 0 +9652 0 +9653 0 +9654 0 +9655 0 +9656 1 +9657 0 +9658 0 +9659 0 +9660 0 +9661 0 +9662 0 +9663 1 +9664 0 +9665 0 +9666 0 +9667 0 +9668 0 +9669 0 +9670 0 +9671 0 +9672 0 +9673 1 +9674 0 +9675 0 +9676 0 +9677 0 +9678 0 +9679 0 +9680 0 +9681 1 +9682 0 +9683 0 +9684 0 +9685 0 +9686 0 +9687 0 +9688 0 +9689 1 +9690 0 +9691 0 +9692 0 +9693 0 +9694 0 +9695 0 +9696 1 +9697 0 +9698 0 +9699 0 +9700 0 +9701 0 +9702 0 +9703 0 +9704 1 +9705 0 +9706 0 +9707 0 +9708 0 +9709 0 +9710 0 +9711 0 +9712 1 +9713 0 +9714 0 +9715 0 +9716 0 +9717 0 +9718 0 +9719 0 +9720 0 +9721 0 +9722 1 +9723 0 +9724 0 +9725 0 +9726 0 +9727 0 +9728 0 +9729 0 +9730 0 +9731 1 +9732 0 +9733 0 +9734 0 +9735 0 +9736 0 +9737 0 +9738 0 +9739 0 +9740 1 +9741 0 +9742 0 +9743 0 +9744 0 +9745 0 +9746 0 +9747 0 +9748 0 +9749 1 +9750 0 +9751 0 +9752 0 +9753 0 +9754 0 +9755 0 +9756 1 +9757 0 +9758 0 +9759 0 +9760 0 +9761 0 +9762 0 +9763 0 +9764 0 +9765 0 +9766 0 +9767 0 +9768 0 +9769 0 +9770 0 +9771 0 +9772 0 +9773 1 +9774 0 +9775 0 +9776 0 +9777 0 +9778 0 +9779 0 +9780 1 +9781 0 +9782 0 +9783 0 +9784 0 +9785 0 +9786 0 +9787 0 +9788 1 +9789 0 +9790 0 +9791 0 +9792 0 +9793 0 +9794 0 +9795 0 +9796 0 +9797 0 +9798 0 +9799 0 +9800 0 +9801 0 +9802 0 +9803 1 +9804 0 +9805 0 +9806 0 +9807 0 +9808 0 +9809 0 +9810 0 +9811 0 +9812 1 +9813 0 +9814 0 +9815 0 +9816 0 +9817 0 +9818 0 +9819 0 +9820 1 +9821 0 +9822 0 +9823 0 +9824 0 +9825 0 +9826 0 +9827 0 +9828 0 +9829 1 +9830 0 +9831 0 +9832 0 +9833 0 +9834 0 +9835 0 +9836 0 +9837 0 +9838 1 +9839 0 +9840 0 +9841 0 +9842 0 +9843 0 +9844 0 +9845 0 +9846 0 +9847 0 +9848 1 +9849 0 +9850 0 +9851 0 +9852 0 +9853 0 +9854 4 +9855 0 +9856 0 +9857 1 +9858 0 +9859 0 +9860 0 +9861 0 +9862 1 +9863 0 +9864 0 +9865 0 +9866 0 +9867 0 +9868 1 +9869 0 +9870 0 +9871 0 +9872 0 +9873 1 +9874 0 +9875 0 +9876 0 +9877 0 +9878 1 +9879 0 +9880 0 +9881 0 +9882 0 +9883 0 +9884 0 +9885 0 +9886 1 +9887 0 +9888 0 +9889 0 +9890 0 +9891 0 +9892 0 +9893 0 +9894 0 +9895 1 +9896 0 +9897 0 +9898 0 +9899 0 +9900 0 +9901 0 +9902 0 +9903 0 +9904 1 +9905 0 +9906 0 +9907 0 +9908 0 +9909 0 +9910 0 +9911 0 +9912 0 +9913 0 +9914 0 +9915 0 +9916 0 +9917 0 +9918 0 +9919 0 +9920 0 +9921 0 +9922 0 +9923 0 +9924 1 +9925 0 +9926 0 +9927 0 +9928 0 +9929 0 +9930 0 +9931 0 +9932 0 +9933 0 +9934 1 +9935 0 +9936 0 +9937 0 +9938 0 +9939 0 +9940 0 +9941 0 +9942 0 +9943 0 +9944 1 +9945 0 +9946 0 +9947 0 +9948 0 +9949 0 +9950 0 +9951 0 +9952 0 +9953 0 +9954 1 +9955 0 +9956 0 +9957 0 +9958 0 +9959 0 +9960 0 +9961 0 +9962 0 +9963 1 +9964 0 +9965 0 +9966 0 +9967 0 +9968 0 +9969 0 +9970 0 +9971 0 +9972 1 +9973 0 +9974 0 +9975 0 +9976 0 +9977 0 +9978 0 +9979 0 +9980 0 +9981 0 +9982 0 +9983 1 +9984 0 +9985 0 +9986 0 +9987 0 +9988 0 +9989 0 +9990 0 +9991 0 +9992 0 +9993 1 +9994 0 +9995 0 +9996 0 +9997 0 +9998 0 +9999 0 +10000 0 +10001 0 +10002 0 +10003 0 +10004 1 +10005 0 +10006 0 +10007 0 +10008 0 +10009 0 +10010 0 +10011 0 +10012 0 +10013 1 +10014 0 +10015 0 +10016 0 +10017 0 +10018 0 +10019 0 +10020 0 +10021 0 +10022 0 +10023 1 +10024 0 +10025 0 +10026 0 +10027 0 +10028 0 +10029 0 +10030 0 +10031 1 +10032 0 +10033 0 +10034 0 +10035 0 +10036 0 +10037 0 +10038 0 +10039 0 +10040 0 +10041 1 +10042 0 +10043 0 +10044 0 +10045 0 +10046 0 +10047 0 +10048 0 +10049 0 +10050 0 +10051 1 +10052 0 +10053 0 +10054 0 +10055 0 +10056 0 +10057 0 +10058 0 +10059 0 +10060 1 +10061 0 +10062 0 +10063 0 +10064 0 +10065 0 +10066 0 +10067 0 +10068 0 +10069 1 +10070 0 +10071 0 +10072 0 +10073 0 +10074 0 +10075 0 +10076 0 +10077 0 +10078 1 +10079 0 +10080 0 +10081 0 +10082 0 +10083 0 +10084 0 +10085 0 +10086 0 +10087 1 +10088 0 +10089 0 +10090 0 +10091 0 +10092 0 +10093 0 +10094 0 +10095 0 +10096 0 +10097 1 +10098 0 +10099 0 +10100 0 +10101 0 +10102 0 +10103 0 +10104 0 +10105 0 +10106 0 +10107 0 +10108 1 +10109 0 +10110 0 +10111 0 +10112 0 +10113 0 +10114 0 +10115 0 +10116 0 +10117 0 +10118 1 +10119 0 +10120 0 +10121 0 +10122 0 +10123 0 +10124 0 +10125 0 +10126 0 +10127 1 +10128 0 +10129 0 +10130 0 +10131 0 +10132 0 +10133 0 +10134 0 +10135 0 +10136 0 +10137 1 +10138 0 +10139 0 +10140 0 +10141 0 +10142 0 +10143 0 +10144 0 +10145 0 +10146 0 +10147 1 +10148 0 +10149 0 +10150 0 +10151 0 +10152 0 +10153 0 +10154 0 +10155 0 +10156 0 +10157 1 +10158 0 +10159 0 +10160 0 +10161 0 +10162 0 +10163 0 +10164 0 +10165 0 +10166 0 +10167 1 +10168 0 +10169 0 +10170 0 +10171 0 +10172 0 +10173 0 +10174 0 +10175 0 +10176 1 +10177 0 +10178 0 +10179 0 +10180 0 +10181 0 +10182 0 +10183 0 +10184 0 +10185 1 +10186 0 +10187 0 +10188 0 +10189 0 +10190 0 +10191 0 +10192 0 +10193 1 +10194 0 +10195 0 +10196 0 +10197 0 +10198 0 +10199 0 +10200 0 +10201 1 +10202 0 +10203 0 +10204 0 +10205 0 +10206 0 +10207 0 +10208 0 +10209 0 +10210 0 +10211 1 +10212 0 +10213 0 +10214 0 +10215 0 +10216 0 +10217 0 +10218 0 +10219 0 +10220 1 +10221 0 +10222 0 +10223 0 +10224 0 +10225 0 +10226 0 +10227 0 +10228 0 +10229 0 +10230 1 +10231 0 +10232 0 +10233 0 +10234 0 +10235 0 +10236 0 +10237 0 +10238 0 +10239 0 +10240 1 +10241 0 +10242 0 +10243 0 +10244 0 +10245 0 +10246 0 +10247 0 +10248 0 +10249 0 +10250 1 +10251 0 +10252 0 +10253 0 +10254 0 +10255 0 +10256 0 +10257 0 +10258 0 +10259 0 +10260 1 +10261 0 +10262 0 +10263 0 +10264 1 +10265 0 +10266 0 +10267 0 +10268 0 +10269 0 +10270 1 +10271 0 +10272 0 +10273 0 +10274 0 +10275 0 +10276 0 +10277 0 +10278 1 +10279 0 +10280 0 +10281 0 +10282 0 +10283 0 +10284 0 +10285 0 +10286 1 +10287 0 +10288 0 +10289 0 +10290 0 +10291 0 +10292 0 +10293 0 +10294 0 +10295 0 +10296 1 +10297 0 +10298 0 +10299 0 +10300 0 +10301 0 +10302 0 +10303 0 +10304 0 +10305 1 +10306 0 +10307 0 +10308 0 +10309 0 +10310 0 +10311 0 +10312 0 +10313 0 +10314 1 +10315 0 +10316 0 +10317 0 +10318 0 +10319 0 +10320 0 +10321 0 +10322 0 +10323 1 +10324 0 +10325 0 +10326 0 +10327 0 +10328 0 +10329 0 +10330 0 +10331 0 +10332 0 +10333 1 +10334 0 +10335 0 +10336 0 +10337 0 +10338 0 +10339 0 +10340 0 +10341 0 +10342 0 +10343 0 +10344 0 +10345 0 +10346 0 +10347 0 +10348 0 +10349 0 +10350 0 +10351 1 +10352 0 +10353 0 +10354 0 +10355 0 +10356 0 +10357 0 +10358 0 +10359 0 +10360 1 +10361 0 +10362 0 +10363 0 +10364 0 +10365 0 +10366 0 +10367 0 +10368 0 +10369 0 +10370 1 +10371 0 +10372 0 +10373 0 +10374 0 +10375 0 +10376 0 +10377 0 +10378 0 +10379 0 +10380 1 +10381 0 +10382 0 +10383 0 +10384 0 +10385 0 +10386 0 +10387 1 +10388 0 +10389 0 +10390 0 +10391 0 +10392 0 +10393 0 +10394 0 +10395 1 +10396 0 +10397 0 +10398 0 +10399 0 +10400 0 +10401 0 +10402 0 +10403 0 +10404 1 +10405 0 +10406 0 +10407 0 +10408 0 +10409 0 +10410 0 +10411 0 +10412 0 +10413 0 +10414 1 +10415 0 +10416 0 +10417 0 +10418 0 +10419 0 +10420 0 +10421 0 +10422 0 +10423 1 +10424 0 +10425 0 +10426 0 +10427 0 +10428 0 +10429 0 +10430 0 +10431 0 +10432 0 +10433 1 +10434 0 +10435 0 +10436 0 +10437 0 +10438 0 +10439 0 +10440 0 +10441 0 +10442 0 +10443 1 +10444 0 +10445 0 +10446 0 +10447 0 +10448 0 +10449 0 +10450 0 +10451 0 +10452 1 +10453 0 +10454 0 +10455 0 +10456 0 +10457 0 +10458 0 +10459 0 +10460 1 +10461 0 +10462 0 +10463 0 +10464 0 +10465 0 +10466 0 +10467 0 +10468 0 +10469 1 +10470 0 +10471 0 +10472 0 +10473 0 +10474 0 +10475 0 +10476 0 +10477 0 +10478 0 +10479 1 +10480 0 +10481 0 +10482 0 +10483 0 +10484 0 +10485 0 +10486 0 +10487 0 +10488 0 +10489 1 +10490 0 +10491 0 +10492 0 +10493 0 +10494 0 +10495 0 +10496 0 +10497 0 +10498 1 +10499 0 +10500 0 +10501 0 +10502 0 +10503 0 +10504 0 +10505 0 +10506 1 +10507 0 +10508 0 +10509 0 +10510 0 +10511 0 +10512 0 +10513 0 +10514 0 +10515 0 +10516 0 +10517 1 +10518 0 +10519 0 +10520 0 +10521 0 +10522 0 +10523 0 +10524 0 +10525 0 +10526 0 +10527 1 +10528 0 +10529 0 +10530 0 +10531 0 +10532 0 +10533 0 +10534 0 +10535 0 +10536 1 +10537 0 +10538 0 +10539 0 +10540 0 +10541 0 +10542 0 +10543 0 +10544 0 +10545 1 +10546 0 +10547 0 +10548 0 +10549 0 +10550 0 +10551 0 +10552 0 +10553 0 +10554 0 +10555 1 +10556 0 +10557 0 +10558 0 +10559 0 +10560 0 +10561 0 +10562 0 +10563 0 +10564 0 +10565 0 +10566 1 +10567 0 +10568 0 +10569 0 +10570 0 +10571 0 +10572 0 +10573 0 +10574 0 +10575 0 +10576 0 +10577 0 +10578 0 +10579 0 +10580 0 +10581 0 +10582 0 +10583 0 +10584 0 +10585 0 +10586 0 +10587 1 +10588 0 +10589 0 +10590 0 +10591 0 +10592 0 +10593 0 +10594 0 +10595 0 +10596 0 +10597 0 +10598 1 +10599 0 +10600 0 +10601 0 +10602 0 +10603 0 +10604 0 +10605 0 +10606 0 +10607 0 +10608 0 +10609 1 +10610 0 +10611 0 +10612 0 +10613 0 +10614 0 +10615 0 +10616 0 +10617 1 +10618 0 +10619 0 +10620 0 +10621 0 +10622 0 +10623 0 +10624 0 +10625 1 +10626 0 +10627 0 +10628 0 +10629 0 +10630 0 +10631 0 +10632 0 +10633 0 +10634 1 +10635 0 +10636 0 +10637 0 +10638 0 +10639 0 +10640 0 +10641 0 +10642 0 +10643 0 +10644 1 +10645 0 +10646 0 +10647 0 +10648 0 +10649 0 +10650 0 +10651 0 +10652 0 +10653 1 +10654 0 +10655 0 +10656 0 +10657 0 +10658 0 +10659 0 +10660 0 +10661 1 +10662 0 +10663 0 +10664 0 +10665 0 +10666 0 +10667 0 +10668 0 +10669 0 +10670 0 +10671 1 +10672 0 +10673 0 +10674 0 +10675 0 +10676 0 +10677 0 +10678 0 +10679 0 +10680 0 +10681 1 +10682 0 +10683 0 +10684 0 +10685 0 +10686 0 +10687 0 +10688 0 +10689 0 +10690 0 +10691 0 +10692 0 +10693 0 +10694 0 +10695 0 +10696 0 +10697 0 +10698 0 +10699 0 +10700 0 +10701 1 +10702 0 +10703 0 +10704 0 +10705 0 +10706 0 +10707 0 +10708 0 +10709 0 +10710 0 +10711 1 +10712 0 +10713 0 +10714 0 +10715 0 +10716 0 +10717 0 +10718 0 +10719 0 +10720 0 +10721 1 +10722 0 +10723 0 +10724 0 +10725 0 +10726 0 +10727 0 +10728 0 +10729 0 +10730 1 +10731 0 +10732 0 +10733 0 +10734 0 +10735 0 +10736 0 +10737 0 +10738 0 +10739 0 +10740 1 +10741 0 +10742 0 +10743 0 +10744 0 +10745 0 +10746 0 +10747 0 +10748 0 +10749 1 +10750 0 +10751 0 +10752 0 +10753 0 +10754 0 +10755 0 +10756 0 +10757 0 +10758 0 +10759 1 +10760 0 +10761 0 +10762 0 +10763 0 +10764 0 +10765 0 +10766 0 +10767 0 +10768 0 +10769 0 +10770 1 +10771 0 +10772 0 +10773 0 +10774 0 +10775 0 +10776 0 +10777 0 +10778 0 +10779 0 +10780 1 +10781 0 +10782 0 +10783 0 +10784 0 +10785 0 +10786 0 +10787 0 +10788 0 +10789 0 +10790 1 +10791 0 +10792 0 +10793 0 +10794 0 +10795 0 +10796 0 +10797 0 +10798 0 +10799 0 +10800 1 +10801 0 +10802 0 +10803 0 +10804 0 +10805 0 +10806 0 +10807 0 +10808 0 +10809 0 +10810 0 +10811 0 +10812 0 +10813 0 +10814 0 +10815 0 +10816 0 +10817 0 +10818 0 +10819 0 +10820 1 +10821 0 +10822 0 +10823 0 +10824 0 +10825 0 +10826 0 +10827 0 +10828 0 +10829 0 +10830 0 +10831 1 +10832 0 +10833 0 +10834 0 +10835 0 +10836 0 +10837 0 +10838 0 +10839 0 +10840 1 +10841 0 +10842 0 +10843 0 +10844 0 +10845 0 +10846 0 +10847 0 +10848 0 +10849 0 +10850 0 +10851 0 +10852 0 +10853 0 +10854 0 +10855 0 +10856 0 +10857 0 +10858 0 +10859 0 +10860 1 +10861 0 +10862 0 +10863 0 +10864 0 +10865 0 +10866 0 +10867 0 +10868 0 +10869 1 +10870 0 +10871 0 +10872 0 +10873 0 +10874 0 +10875 0 +10876 0 +10877 0 +10878 0 +10879 0 +10880 1 +10881 0 +10882 0 +10883 0 +10884 0 +10885 0 +10886 0 +10887 0 +10888 0 +10889 0 +10890 1 +10891 0 +10892 0 +10893 0 +10894 0 +10895 0 +10896 0 +10897 0 +10898 0 +10899 0 +10900 1 +10901 0 +10902 0 +10903 0 +10904 0 +10905 0 +10906 0 +10907 0 +10908 0 +10909 0 +10910 0 +10911 1 +10912 0 +10913 0 +10914 0 +10915 0 +10916 0 +10917 0 +10918 0 +10919 0 +10920 0 +10921 1 +10922 0 +10923 0 +10924 0 +10925 0 +10926 0 +10927 0 +10928 0 +10929 0 +10930 0 +10931 1 +10932 0 +10933 0 +10934 0 +10935 0 +10936 0 +10937 0 +10938 0 +10939 0 +10940 1 +10941 0 +10942 0 +10943 0 +10944 0 +10945 0 +10946 0 +10947 0 +10948 0 +10949 1 +10950 0 +10951 0 +10952 0 +10953 0 +10954 0 +10955 0 +10956 0 +10957 0 +10958 1 +10959 0 +10960 0 +10961 0 +10962 0 +10963 0 +10964 0 +10965 0 +10966 0 +10967 0 +10968 1 +10969 0 +10970 0 +10971 0 +10972 0 +10973 0 +10974 0 +10975 0 +10976 0 +10977 0 +10978 1 +10979 0 +10980 0 +10981 0 +10982 0 +10983 0 +10984 0 +10985 0 +10986 0 +10987 0 +10988 0 +10989 1 +10990 0 +10991 0 +10992 0 +10993 0 +10994 0 +10995 0 +10996 0 +10997 0 +10998 0 +10999 0 +11000 1 \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..0c44ae7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Isaac Z. Schlueter ("Author") +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md new file mode 100644 index 0000000..34c1189 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md @@ -0,0 +1,15 @@ +# readable-stream + +***Node-core streams for userland*** + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png)](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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..b513d61 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,89 @@ +// 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..895ca50 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,46 @@ +// 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..6307220 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,982 @@ +// 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..eb188df --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,210 @@ +// 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..4bdaa4f --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,386 @@ +// 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/LICENSE new file mode 100644 index 0000000..d8d7f94 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/LICENSE @@ -0,0 +1,19 @@ +Copyright Node.js 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..ff4c851 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// 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(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +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 objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (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; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json new file mode 100644 index 0000000..ddd227e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json @@ -0,0 +1,60 @@ +{ + "name": "core-util-is", + "version": "1.0.2", + "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.git" + }, + "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" + }, + "scripts": { + "test": "tap test.js" + }, + "devDependencies": { + "tap": "^2.3.0" + }, + "gitHead": "a177da234df5638b363ddc15fa324619a38577c8", + "homepage": "https://github.com/isaacs/core-util-is#readme", + "_id": "core-util-is@1.0.2", + "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "_from": "core-util-is@>=1.0.0 <1.1.0", + "_npmVersion": "3.3.2", + "_nodeVersion": "4.0.0", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "dist": { + "shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "tarball": "http://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/test.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/test.js new file mode 100644 index 0000000..1a490c6 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/test.js @@ -0,0 +1,68 @@ +var assert = require('tap'); + +var t = require('./lib/util'); + +assert.equal(t.isArray([]), true); +assert.equal(t.isArray({}), false); + +assert.equal(t.isBoolean(null), false); +assert.equal(t.isBoolean(true), true); +assert.equal(t.isBoolean(false), true); + +assert.equal(t.isNull(null), true); +assert.equal(t.isNull(undefined), false); +assert.equal(t.isNull(false), false); +assert.equal(t.isNull(), false); + +assert.equal(t.isNullOrUndefined(null), true); +assert.equal(t.isNullOrUndefined(undefined), true); +assert.equal(t.isNullOrUndefined(false), false); +assert.equal(t.isNullOrUndefined(), true); + +assert.equal(t.isNumber(null), false); +assert.equal(t.isNumber('1'), false); +assert.equal(t.isNumber(1), true); + +assert.equal(t.isString(null), false); +assert.equal(t.isString('1'), true); +assert.equal(t.isString(1), false); + +assert.equal(t.isSymbol(null), false); +assert.equal(t.isSymbol('1'), false); +assert.equal(t.isSymbol(1), false); +assert.equal(t.isSymbol(Symbol()), true); + +assert.equal(t.isUndefined(null), false); +assert.equal(t.isUndefined(undefined), true); +assert.equal(t.isUndefined(false), false); +assert.equal(t.isUndefined(), true); + +assert.equal(t.isRegExp(null), false); +assert.equal(t.isRegExp('1'), false); +assert.equal(t.isRegExp(new RegExp()), true); + +assert.equal(t.isObject({}), true); +assert.equal(t.isObject([]), true); +assert.equal(t.isObject(new RegExp()), true); +assert.equal(t.isObject(new Date()), true); + +assert.equal(t.isDate(null), false); +assert.equal(t.isDate('1'), false); +assert.equal(t.isDate(new Date()), true); + +assert.equal(t.isError(null), false); +assert.equal(t.isError({ err: true }), false); +assert.equal(t.isError(new Error()), true); + +assert.equal(t.isFunction(null), false); +assert.equal(t.isFunction({ }), false); +assert.equal(t.isFunction(function() {}), true); + +assert.equal(t.isPrimitive(null), true); +assert.equal(t.isPrimitive(''), true); +assert.equal(t.isPrimitive(0), true); +assert.equal(t.isPrimitive(new Date()), false); + +assert.equal(t.isBuffer(null), false); +assert.equal(t.isBuffer({}), false); +assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json new file mode 100644 index 0000000..93d5078 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json @@ -0,0 +1,50 @@ +{ + "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.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "_id": "inherits@2.0.1", + "dist": { + "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/inherits#readme" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md new file mode 100644 index 0000000..052a62b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js new file mode 100644 index 0000000..ec58596 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js new file mode 100644 index 0000000..5f5ad45 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json new file mode 100644 index 0000000..19228ab --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json @@ -0,0 +1,53 @@ +{ + "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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// 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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json new file mode 100644 index 0000000..0364d54 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json @@ -0,0 +1,54 @@ +{ + "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", + "gitHead": "d46d4fd87cf1d06e031c23f1ba170ca7d4ade9a0", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "_id": "string_decoder@0.10.31", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_from": "string_decoder@>=0.10.0 <0.11.0", + "_npmVersion": "1.4.23", + "_npmUser": { + "name": "rvagg", + "email": "rod@vagg.org" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + }, + { + "name": "rvagg", + "email": "rod@vagg.org" + } + ], + "dist": { + "shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "tarball": "http://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json new file mode 100644 index 0000000..2dc3a25 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json @@ -0,0 +1,69 @@ +{ + "name": "readable-stream", + "version": "1.0.31", + "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.git" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/readable-stream/issues" + }, + "homepage": "https://github.com/isaacs/readable-stream", + "_id": "readable-stream@1.0.31", + "_shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", + "_from": "readable-stream@1.0.31", + "_npmVersion": "1.4.9", + "_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": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", + "tarball": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..4d1ddfc --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js @@ -0,0 +1,6 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +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/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/package.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/package.json new file mode 100644 index 0000000..6c01d68 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/package.json @@ -0,0 +1,84 @@ +{ + "name": "mongodb", + "version": "2.1.6", + "description": "MongoDB legacy driver emulation layer on top of mongodb-core", + "main": "index.js", + "repository": { + "type": "git", + "url": "git@github.com:mongodb/node-mongodb-native.git" + }, + "keywords": [ + "mongodb", + "driver", + "legacy" + ], + "dependencies": { + "es6-promise": "3.0.2", + "mongodb-core": "1.3.1", + "readable-stream": "1.0.31" + }, + "devDependencies": { + "JSONStream": "^1.0.7", + "betterbenchmarks": "^0.1.0", + "bluebird": "2.9.27", + "bson": "^0.4.20", + "cli-table": "^0.3.1", + "co": "4.5.4", + "colors": "^1.1.2", + "coveralls": "^2.11.6", + "event-stream": "^3.3.2", + "gleak": "0.5.0", + "integra": "0.1.8", + "jsdoc": "3.3.0-beta3", + "ldjson-stream": "^1.2.1", + "mongodb-extended-json": "1.3.0", + "mongodb-topology-manager": "1.0.x", + "mongodb-version-manager": "^0.8.10", + "nyc": "^5.5.0", + "optimist": "0.6.1", + "rimraf": "2.2.6", + "semver": "4.1.0", + "worker-farm": "^1.3.1" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.3" + }, + "bugs": { + "url": "https://github.com/mongodb/node-mongodb-native/issues" + }, + "scripts": { + "test": "node test/runner.js -t functional", + "coverage": "nyc node test/runner.js -t functional && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls" + }, + "homepage": "https://github.com/mongodb/node-mongodb-native", + "gitHead": "173e568b5e7678b9cf9f3602ac28028309a1b85d", + "_id": "mongodb@2.1.6", + "_shasum": "ebeec407dd72ec1d79f161ddb3e9b1c89fd49380", + "_from": "mongodb@2.1.6", + "_npmVersion": "2.14.12", + "_nodeVersion": "4.2.4", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "ebeec407dd72ec1d79f161ddb3e9b1c89fd49380", + "tarball": "http://registry.npmjs.org/mongodb/-/mongodb-2.1.6.tgz" + }, + "_npmOperationalInternal": { + "host": "packages-9-west.internal.npmjs.com", + "tmp": "tmp/mongodb-2.1.6.tgz_1454648397133_0.14874957758001983" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-2.1.6.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/test.js b/5-2/service/node_modules/mongoose/node_modules/mongodb/test.js new file mode 100644 index 0000000..68f40d1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/test.js @@ -0,0 +1,14 @@ +var MongoClient = require('./').MongoClient; + +MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { + console.dir(err) + + var json = require('./test.json'); + + db.collection('t').insertOne(json, function(err, r) { + console.dir(err) + console.dir(r) + db.close(); + + }) +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/mongodb/test.json b/5-2/service/node_modules/mongoose/node_modules/mongodb/test.json new file mode 100644 index 0000000..6644553 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mongodb/test.json @@ -0,0 +1,28 @@ +{ + "military_base": { + "type": "military", + "level": 0, + "maxLevel": 25, + "upgrade": true, + "targetEnvironment": [], + "timeUntilBuilt": 0, + "costCoef": 0.4, + "requiredResearches": ["foo#4", "bar#1"], + "requiredResources" : ["cash", "metal", "palladium"], + "inProgress": 0, + "queue": [] + }, + "aqua_center": { + "type": "industrial", + "level": 0, + "maxLevel": 25, + "upgrade": true, + "targetEnvironment": ["ocean", "snowy"], + "timeUntilBuilt": 0, + "costCoef": 0.7, + "requiredResearches": ["lorem#10", "ipsum#3"], + "requiredResources" : ["cash", "cristal"], + "inProgress": 0, + "queue": [] + } +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/.npmignore b/5-2/service/node_modules/mongoose/node_modules/mpath/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/.travis.yml b/5-2/service/node_modules/mongoose/node_modules/mpath/.travis.yml new file mode 100644 index 0000000..895dbd3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/History.md b/5-2/service/node_modules/mongoose/node_modules/mpath/History.md new file mode 100644 index 0000000..87de484 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/History.md @@ -0,0 +1,30 @@ + +0.2.1 / 2013-03-22 +================== + + * test; added for #5 + * fix typo that breaks set #5 [Contra](https://github.com/Contra) + +0.2.0 / 2013-03-15 +================== + + * added; adapter support for set + * added; adapter support for get + * add basic benchmarks + * add support for using module as a component #2 [Contra](https://github.com/Contra) + +0.1.1 / 2012-12-21 +================== + + * added; map support + +0.1.0 / 2012-12-13 +================== + + * added; set('array.property', val, object) support + * added; get('array.property', object) support + +0.0.1 / 2012-11-03 +================== + + * initial release diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mpath/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/LICENSE @@ -0,0 +1,22 @@ +(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/5-2/service/node_modules/mongoose/node_modules/mpath/Makefile b/5-2/service/node_modules/mongoose/node_modules/mpath/Makefile new file mode 100644 index 0000000..314c361 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/Makefile @@ -0,0 +1,8 @@ + +test: + @node_modules/mocha/bin/mocha -A $(T) + +bench: + node bench.js + +.PHONY: test diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/README.md b/5-2/service/node_modules/mongoose/node_modules/mpath/README.md new file mode 100644 index 0000000..9831dd0 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/README.md @@ -0,0 +1,278 @@ +#mpath + +{G,S}et javascript object values using MongoDB-like path notation. + +###Getting + +```js +var mpath = require('mpath'); + +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.1.title', obj) // 'exciting!' +``` + +`mpath.get` supports array property notation as well. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.title', obj) // ['funny', 'exciting!'] +``` + +Array property and indexing syntax, when used together, are very powerful. + +```js +var obj = { + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} + +var found = mpath.get('array.o.array.x.b.1', obj); + +console.log(found); // prints.. + + [ [6, undefined] + , [2, undefined, undefined] + , [null, 1] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + +``` + +#####Field selection rules: + +The following rules are iteratively applied to each `segment` in the passed `path`. For example: + +```js +var path = 'one.two.14'; // path +'one' // segment 0 +'two' // segment 1 +14 // segment 2 +``` + +- 1) when value of the segment parent is not an array, return the value of `parent.segment` +- 2) when value of the segment parent is an array + - a) if the segment is an integer, replace the parent array with the value at `parent[segment]` + - b) if not an integer, keep the array but replace each array `item` with the value returned from calling `get(remainingSegments, item)` or undefined if falsey. + +#####Maps + +`mpath.get` also accepts an optional `map` argument which receives each individual found value. The value returned from the `map` function will be used in the original found values place. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.title', obj, function (val) { + return 'funny' == val + ? 'amusing' + : val; +}); +// ['amusing', 'exciting!'] +``` + +###Setting + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.1.title', 'hilarious', obj) +console.log(obj.comments[1].title) // 'hilarious' +``` + +`mpath.set` supports the same array property notation as `mpath.get`. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: 'hilarious' }, + { title: 'fruity' } + ]} +``` + +Array property and indexing syntax can be used together also when setting. + +```js +var obj = { + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ] +} + +mpath.set('array.1.o', 'this was changed', obj); + +console.log(require('util').inspect(obj, false, 1000)); // prints.. + +{ + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: 'this was changed' } + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} + +mpath.set('array.o.array.x', 'this was changed too', obj); + +console.log(require('util').inspect(obj, false, 1000)); // prints.. + +{ + array: [ + { o: { array: [{x: 'this was changed too'}, { y: 10, x: 'this was changed too'} ] }} + , { o: 'this was changed' } + , { o: { array: [{x: 'this was changed too'}, { x: 'this was changed too'}] }} + , { o: { array: [{x: 'this was changed too'}] }} + , { o: { array: [{x: 'this was changed too', y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} +``` + +####Setting arrays + +By default, setting a property within an array to another array results in each element of the new array being set to the item in the destination array at the matching index. An example is helpful. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: 'hilarious' }, + { title: 'fruity' } + ]} +``` + +If we do not desire this destructuring-like assignment behavior we may instead specify the `$` operator in the path being set to force the array to be copied directly. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.$.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: ['hilarious', 'fruity'] }, + { title: ['hilarious', 'fruity'] } + ]} +``` + +####Field assignment rules + +The rules utilized mirror those used on `mpath.get`, meaning we can take values returned from `mpath.get`, update them, and reassign them using `mpath.set`. Note that setting nested arrays of arrays can get unweildy quickly. Check out the [tests](https://github.com/aheckmann/mpath/blob/master/test/index.js) for more extreme examples. + +#####Maps + +`mpath.set` also accepts an optional `map` argument which receives each individual value being set. The value returned from the `map` function will be used in the original values place. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj, function (val) { + return val.length; +}); + +console.log(obj); // prints.. + + { comments: [ + { title: 9 }, + { title: 6 } + ]} +``` + +### Custom object types + +Sometimes you may want to enact the same functionality on custom object types that store all their real data internally, say for an ODM type object. No fear, `mpath` has you covered. Simply pass the name of the property being used to store the internal data and it will be traversed instead: + +```js +var mpath = require('mpath'); + +var obj = { + comments: [ + { title: 'exciting!', _doc: { title: 'great!' }} + ] +} + +mpath.get('comments.0.title', obj, '_doc') // 'great!' +mpath.set('comments.0.title', 'nov 3rd', obj, '_doc') +mpath.get('comments.0.title', obj, '_doc') // 'nov 3rd' +mpath.get('comments.0.title', obj) // 'exciting' +``` + +When used with a `map`, the `map` argument comes last. + +```js +mpath.get(path, obj, '_doc', map); +mpath.set(path, val, obj, '_doc', map); +``` + +[LICENSE](https://github.com/aheckmann/mpath/blob/master/LICENSE) + diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/bench.js b/5-2/service/node_modules/mongoose/node_modules/mpath/bench.js new file mode 100644 index 0000000..7ec6a87 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/bench.js @@ -0,0 +1,109 @@ + +var mpath = require('./') +var Bench = require('benchmark'); +var sha = require('child_process').exec("git log --pretty=format:'%h' -n 1", function (err, sha) { + if (err) throw err; + + var fs = require('fs') + var filename = __dirname + '/bench.out'; + var out = fs.createWriteStream(filename, { flags: 'a', encoding: 'utf8' }); + + /** + * test doc creator + */ + + function doc () { + var o = { first: { second: { third: [3,{ name: 'aaron' }, 9] }}}; + o.comments = [ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ]; + o.name = 'jiro'; + o.array = [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; + o.arr = [ + { arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true } + ] + return o; + } + + var o = doc(); + + var s = new Bench.Suite; + s.add('mpath.get("first", obj)', function () { + mpath.get('first', o); + }) + s.add('mpath.get("first.second", obj)', function () { + mpath.get('first.second', o); + }) + s.add('mpath.get("first.second.third.1.name", obj)', function () { + mpath.get('first.second.third.1.name', o); + }) + s.add('mpath.get("comments", obj)', function () { + mpath.get('comments', o); + }) + s.add('mpath.get("comments.1", obj)', function () { + mpath.get('comments.1', o); + }) + s.add('mpath.get("comments.2.name", obj)', function () { + mpath.get('comments.2.name', o); + }) + s.add('mpath.get("comments.2.comments.1.comments.0.val", obj)', function () { + mpath.get('comments.2.comments.1.comments.0.val', o); + }) + s.add('mpath.get("comments.name", obj)', function () { + mpath.get('comments.name', o); + }) + + s.add('mpath.set("first", obj, val)', function () { + mpath.set('first', o, 1); + }) + s.add('mpath.set("first.second", obj, val)', function () { + mpath.set('first.second', o, 1); + }) + s.add('mpath.set("first.second.third.1.name", obj, val)', function () { + mpath.set('first.second.third.1.name', o, 1); + }) + s.add('mpath.set("comments", obj, val)', function () { + mpath.set('comments', o, 1); + }) + s.add('mpath.set("comments.1", obj, val)', function () { + mpath.set('comments.1', o, 1); + }) + s.add('mpath.set("comments.2.name", obj, val)', function () { + mpath.set('comments.2.name', o, 1); + }) + s.add('mpath.set("comments.2.comments.1.comments.0.val", obj, val)', function () { + mpath.set('comments.2.comments.1.comments.0.val', o, 1); + }) + s.add('mpath.set("comments.name", obj, val)', function () { + mpath.set('comments.name', o, 1); + }) + + s.on('start', function () { + console.log('starting...'); + out.write('*' + sha + ': ' + String(new Date()) + '\n'); + }); + s.on('cycle', function (e) { + var s = String(e.target); + console.log(s); + out.write(s + '\n'); + }) + s.on('complete', function () { + console.log('done') + out.end(''); + }) + s.run() +}) + diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/bench.log b/5-2/service/node_modules/mongoose/node_modules/mpath/bench.log new file mode 100644 index 0000000..e69de29 diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/bench.out b/5-2/service/node_modules/mongoose/node_modules/mpath/bench.out new file mode 100644 index 0000000..40d3c31 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/bench.out @@ -0,0 +1,69 @@ +*b566c26: Fri Mar 15 2013 14:14:04 GMT-0700 (PDT) +mpath.get("first", obj) x 3,827,405 ops/sec ±0.91% (90 runs sampled) +mpath.get("first.second", obj) x 4,930,222 ops/sec ±1.92% (91 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,070,837 ops/sec ±1.45% (97 runs sampled) +mpath.get("comments", obj) x 3,649,771 ops/sec ±1.71% (93 runs sampled) +mpath.get("comments.1", obj) x 3,846,728 ops/sec ±0.86% (94 runs sampled) +mpath.get("comments.2.name", obj) x 3,527,680 ops/sec ±0.95% (96 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,046,982 ops/sec ±0.80% (96 runs sampled) +mpath.get("comments.name", obj) x 625,546 ops/sec ±2.02% (82 runs sampled) +*e42bdb1: Fri Mar 15 2013 14:19:28 GMT-0700 (PDT) +mpath.get("first", obj) x 3,700,783 ops/sec ±1.30% (95 runs sampled) +mpath.get("first.second", obj) x 4,621,795 ops/sec ±0.86% (95 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,012,671 ops/sec ±1.21% (100 runs sampled) +mpath.get("comments", obj) x 3,677,694 ops/sec ±0.80% (96 runs sampled) +mpath.get("comments.1", obj) x 3,798,862 ops/sec ±0.81% (91 runs sampled) +mpath.get("comments.2.name", obj) x 3,489,356 ops/sec ±0.66% (98 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,004,076 ops/sec ±0.85% (99 runs sampled) +mpath.get("comments.name", obj) x 613,270 ops/sec ±1.33% (83 runs sampled) +*0521aac: Fri Mar 15 2013 16:37:16 GMT-0700 (PDT) +mpath.get("first", obj) x 3,834,755 ops/sec ±0.70% (100 runs sampled) +mpath.get("first.second", obj) x 4,999,965 ops/sec ±1.01% (98 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,125,953 ops/sec ±0.97% (100 runs sampled) +mpath.get("comments", obj) x 3,759,233 ops/sec ±0.81% (97 runs sampled) +mpath.get("comments.1", obj) x 3,894,893 ops/sec ±0.76% (96 runs sampled) +mpath.get("comments.2.name", obj) x 3,576,929 ops/sec ±0.68% (98 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,149,610 ops/sec ±0.67% (97 runs sampled) +mpath.get("comments.name", obj) x 629,259 ops/sec ±1.30% (87 runs sampled) +mpath.set("first", obj, val) x 2,869,477 ops/sec ±0.63% (97 runs sampled) +mpath.set("first.second", obj, val) x 2,418,751 ops/sec ±0.62% (98 runs sampled) +mpath.set("first.second.third.1.name", obj, val) x 2,313,099 ops/sec ±0.69% (94 runs sampled) +mpath.set("comments", obj, val) x 2,680,882 ops/sec ±0.76% (99 runs sampled) +mpath.set("comments.1", obj, val) x 2,401,829 ops/sec ±0.68% (98 runs sampled) +mpath.set("comments.2.name", obj, val) x 2,335,081 ops/sec ±1.07% (96 runs sampled) +mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,245,436 ops/sec ±0.76% (92 runs sampled) +mpath.set("comments.name", obj, val) x 2,356,278 ops/sec ±1.15% (100 runs sampled) +*97e85d3: Fri Mar 15 2013 16:39:21 GMT-0700 (PDT) +mpath.get("first", obj) x 3,837,614 ops/sec ±0.74% (99 runs sampled) +mpath.get("first.second", obj) x 4,991,779 ops/sec ±1.01% (94 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,078,455 ops/sec ±1.17% (96 runs sampled) +mpath.get("comments", obj) x 3,770,961 ops/sec ±0.45% (101 runs sampled) +mpath.get("comments.1", obj) x 3,832,814 ops/sec ±0.67% (92 runs sampled) +mpath.get("comments.2.name", obj) x 3,536,436 ops/sec ±0.49% (100 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,141,947 ops/sec ±0.72% (98 runs sampled) +mpath.get("comments.name", obj) x 667,898 ops/sec ±1.62% (85 runs sampled) +mpath.set("first", obj, val) x 2,642,517 ops/sec ±0.72% (98 runs sampled) +mpath.set("first.second", obj, val) x 2,502,124 ops/sec ±1.28% (99 runs sampled) +mpath.set("first.second.third.1.name", obj, val) x 2,426,804 ops/sec ±0.55% (99 runs sampled) +mpath.set("comments", obj, val) x 2,699,478 ops/sec ±0.85% (98 runs sampled) +mpath.set("comments.1", obj, val) x 2,494,454 ops/sec ±1.05% (96 runs sampled) +mpath.set("comments.2.name", obj, val) x 2,463,894 ops/sec ±0.86% (98 runs sampled) +mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,320,398 ops/sec ±0.82% (95 runs sampled) +mpath.set("comments.name", obj, val) x 2,512,408 ops/sec ±0.77% (95 runs sampled) +*2368a6d: Fri Mar 22 2013 14:07:40 GMT-0700 (PDT) +mpath.get("first", obj) x 3,932,284 ops/sec ±0.65% (98 runs sampled) +mpath.get("first.second", obj) x 4,982,307 ops/sec ±1.52% (91 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,094,619 ops/sec ±1.17% (95 runs sampled) +mpath.get("comments", obj) x 3,843,924 ops/sec ±0.76% (95 runs sampled) +mpath.get("comments.1", obj) x 3,864,491 ops/sec ±1.03% (96 runs sampled) +mpath.get("comments.2.name", obj) x 3,568,867 ops/sec ±0.79% (96 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,120,898 ops/sec ±0.94% (95 runs sampled) +mpath.get("comments.name", obj) x 623,508 ops/sec ±1.95% (80 runs sampled) +mpath.set("first", obj, val) x 2,780,551 ops/sec ±1.23% (97 runs sampled) +mpath.set("first.second", obj, val) x 2,227,087 ops/sec ±0.59% (97 runs sampled) +mpath.set("first.second.third.1.name", obj, val) x 2,145,494 ops/sec ±0.86% (96 runs sampled) +mpath.set("comments", obj, val) x 2,768,894 ops/sec ±0.90% (98 runs sampled) +mpath.set("comments.1", obj, val) x 2,202,542 ops/sec ±0.92% (95 runs sampled) +mpath.set("comments.2.name", obj, val) x 2,169,428 ops/sec ±1.10% (96 runs sampled) +mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,060,389 ops/sec ±0.72% (100 runs sampled) +mpath.set("comments.name", obj, val) x 2,128,875 ops/sec ±1.16% (97 runs sampled) diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/component.json b/5-2/service/node_modules/mongoose/node_modules/mpath/component.json new file mode 100644 index 0000000..53c2846 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/component.json @@ -0,0 +1,8 @@ +{ + "name": "mpath", + "version": "0.2.1", + "main": "lib/index.js", + "scripts": [ + "lib/index.js" + ] +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/index.js b/5-2/service/node_modules/mongoose/node_modules/mpath/index.js new file mode 100644 index 0000000..f7b65dd --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/index.js @@ -0,0 +1 @@ +module.exports = exports = require('./lib'); diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/lib/index.js b/5-2/service/node_modules/mongoose/node_modules/mpath/lib/index.js new file mode 100644 index 0000000..1b755b7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/lib/index.js @@ -0,0 +1,215 @@ +/** + * Returns the value of object `o` at the given `path`. + * + * ####Example: + * + * var obj = { + * comments: [ + * { title: 'exciting!', _doc: { title: 'great!' }} + * , { title: 'number dos' } + * ] + * } + * + * mpath.get('comments.0.title', o) // 'exciting!' + * mpath.get('comments.0.title', o, '_doc') // 'great!' + * mpath.get('comments.title', o) // ['exciting!', 'number dos'] + * + * // summary + * mpath.get(path, o) + * mpath.get(path, o, special) + * mpath.get(path, o, map) + * mpath.get(path, o, special, map) + * + * @param {String} path + * @param {Object} o + * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. + * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. + */ + +exports.get = function (path, o, special, map) { + var lookup; + + if ('function' == typeof special) { + if (special.length < 2) { + map = special; + special = undefined; + } else { + lookup = special; + special = undefined; + } + } + + map || (map = K); + + var parts = 'string' == typeof path + ? path.split('.') + : path + + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } + + var obj = o + , part; + + for (var i = 0; i < parts.length; ++i) { + part = parts[i]; + + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + // reading a property from the array items + var paths = parts.slice(i); + + return obj.map(function (item) { + return item + ? exports.get(paths, item, special || lookup, map) + : map(undefined); + }); + } + + if (lookup) { + obj = lookup(obj, part); + } else { + obj = special && obj[special] + ? obj[special][part] + : obj[part]; + } + + if (!obj) return map(obj); + } + + return map(obj); +} + +/** + * Sets the `val` at the given `path` of object `o`. + * + * @param {String} path + * @param {Anything} val + * @param {Object} o + * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. + * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. + */ + +exports.set = function (path, val, o, special, map, _copying) { + var lookup; + + if ('function' == typeof special) { + if (special.length < 2) { + map = special; + special = undefined; + } else { + lookup = special; + special = undefined; + } + } + + map || (map = K); + + var parts = 'string' == typeof path + ? path.split('.') + : path + + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } + + if (null == o) return; + + // the existance of $ in a path tells us if the user desires + // the copying of an array instead of setting each value of + // the array to the one by one to matching positions of the + // current array. + var copy = _copying || /\$/.test(path) + , obj = o + , part + + for (var i = 0, len = parts.length - 1; i < len; ++i) { + part = parts[i]; + + if ('$' == part) { + if (i == len - 1) { + break; + } else { + continue; + } + } + + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + var paths = parts.slice(i); + if (!copy && Array.isArray(val)) { + for (var j = 0; j < obj.length && j < val.length; ++j) { + // assignment of single values of array + exports.set(paths, val[j], obj[j], special || lookup, map, copy); + } + } else { + for (var j = 0; j < obj.length; ++j) { + // assignment of entire value + exports.set(paths, val, obj[j], special || lookup, map, copy); + } + } + return; + } + + if (lookup) { + obj = lookup(obj, part); + } else { + obj = special && obj[special] + ? obj[special][part] + : obj[part]; + } + + if (!obj) return; + } + + // process the last property of the path + + part = parts[len]; + + // use the special property if exists + if (special && obj[special]) { + obj = obj[special]; + } + + // set the value on the last branch + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + if (!copy && Array.isArray(val)) { + for (var item, j = 0; j < obj.length && j < val.length; ++j) { + item = obj[j]; + if (item) { + if (lookup) { + lookup(item, part, map(val[j])); + } else { + if (item[special]) item = item[special]; + item[part] = map(val[j]); + } + } + } + } else { + for (var j = 0; j < obj.length; ++j) { + item = obj[j]; + if (item) { + if (lookup) { + lookup(item, part, map(val)); + } else { + if (item[special]) item = item[special]; + item[part] = map(val); + } + } + } + } + } else { + if (lookup) { + lookup(obj, part, map(val)); + } else { + obj[part] = map(val); + } + } +} + +/*! + * Returns the value passed to it. + */ + +function K (v) { + return v; +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/package.json b/5-2/service/node_modules/mongoose/node_modules/mpath/package.json new file mode 100644 index 0000000..da82844 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/package.json @@ -0,0 +1,48 @@ +{ + "name": "mpath", + "version": "0.2.1", + "description": "{G,S}et object values using MongoDB-like path notation", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mpath.git" + }, + "keywords": [ + "mongodb", + "path", + "get", + "set" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.8.1", + "benchmark": "~1.0.0" + }, + "_id": "mpath@0.2.1", + "dist": { + "shasum": "3a4e829359801de96309c27a6b2e102e89f9e96e", + "tarball": "http://registry.npmjs.org/mpath/-/mpath-0.2.1.tgz" + }, + "_from": "mpath@0.2.1", + "_npmVersion": "1.2.15", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "directories": {}, + "_shasum": "3a4e829359801de96309c27a6b2e102e89f9e96e", + "_resolved": "https://registry.npmjs.org/mpath/-/mpath-0.2.1.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mpath/test/index.js b/5-2/service/node_modules/mongoose/node_modules/mpath/test/index.js new file mode 100644 index 0000000..53bdbd7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpath/test/index.js @@ -0,0 +1,1790 @@ + +/** + * Test dependencies. + */ + +var mpath = require('../') +var assert = require('assert') + +/** + * logging helper + */ + +function log (o) { + console.log(); + console.log(require('util').inspect(o, false, 1000)); +} + +/** + * special path for override tests + */ + +var special = '_doc'; + +/** + * Tests + */ + +describe('mpath', function(){ + + /** + * test doc creator + */ + + function doc () { + var o = { first: { second: { third: [3,{ name: 'aaron' }, 9] }}}; + o.comments = [ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ]; + o.name = 'jiro'; + o.array = [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; + o.arr = [ + { arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true } + ] + return o; + } + + describe('get', function(){ + var o = doc(); + + it('`path` must be a string or array', function(done){ + assert.throws(function () { + mpath.get({}, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(4, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(function(){}, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(/asdf/, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(Math, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(Buffer, o); + }, /Must be either string or array/); + assert.doesNotThrow(function () { + mpath.get('string', o); + }); + assert.doesNotThrow(function () { + mpath.get([], o); + }); + done(); + }) + + describe('without `special`', function(){ + it('works', function(done){ + assert.equal('jiro', mpath.get('name', o)); + + assert.deepEqual( + { second: { third: [3,{ name: 'aaron' }, 9] }} + , mpath.get('first', o) + ); + + assert.deepEqual( + { third: [3,{ name: 'aaron' }, 9] } + , mpath.get('first.second', o) + ); + + assert.deepEqual( + [3,{ name: 'aaron' }, 9] + , mpath.get('first.second.third', o) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o) + ); + + assert.deepEqual([ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], + mpath.get('comments', o)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o)); + assert.deepEqual('one', mpath.get('comments.0.name', o)); + assert.deepEqual('two', mpath.get('comments.1.name', o)); + assert.deepEqual('three', mpath.get('comments.2.name', o)); + + assert.deepEqual([{},{ comments: [{val: 'twoo'}]}] + , mpath.get('comments.2.comments', o)); + + assert.deepEqual({ comments: [{val: 'twoo'}]} + , mpath.get('comments.2.comments.1', o)); + + assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o)); + + done(); + }) + + it('handles array.property dot-notation', function(done){ + assert.deepEqual( + ['one', 'two', 'three'] + , mpath.get('comments.name', o) + ); + done(); + }) + + it('handles array.array notation', function(done){ + assert.deepEqual( + [undefined, undefined, [{}, {comments:[{val:'twoo'}]}]] + , mpath.get('comments.comments', o) + ); + done(); + }) + + it('handles prop.prop.prop.arrayProperty notation', function(done){ + assert.deepEqual( + [undefined, 'aaron', undefined] + , mpath.get('first.second.third.name', o) + ); + assert.deepEqual( + [1, 'aaron', 1] + , mpath.get('first.second.third.name', o, function (v) { + return undefined === v ? 1 : v; + }) + ); + done(); + }) + + it('handles array.prop.array', function(done){ + assert.deepEqual( + [ [{x: {b: [4,6,8]}}, { y: 10} ] + , [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] + , [{x: {b: null }}, { x: { b: [null, 1]}}] + , [{x: null }] + , [{y: 3 }] + , [3, 0, null] + , undefined + ] + , mpath.get('array.o.array', o) + ); + done(); + }) + + it('handles array.prop.array.index', function(done){ + assert.deepEqual( + [ {x: {b: [4,6,8]}} + , {x: {b: [1,2,3]}} + , {x: {b: null }} + , {x: null } + , {y: 3 } + , 3 + , undefined + ] + , mpath.get('array.o.array.0', o) + ); + done(); + }) + + it('handles array.prop.array.index.prop', function(done){ + assert.deepEqual( + [ {b: [4,6,8]} + , {b: [1,2,3]} + , {b: null } + , null + , undefined + , undefined + , undefined + ] + , mpath.get('array.o.array.0.x', o) + ); + done(); + }) + + it('handles array.prop.array.prop', function(done){ + assert.deepEqual( + [ [undefined, 10 ] + , [undefined, undefined, undefined] + , [undefined, undefined] + , [undefined] + , [3] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.y', o) + ); + assert.deepEqual( + [ [{b: [4,6,8]}, undefined] + , [{b: [1,2,3]}, {z: 10 }, {b: 'hi'}] + , [{b: null }, { b: [null, 1]}] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.x', o) + ); + done(); + }) + + it('handles array.prop.array.prop.prop', function(done){ + assert.deepEqual( + [ [[4,6,8], undefined] + , [[1,2,3], undefined, 'hi'] + , [null, [null, 1]] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.x.b', o) + ); + done(); + }) + + it('handles array.prop.array.prop.prop.index', function(done){ + assert.deepEqual( + [ [6, undefined] + , [2, undefined, 'i'] // undocumented feature (string indexing) + , [null, 1] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.x.b.1', o) + ); + assert.deepEqual( + [ [6, 0] + , [2, 0, 'i'] // undocumented feature (string indexing) + , [null, 1] + , [null] + , [0] + , [0, 0, 0] + , 0 + ] + , mpath.get('array.o.array.x.b.1', o, function (v) { + return undefined === v ? 0 : v; + }) + ); + done(); + }) + + it('handles array.index.prop.prop', function(done){ + assert.deepEqual( + [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] + , mpath.get('array.1.o.array', o) + ); + assert.deepEqual( + ['hi','hi','hi'] + , mpath.get('array.1.o.array', o, function (v) { + if (Array.isArray(v)) { + return v.map(function (val) { + return 'hi'; + }) + } + return v; + }) + ); + done(); + }) + + it('handles array.array.index', function(done){ + assert.deepEqual( + [{ a: { c: 48 }}, undefined] + , mpath.get('arr.arr.1', o) + ); + assert.deepEqual( + ['woot', undefined] + , mpath.get('arr.arr.1', o, function (v) { + if (v && v.a && v.a.c) return 'woot'; + return v; + }) + ); + done(); + }) + + it('handles array.array.index.prop', function(done){ + assert.deepEqual( + [{ c: 48 }, 'woot'] + , mpath.get('arr.arr.1.a', o, function (v) { + if (undefined === v) return 'woot'; + return v; + }) + ); + assert.deepEqual( + [{ c: 48 }, undefined] + , mpath.get('arr.arr.1.a', o) + ); + mpath.set('arr.arr.1.a', [{c:49},undefined], o) + assert.deepEqual( + [{ c: 49 }, undefined] + , mpath.get('arr.arr.1.a', o) + ); + mpath.set('arr.arr.1.a', [{c:48},undefined], o) + done(); + }) + + it('handles array.array.index.prop.prop', function(done){ + assert.deepEqual( + [48, undefined] + , mpath.get('arr.arr.1.a.c', o) + ); + assert.deepEqual( + [48, 'woot'] + , mpath.get('arr.arr.1.a.c', o, function (v) { + if (undefined === v) return 'woot'; + return v; + }) + ); + done(); + }) + + }) + + describe('with `special`', function(){ + describe('that is a string', function(){ + it('works', function(done){ + assert.equal('jiro', mpath.get('name', o, special)); + + assert.deepEqual( + { second: { third: [3,{ name: 'aaron' }, 9] }} + , mpath.get('first', o, special) + ); + + assert.deepEqual( + { third: [3,{ name: 'aaron' }, 9] } + , mpath.get('first.second', o, special) + ); + + assert.deepEqual( + [3,{ name: 'aaron' }, 9] + , mpath.get('first.second.third', o, special) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o, special) + ); + + assert.deepEqual( + 4 + , mpath.get('first.second.third.0', o, special, function (v) { + return 3 === v ? 4 : v; + }) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o, special) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o, special) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o, special) + ); + + assert.deepEqual([ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], + mpath.get('comments', o, special)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); + assert.deepEqual('one', mpath.get('comments.0.name', o, special)); + assert.deepEqual('2', mpath.get('comments.1.name', o, special)); + assert.deepEqual('3', mpath.get('comments.2.name', o, special)); + assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function (v) { + return '3' === v ? 'nice' : v; + })); + + assert.deepEqual([{},{ _doc: { comments: [{ val: 2 }] }}] + , mpath.get('comments.2.comments', o, special)); + + assert.deepEqual({ _doc: { comments: [{val: 2}]}} + , mpath.get('comments.2.comments.1', o, special)); + + assert.deepEqual(2, mpath.get('comments.2.comments.1.comments.0.val', o, special)); + done(); + }) + + it('handles array.property dot-notation', function(done){ + assert.deepEqual( + ['one', '2', '3'] + , mpath.get('comments.name', o, special) + ); + assert.deepEqual( + ['one', 2, '3'] + , mpath.get('comments.name', o, special, function (v) { + return '2' === v ? 2 : v + }) + ); + done(); + }) + + it('handles array.array notation', function(done){ + assert.deepEqual( + [undefined, undefined, [{}, {_doc: { comments:[{val:2}]}}]] + , mpath.get('comments.comments', o, special) + ); + done(); + }) + + it('handles array.array.index.array', function(done){ + assert.deepEqual( + [undefined, undefined, [{val:2}]] + , mpath.get('comments.comments.1.comments', o, special) + ); + done(); + }) + + it('handles array.array.index.array.prop', function(done){ + assert.deepEqual( + [undefined, undefined, [2]] + , mpath.get('comments.comments.1.comments.val', o, special) + ); + assert.deepEqual( + ['nil', 'nil', [2]] + , mpath.get('comments.comments.1.comments.val', o, special, function (v) { + return undefined === v ? 'nil' : v; + }) + ); + done(); + }) + }) + + describe('that is a function', function(){ + var special = function (obj, key) { + return obj[key] + } + + it('works', function(done){ + assert.equal('jiro', mpath.get('name', o, special)); + + assert.deepEqual( + { second: { third: [3,{ name: 'aaron' }, 9] }} + , mpath.get('first', o, special) + ); + + assert.deepEqual( + { third: [3,{ name: 'aaron' }, 9] } + , mpath.get('first.second', o, special) + ); + + assert.deepEqual( + [3,{ name: 'aaron' }, 9] + , mpath.get('first.second.third', o, special) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o, special) + ); + + assert.deepEqual( + 4 + , mpath.get('first.second.third.0', o, special, function (v) { + return 3 === v ? 4 : v; + }) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o, special) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o, special) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o, special) + ); + + assert.deepEqual([ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], + mpath.get('comments', o, special)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); + assert.deepEqual('one', mpath.get('comments.0.name', o, special)); + assert.deepEqual('two', mpath.get('comments.1.name', o, special)); + assert.deepEqual('three', mpath.get('comments.2.name', o, special)); + assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function (v) { + return 'three' === v ? 'nice' : v; + })); + + assert.deepEqual([{},{ comments: [{ val: 'twoo' }] }] + , mpath.get('comments.2.comments', o, special)); + + assert.deepEqual({ comments: [{val: 'twoo'}]} + , mpath.get('comments.2.comments.1', o, special)); + + assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o, special)); + + var overide = false; + assert.deepEqual('twoo', mpath.get('comments.8.comments.1.comments.0.val', o, function (obj, path) { + if (Array.isArray(obj) && 8 == path) { + overide = true; + return obj[2]; + } + return obj[path]; + })); + assert.ok(overide); + + done(); + }) + + it('in combination with map', function(done){ + var special = function (obj, key) { + if (Array.isArray(obj)) return obj[key]; + return obj.mpath; + } + var map = function (val) { + return 'convert' == val + ? 'mpath' + : val; + } + var o = { mpath: [{ mpath: 'converse' }, { mpath: 'convert' }] } + + assert.equal('mpath', mpath.get('something.1.kewl', o, special, map)); + done(); + }) + }) + }) + }) + + describe('set', function(){ + describe('without `special`', function(){ + var o = doc(); + + it('works', function(done){ + mpath.set('name', 'a new val', o, function (v) { + return 'a new val' === v ? 'changed' : v; + }); + assert.deepEqual('changed', o.name); + + mpath.set('name', 'changed', o); + assert.deepEqual('changed', o.name); + + mpath.set('first.second.third', [1,{name:'x'},9], o); + assert.deepEqual([1,{name:'x'},9], o.first.second.third); + + mpath.set('first.second.third.1.name', 'y', o) + assert.deepEqual([1,{name:'y'},9], o.first.second.third); + + mpath.set('comments.1.name', 'ttwwoo', o); + assert.deepEqual({ name: 'ttwwoo', _doc: { name: '2' }}, o.comments[1]); + + mpath.set('comments.2.comments.1.comments.0.expand', 'added', o); + assert.deepEqual( + { val: 'twoo', expand: 'added'} + , o.comments[2].comments[1].comments[0]); + + mpath.set('comments.2.comments.1.comments.2', 'added', o); + assert.equal(3, o.comments[2].comments[1].comments.length); + assert.deepEqual( + { val: 'twoo', expand: 'added'} + , o.comments[2].comments[1].comments[0]); + assert.deepEqual( + undefined + , o.comments[2].comments[1].comments[1]); + assert.deepEqual( + 'added' + , o.comments[2].comments[1].comments[2]); + + done(); + }) + + describe('array.path', function(){ + describe('with single non-array value', function(){ + it('works', function(done){ + mpath.set('arr.yep', false, o, function (v) { + return false === v ? true: v; + }); + assert.deepEqual([ + { yep: true, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true } + ], o.arr); + + mpath.set('arr.yep', false, o); + + assert.deepEqual([ + { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: false } + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('that are equal in length', function(done){ + mpath.set('arr.yep', ['one',2], o, function (v) { + return 'one' === v ? 1 : v; + }); + assert.deepEqual([ + { yep: 1, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + mpath.set('arr.yep', ['one',2], o); + + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + + done(); + }) + + it('that is less than length', function(done){ + mpath.set('arr.yep', [47], o, function (v) { + return 47 === v ? 4 : v; + }); + assert.deepEqual([ + { yep: 4, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + + mpath.set('arr.yep', [47], o); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + + done(); + }) + + it('that is greater than length', function(done){ + mpath.set('arr.yep', [5,6,7], o, function (v) { + return 5 === v ? 'five' : v; + }); + assert.deepEqual([ + { yep: 'five', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 6 } + ], o.arr); + + mpath.set('arr.yep', [5,6,7], o); + assert.deepEqual([ + { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 6 } + ], o.arr); + + done(); + }) + }) + }) + + describe('array.$.path', function(){ + describe('with single non-array value', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', {xtra: 'double good'}, o, function (v) { + return v && v.xtra ? 'hi' : v; + }); + assert.deepEqual([ + { yep: 'hi', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 'hi'} + ], o.arr); + + mpath.set('arr.$.yep', {xtra: 'double good'}, o); + assert.deepEqual([ + { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: {xtra:'double good'}} + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', [15], o, function (v) { + return v.length === 1 ? [] : v; + }); + assert.deepEqual([ + { yep: [], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: []} + ], o.arr); + + mpath.set('arr.$.yep', [15], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: [15]} + ], o.arr); + + done(); + }) + }) + }) + + describe('array.index.path', function(){ + it('works', function(done){ + mpath.set('arr.1.yep', 0, o, function (v) { + return 0 === v ? 'zero' : v; + }); + assert.deepEqual([ + { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 'zero' } + ], o.arr); + + mpath.set('arr.1.yep', 0, o); + assert.deepEqual([ + { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.e', 35, o, function (v) { + return 35 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 3}, { a: { c: 48 }, e: 3}, { d: 'yep', e: 3 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.e', 35, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.e', ['a','b'], o, function (v) { + return 'a' === v ? 'x' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 'x'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.e', ['a','b'], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.a.b', 36, o, function (v) { + return 36 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 3 }, e: 'a'}, { a: { c: 48, b: 3 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.a.b', 36, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.a.b', [1,2,3,4], o, function (v) { + return 2 === v ? 'two' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 'two' }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.a.b', [1,2,3,4], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.$.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.$.a.b', '$', o, function (v) { + return '$' === v ? 'dolla billz' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 'dolla billz' }, e: 'a'}, { a: { c: 48, b: 'dolla billz' }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', '$', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.$.a.b', [1], o, function (v) { + return Array.isArray(v) ? {} : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', [1], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.array.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.0.a', 'single', o, function (v) { + return 'single' === v ? 'double' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'double', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.arr.0.a', 'single', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, function (v) { + return 4 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 3, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: false } + ], o.arr); + + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: false } + ], o.arr); + + done(); + }) + }) + + describe('array.array.$.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.$.0.a', 'singles', o, function (v) { + return 0; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 0, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.arr.$.0.a', 'singles', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('$.arr.arr.0.a', 'single', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, function (v) { + return 'nope' + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'nope', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + done(); + }) + }) + + describe('array.array.path.index', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.a.7', 47, o, function (v) { + return 1 + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,1], e: 'a'}, { a: { c: 48, b: [1], '7': 1 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + mpath.set('arr.arr.a.7', 47, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + done(); + }) + it('with array', function(done){ + o.arr[1].arr = [{ a: [] }, { a: [] }, { a: null }]; + mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o); + + var a1 = []; + var a2 = []; + a1[7] = undefined; + a2[7] = 'woot'; + + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0, arr: [{a:a1},{a:a2},{a:null}] } + ], o.arr); + + done(); + }) + }) + + describe('handles array.array.path', function(){ + it('with single', function(done){ + o.arr[1].arr = [{},{}]; + assert.deepEqual([{},{}], o.arr[1].arr); + o.arr.push({ arr: 'something else' }); + o.arr.push({ arr: ['something else'] }); + o.arr.push({ arr: [[]] }); + o.arr.push({ arr: [5] }); + + var weird = []; + weird.e = 'xmas'; + + // test + mpath.set('arr.arr.e', 47, o, function (v) { + return 'xmas' + }); + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 'xmas'} + , { a: { c: 48, b: [1], '7': 46 }, e: 'xmas'} + , { d: 'yep', e: 'xmas' } + ] + } + , { yep: 0, arr: [{e: 'xmas'}, {e:'xmas'}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + weird.e = 47; + + mpath.set('arr.arr.e', 47, o); + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 47} + , { a: { c: 48, b: [1], '7': 46 }, e: 47} + , { d: 'yep', e: 47 } + ] + } + , { yep: 0, arr: [{e: 47}, {e:47}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + done(); + }) + it('with arrays', function(done){ + mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, function (v) { + return 10; + }); + + var weird = []; + weird.e = 10; + + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 10} + , { a: { c: 48, b: [1], '7': 46 }, e: 10} + , { d: 'yep', e: 10 } + ] + } + , { yep: 0, arr: [{e: 10}, {e:10}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o); + + weird.e = 6; + + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 1} + , { a: { c: 48, b: [1], '7': 46 }, e: 2} + , { d: 'yep', e: 3 } + ] + } + , { yep: 0, arr: [{e: 4}, {e:5}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + done(); + }) + }) + }) + + describe('with `special`', function(){ + var o = doc(); + + it('works', function(done){ + mpath.set('name', 'chan', o, special, function (v) { + return 'hi'; + }); + assert.deepEqual('hi', o.name); + + mpath.set('name', 'changer', o, special); + assert.deepEqual('changer', o.name); + + mpath.set('first.second.third', [1,{name:'y'},9], o, special); + assert.deepEqual([1,{name:'y'},9], o.first.second.third); + + mpath.set('first.second.third.1.name', 'z', o, special) + assert.deepEqual([1,{name:'z'},9], o.first.second.third); + + mpath.set('comments.1.name', 'ttwwoo', o, special); + assert.deepEqual({ name: 'two', _doc: { name: 'ttwwoo' }}, o.comments[1]); + + mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special, function (v) { + return 'super' + }); + assert.deepEqual( + { val: 2, expander: 'super'} + , o.comments[2]._doc.comments[1]._doc.comments[0]); + + mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special); + assert.deepEqual( + { val: 2, expander: 'adder'} + , o.comments[2]._doc.comments[1]._doc.comments[0]); + + mpath.set('comments.2.comments.1.comments.2', 'set', o, special); + assert.equal(3, o.comments[2]._doc.comments[1]._doc.comments.length); + assert.deepEqual( + { val: 2, expander: 'adder'} + , o.comments[2]._doc.comments[1]._doc.comments[0]); + assert.deepEqual( + undefined + , o.comments[2]._doc.comments[1]._doc.comments[1]); + assert.deepEqual( + 'set' + , o.comments[2]._doc.comments[1]._doc.comments[2]); + done(); + }) + + describe('array.path', function(){ + describe('with single non-array value', function(){ + it('works', function(done){ + o.arr[1]._doc = { special: true } + + mpath.set('arr.yep', false, o, special, function (v) { + return 'yes'; + }); + assert.deepEqual([ + { yep: 'yes', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 'yes'}} + ], o.arr); + + mpath.set('arr.yep', false, o, special); + assert.deepEqual([ + { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: false }} + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('that are equal in length', function(done){ + mpath.set('arr.yep', ['one',2], o, special, function (v) { + return 2 === v ? 20 : v; + }); + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 20}} + ], o.arr); + + mpath.set('arr.yep', ['one',2], o, special); + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + done(); + }) + + it('that is less than length', function(done){ + mpath.set('arr.yep', [47], o, special, function (v) { + return 80; + }); + assert.deepEqual([ + { yep: 80, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + mpath.set('arr.yep', [47], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + // add _doc to first element + o.arr[0]._doc = { yep: 46, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + + mpath.set('arr.yep', [20], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 20, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + done(); + }) + + it('that is greater than length', function(done){ + mpath.set('arr.yep', [5,6,7], o, special, function () { + return 'x'; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 'x', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 'x'}} + ], o.arr); + + mpath.set('arr.yep', [5,6,7], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 6}} + ], o.arr); + + done(); + }) + }) + }) + + describe('array.$.path', function(){ + describe('with single non-array value', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', {xtra: 'double good'}, o, special, function (v) { + return 9; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: 9, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 9}} + ], o.arr); + + mpath.set('arr.$.yep', {xtra: 'double good'}, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: {xtra:'double good'}}} + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', [15], o, special, function (v) { + return 'array' + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: 'array', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 'array'}} + ], o.arr); + + mpath.set('arr.$.yep', [15], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: [15]}} + ], o.arr); + + done(); + }) + }) + }) + + describe('array.index.path', function(){ + it('works', function(done){ + mpath.set('arr.1.yep', 0, o, special, function (v) { + return 1; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 1}} + ], o.arr); + + mpath.set('arr.1.yep', 0, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.e', 35, o, special, function (v) { + return 30 + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 30}, { a: { c: 48 }, e: 30}, { d: 'yep', e: 30 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.e', 35, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.e', ['a','b'], o, special, function (v) { + return 'a' === v ? 'A' : v; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'A'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.e', ['a','b'], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.a.b', 36, o, special, function (v) { + return 20 + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 20 }, e: 'a'}, { a: { c: 48, b: 20 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.a.b', 36, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special, function (v) { + return v*2; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 2 }, e: 'a'}, { a: { c: 48, b: 4 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.$.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.$.a.b', '$', o, special, function (v) { + return 'dollaz' + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 'dollaz' }, e: 'a'}, { a: { c: 48, b: 'dollaz' }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', '$', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.$.a.b', [1], o, special, function (v) { + return {}; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', [1], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.array.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.0.a', 'single', o, special, function (v) { + return 88; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 88, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.0.a', 'single', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special, function (v) { + return v*2; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 8, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.array.$.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.$.0.a', 'singles', o, special, function (v) { + return v.toUpperCase(); + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'SINGLES', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.$.0.a', 'singles', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('$.arr.arr.0.a', 'single', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special, function (v) { + return Array + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: Array, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.array.path.index', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.a.7', 47, o, special, function (v) { + return Object; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,Object], e: 'a'}, { a: { c: 48, b: [1], '7': Object }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.a.7', 47, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + o.arr[1]._doc.arr = [{ a: [] }, { a: [] }, { a: null }]; + mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special, function (v) { + return undefined === v ? 'nope' : v; + }); + + var a1 = []; + var a2 = []; + a1[7] = 'nope'; + a2[7] = 'woot'; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special); + + a1[7] = undefined; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('handles array.array.path', function(){ + it('with single', function(done){ + o.arr[1]._doc.arr = [{},{}]; + assert.deepEqual([{},{}], o.arr[1]._doc.arr); + o.arr.push({ _doc: { arr: 'something else' }}); + o.arr.push({ _doc: { arr: ['something else'] }}); + o.arr.push({ _doc: { arr: [[]] }}); + o.arr.push({ _doc: { arr: [5] }}); + + // test + mpath.set('arr.arr.e', 47, o, special); + + var weird = []; + weird.e = 47; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { + yep: [15] + , arr: [ + { a: [4,8,15,16,23,42,108,null], e: 47} + , { a: { c: 48, b: [1], '7': 46 }, e: 47} + , { d: 'yep', e: 47 } + ] + } + } + , { yep: true + , _doc: { + arr: [ + {e:47} + , {e:47} + ] + , special: true + , yep: 0 + } + } + , { _doc: { arr: 'something else' }} + , { _doc: { arr: ['something else'] }} + , { _doc: { arr: [weird] }} + , { _doc: { arr: [5] }} + ] + , o.arr); + + done(); + }) + it('with arrays', function(done){ + mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, special); + + var weird = []; + weird.e = 6; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { + yep: [15] + , arr: [ + { a: [4,8,15,16,23,42,108,null], e: 1} + , { a: { c: 48, b: [1], '7': 46 }, e: 2} + , { d: 'yep', e: 3 } + ] + } + } + , { yep: true + , _doc: { + arr: [ + {e:4} + , {e:5} + ] + , special: true + , yep: 0 + } + } + , { _doc: { arr: 'something else' }} + , { _doc: { arr: ['something else'] }} + , { _doc: { arr: [weird] }} + , { _doc: { arr: [5] }} + ] + , o.arr); + + done(); + }) + }) + + describe('that is a function', function(){ + describe('without map', function(){ + it('works on array value', function(done){ + var o = { hello: { world: [{ how: 'are' }, { you: '?' }] }}; + var special = function (obj, key, val) { + if (val) { + obj[key] = val; + } else { + return 'thing' == key + ? obj.world + : obj[key] + } + } + mpath.set('hello.thing.how', 'arrrr', o, special); + assert.deepEqual(o, { hello: { world: [{ how: 'arrrr' }, { you: '?', how: 'arrrr' }] }}); + done(); + }) + it('works on non-array value', function(done){ + var o = { hello: { world: { how: 'are you' }}}; + var special = function (obj, key, val) { + if (val) { + obj[key] = val; + } else { + return 'thing' == key + ? obj.world + : obj[key] + } + } + mpath.set('hello.thing.how', 'RU', o, special); + assert.deepEqual(o, { hello: { world: { how: 'RU' }}}); + done(); + }) + }) + it('works with map', function(done){ + var o = { hello: { world: [{ how: 'are' }, { you: '?' }] }}; + var special = function (obj, key, val) { + if (val) { + obj[key] = val; + } else { + return 'thing' == key + ? obj.world + : obj[key] + } + } + var map = function (val) { + return 'convert' == val + ? 'ºº' + : val + } + mpath.set('hello.thing.how', 'convert', o, special, map); + assert.deepEqual(o, { hello: { world: [{ how: 'ºº' }, { you: '?', how: 'ºº' }] }}); + done(); + }) + }) + + }) + + describe('get/set integration', function(){ + var o = doc(); + + it('works', function(done){ + var vals = mpath.get('array.o.array.x.b', o); + + vals[0][0][2] = 10; + vals[1][0][1] = 0; + vals[1][1] = 'Rambaldi'; + vals[1][2] = [12,14]; + vals[2] = [{changed:true}, [null, ['changed','to','array']]]; + + mpath.set('array.o.array.x.b', vals, o); + + var t = [ + { o: { array: [{x: {b: [4,6,10]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,0,3]}}, { x: {b:'Rambaldi',z: 10 }}, { x: {b: [12,14]}}] }} + , { o: { array: [{x: {b: {changed:true}}}, { x: { b: [null, ['changed','to','array']]}}]}} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; + assert.deepEqual(t, o.array); + done(); + }) + + it('array.prop', function(done){ + mpath.set('comments.name', ['this', 'was', 'changed'], o); + + assert.deepEqual([ + { name: 'this' } + , { name: 'was', _doc: { name: '2' }} + , { name: 'changed' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ], o.comments); + + mpath.set('comments.name', ['also', 'changed', 'this'], o, special); + + assert.deepEqual([ + { name: 'also' } + , { name: 'was', _doc: { name: 'changed' }} + , { name: 'changed' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: 'this', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ], o.comments); + + done(); + }) + + }) + + describe('multiple $ use', function(){ + var o = doc(); + it('is ok', function(done){ + assert.doesNotThrow(function () { + mpath.set('arr.$.arr.$.a', 35, o); + }); + done(); + }) + }) + + it('ignores setting a nested path that doesnt exist', function(done){ + var o = doc(); + assert.doesNotThrow(function(){ + mpath.set('thing.that.is.new', 10, o); + }) + done(); + }) + }) + +}) diff --git a/5-2/service/node_modules/mongoose/node_modules/mpromise/.npmignore b/5-2/service/node_modules/mongoose/node_modules/mpromise/.npmignore new file mode 100644 index 0000000..e86496f --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpromise/.npmignore @@ -0,0 +1,4 @@ +*.sw* +node_modules/ +.DS_Store +.idea \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mpromise/.travis.yml b/5-2/service/node_modules/mongoose/node_modules/mpromise/.travis.yml new file mode 100644 index 0000000..d63ba09 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpromise/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 diff --git a/5-2/service/node_modules/mongoose/node_modules/mpromise/History.md b/5-2/service/node_modules/mongoose/node_modules/mpromise/History.md new file mode 100644 index 0000000..12c0dc3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpromise/History.md @@ -0,0 +1,80 @@ +0.5.5 / 2014-09-19 +================== + + * change `end()` semantics + * add `catch()` as in ES6 + +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/5-2/service/node_modules/mongoose/node_modules/mpromise/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mpromise/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpromise/LICENSE @@ -0,0 +1,22 @@ +(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/5-2/service/node_modules/mongoose/node_modules/mpromise/README.md b/5-2/service/node_modules/mongoose/node_modules/mpromise/README.md new file mode 100644 index 0000000..2906f56 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpromise/README.md @@ -0,0 +1,224 @@ +#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/5-2/service/node_modules/mongoose/node_modules/mpromise/lib/promise.js b/5-2/service/node_modules/mongoose/node_modules/mpromise/lib/promise.js new file mode 100644 index 0000000..3cb4419 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpromise/lib/promise.js @@ -0,0 +1,445 @@ +'use strict'; +var util = require('util'); +var EventEmitter = require('events').EventEmitter; +function toArray(arr, start, end) { + return Array.prototype.slice.call(arr, start, end) +} +function strongUnshift(x, arrLike) { + var arr = toArray(arrLike); + arr.unshift(x); + return arr; +} + + +/** + * MPromise 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) { + this.emitter = new EventEmitter(); + this.emitted = {}; + this.ended = false; + if ('function' == typeof back) { + this.ended = true; + this.onResolve(back); + } +} + + +/* + * Module exports. + */ +module.exports = Promise; + + +/*! + * event names + */ +Promise.SUCCESS = 'fulfill'; +Promise.FAILURE = 'reject'; + + +/** + * 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 {MPromise} this + * @api private + */ +Promise.prototype.on = function (event, callback) { + if (this.emitted[event]) + callback.apply(undefined, this.emitted[event]); + else + this.emitter.on(event, callback); + + return this; +}; + + +/** + * Keeps track of emitted events to run them on `on`. + * + * @api private + */ +Promise.prototype.safeEmit = function (event) { + // ensures a promise can't be fulfill() or reject() more than once + if (event == Promise.SUCCESS || event == Promise.FAILURE) { + if (this.emitted[Promise.SUCCESS] || this.emitted[Promise.FAILURE]) { + return this; + } + this.emitted[event] = toArray(arguments, 1); + } + + this.emitter.emit.apply(this.emitter, arguments); + return this; +}; + + +/** + * @api private + */ +Promise.prototype.hasRejectListeners = function () { + return EventEmitter.listenerCount(this.emitter, Promise.FAILURE) > 0; +}; + + +/** + * 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 () { + return this.safeEmit.apply(this, strongUnshift(Promise.SUCCESS, arguments)); +}; + + +/** + * 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 {MPromise} this + */ +Promise.prototype.reject = function (reason) { + if (this.ended && !this.hasRejectListeners()) + throw reason; + return this.safeEmit(Promise.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 {MPromise} 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(Promise.SUCCESS, fn); +}; + + +/** + * Adds a listener to the FAILURE event. + * + * @return {MPromise} 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(Promise.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...) {} + * + * Also marks the promise as `end`ed, since it's the common use-case, and yet has no + * side effects unless `fn` is undefined or null. + * + * @param {Function} fn + * @return {MPromise} this + */ +Promise.prototype.onResolve = function (fn) { + if (!fn) return this; + if ('function' != typeof fn) throw new TypeError("fn should be a function"); + this.on(Promise.FAILURE, function (err) { fn.call(this, err); }); + this.on(Promise.SUCCESS, function () { fn.apply(this, strongUnshift(null, arguments)); }); + 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 {MPromise} newPromise + */ +Promise.prototype.then = function (onFulfill, onReject) { + var newPromise = new Promise; + + if ('function' == typeof onFulfill) { + this.onFulfill(handler(newPromise, onFulfill)); + } else { + this.onFulfill(newPromise.fulfill.bind(newPromise)); + } + + if ('function' == typeof onReject) { + this.onReject(handler(newPromise, onReject)); + } else { + this.onReject(newPromise.reject.bind(newPromise)); + } + + return newPromise; +}; + + +function handler(promise, fn) { + function newTickHandler() { + var pDomain = promise.emitter.domain; + if (pDomain && pDomain !== process.domain) pDomain.enter(); + try { + var x = fn.apply(undefined, boundHandler.args); + } catch (err) { + promise.reject(err); + return; + } + resolve(promise, x); + } + function boundHandler() { + boundHandler.args = arguments; + process.nextTick(newTickHandler); + } + return boundHandler; +} + + +function resolve(promise, x) { + function fulfillOnce() { + if (done++) return; + resolve.apply(undefined, strongUnshift(promise, arguments)); + } + function rejectOnce(reason) { + if (done++) return; + promise.reject(reason); + } + + if (promise === x) { + promise.reject(new TypeError("promise and x are the same")); + return; + } + var rest = toArray(arguments, 1); + var type = typeof x; + if ('undefined' == type || null == x || !('object' == type || 'function' == type)) { + promise.fulfill.apply(promise, rest); + return; + } + + try { + var theThen = x.then; + } catch (err) { + promise.reject(err); + return; + } + + if ('function' != typeof theThen) { + promise.fulfill.apply(promise, rest); + return; + } + + var done = 0; + try { + var ret = theThen.call(x, fulfillOnce, rejectOnce); + return ret; + } catch (err) { + if (done++) return; + promise.reject(err); + } +} + + +/** + * 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 {MPromise} this + */ +Promise.prototype.end = Promise.prototype['catch'] = function (onReject) { + if (!onReject && !this.hasRejectListeners()) + onReject = function idRejector(e) { throw e; }; + 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 {MPromise} p + * @param {String} name + * @return {MPromise} this + */ +Promise.trace = function (p, name) { + p.then( + function () { + console.log("%s fulfill %j", name, toArray(arguments)); + }, + function () { + console.log("%s reject %j", name, toArray(arguments)); + } + ) +}; + + +Promise.prototype.chain = function (p2) { + var p1 = this; + p1.onFulfill(p2.fulfill.bind(p2)); + p1.onReject(p2.reject.bind(p2)); + return p2; +}; + + +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; +}; + + +/* This is for the A+ tests, but it's very useful as well */ +Promise.fulfilled = function fulfilled() { var p = new Promise; p.fulfill.apply(p, arguments); return p; }; +Promise.rejected = function rejected(reason) { return new Promise().reject(reason); }; +Promise.deferred = function deferred() { + var p = new Promise; + return { + promise: p, + reject: p.reject.bind(p), + resolve: p.fulfill.bind(p), + callback: p.resolve.bind(p) + } +}; +/* End A+ tests adapter bit */ diff --git a/5-2/service/node_modules/mongoose/node_modules/mpromise/package.json b/5-2/service/node_modules/mongoose/node_modules/mpromise/package.json new file mode 100644 index 0000000..05b1d76 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpromise/package.json @@ -0,0 +1,65 @@ +{ + "name": "mpromise", + "version": "0.5.5", + "description": "Promises A+ conformant implementation", + "main": "lib/promise.js", + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "promises-aplus-tests": "2.1.0", + "mocha": "1.21.4" + }, + "repository": { + "type": "git", + "url": "https://github.com/aheckmann/mpromise" + }, + "keywords": [ + "promise", + "mongoose", + "aplus", + "a+", + "plus" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "contributors": [ + { + "name": "Refael Ackermann", + "email": "refack@gmail", + "url": "http://node.org.il/" + } + ], + "license": "MIT", + "gitHead": "c8842ff1065e9fceef0eef7e97bdb291b7c2550e", + "bugs": { + "url": "https://github.com/aheckmann/mpromise/issues" + }, + "homepage": "https://github.com/aheckmann/mpromise", + "_id": "mpromise@0.5.5", + "_shasum": "f5b24259d763acc2257b0a0c8c6d866fd51732e6", + "_from": "mpromise@0.5.5", + "_npmVersion": "2.0.0-beta.2", + "_npmUser": { + "name": "refack", + "email": "refael@empeeric.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "refack", + "email": "refael@empeeric.com" + } + ], + "dist": { + "shasum": "f5b24259d763acc2257b0a0c8c6d866fd51732e6", + "tarball": "http://registry.npmjs.org/mpromise/-/mpromise-0.5.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mpromise/-/mpromise-0.5.5.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js b/5-2/service/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js new file mode 100644 index 0000000..a6a6be7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js @@ -0,0 +1,28 @@ +var Promise = require('../') + , Domain = require('domain').Domain + , assert = require('assert'); + + +describe("domains", function () { + it("exceptions should not breakout of domain boundaries", function (done) { + if (process.version.indexOf('v0.10') != 0) return done(); + var d = new Domain; + d.on('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(); + }); + + process.nextTick(function () { + p.fulfill(); + }); + }); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/mpromise/test/promise.test.js b/5-2/service/node_modules/mongoose/node_modules/mpromise/test/promise.test.js new file mode 100644 index 0000000..bf3044d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpromise/test/promise.test.js @@ -0,0 +1,554 @@ +/*global describe,it */ +/** + * Module dependencies. + */ + +var assert = require('assert'); +var MPromise = require('../'); + +/** + * Test. + */ + +describe('promise', function () { + it('events fire right after fulfill()', function (done) { + var promise = new MPromise() + , 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 MPromise() + , 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 MPromise(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 MPromise() + , called = 0; + + promise.fulfill('woot'); + + promise.onResolve(function (err, data) { + assert.equal(data, 'woot'); + called++; + }); + + promise.onResolve(function (err) { + assert.strictEqual(err, null); + called++; + }); + + assert.equal(2, called); + done(); + }) + }); + + describe('onFulfill shortcut', function () { + it('works', function (done) { + var promise = new MPromise() + , 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 MPromise() + , 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 MPromise(); + assert.ok(promise.on('jump', function () {}) instanceof MPromise); + done() + }); + + it('onFulfill()', function (done) { + var promise = new MPromise(); + assert.ok(promise.onFulfill(function () {}) instanceof MPromise); + done(); + }); + it('onReject()', function (done) { + var promise = new MPromise(); + assert.ok(promise.onReject(function () {}) instanceof MPromise); + done(); + }); + it('onResolve()', function (done) { + var promise = new MPromise(); + assert.ok(promise.onResolve(function () {}) instanceof MPromise); + done(); + }) + }); + + describe('casting errors', function () { + describe('reject()', function () { + it('does not cast arguments to Error', function (done) { + var p = new MPromise(function (err) { + 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 MPromise; + 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 MPromise; + 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 MPromise; + 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.10') != 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 MPromise; + 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 MPromise; + 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 MPromise; + 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 MPromise; + + 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('fulfill values and splats', function () { + it('should handle multiple values', function (done) { + var p = new MPromise; + p.onFulfill(function (a, b, c) { + assert.equal('a', a); + assert.equal('b', b); + assert.equal('c', c); + done(); + }); + p.fulfill('a', 'b', 'c'); + }); + + it('should handle multiple values from a then', function (done) { + MPromise.fulfilled().then( + function () { + return MPromise.fulfilled().then( + function () { + var p = new MPromise; + p.fulfill('a', 'b', 'c'); + return p; + } + ); + } + ).onFulfill( + function (a, b, c) { + assert.equal('a', a); + assert.equal('b', b); + assert.equal('c', c); + done(); + } + ).end() + }); + + it('should work with `fulfilled` convenience method', function (done) { + MPromise.fulfilled('a', 'b', 'c').then(function (a, b, c) { + assert.equal('a', a); + assert.equal('b', b); + assert.equal('c', c); + done(); + }) + }); + }); + + + describe('end', function () { + it("should return the promise", function (done) { + var p = new MPromise; + var p1 = p.end(); + assert.equal(p, p1); + done(); + }); + + + it("should throw for chain", function (done) { + var p = new MPromise; + 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 MPromise; + 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 MPromise; + p1.chain(new MPromise(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 MPromise; + p1.chain(new MPromise(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 MPromise; + p1.chain(new MPromise(function (err) { + assert.equal(err, e); + done(); + })); + p1.resolve(e); + }); + + + it('should propagate resolution val', function (done) { + var varSentinel = {a: 'a'}; + var p1 = new MPromise; + p1.chain(new MPromise(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 MPromise; + var p2 = p.all(function () { + return [ + (function () { + var p = new MPromise(); + count++; + p.resolve(); + return p; + })() + , (function () { + var p = new MPromise(); + 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 MPromise; + var p2 = p.all(function () { + return [ + (function () { + var p = new MPromise(); + count++; + p.resolve(); + return p; + })() + , (function () { + 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 = MPromise.deferred(); + assert.ok(d.promise instanceof MPromise); + assert.ok(d.reject instanceof Function); + assert.ok(d.resolve 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(); + }; + MPromise.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(); + }; + MPromise.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); + }; + MPromise.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") + }; + MPromise.hook([l1, l2, l1]).end(function (err) { + assert(run, 2); + done(); + }); + }); + }); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js b/5-2/service/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js new file mode 100644 index 0000000..d30bb32 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js @@ -0,0 +1,15 @@ +/** + * Module dependencies. + */ +var Promise = require('../lib/promise'); +var aplus = require('promises-aplus-tests'); + +// tests +describe("run A+ suite", function () { + aplus.mocha({ + fulfilled: Promise.fulfilled, + rejected: Promise.rejected, + deferred: Promise.deferred + }); +}); + diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/.npmignore b/5-2/service/node_modules/mongoose/node_modules/mquery/.npmignore new file mode 100644 index 0000000..5a14ae1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/.npmignore @@ -0,0 +1,3 @@ +*.sw* +node_modules/ +coverage/ diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/.travis.yml b/5-2/service/node_modules/mongoose/node_modules/mquery/.travis.yml new file mode 100644 index 0000000..4dc3a7d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 +services: + - mongodb diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/History.md b/5-2/service/node_modules/mongoose/node_modules/mquery/History.md new file mode 100644 index 0000000..9972664 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/History.md @@ -0,0 +1,230 @@ + +1.6.2 / 2015-07-12 +================== + + * fixed; support exec cb being called synchronously #66 + +1.6.1 / 2015-06-16 +================== + + * fixed; do not treat $meta projection as inclusive [vkarpov15](https://github.com/vkarpov15) + +1.6.0 / 2015-05-27 +================== + + * update dependencies #65 [bachp](https://github.com/bachp) + +1.5.0 / 2015-03-31 +================== + + * fixed; debug output + * fixed; allow hint usage with count #61 [trueinsider](https://github.com/trueinsider) + +1.4.0 / 2015-03-29 +================== + + * added; object support to slice() #60 [vkarpov15](https://github.com/vkarpov15) + * debug; improved output #57 [flyvictor](https://github.com/flyvictor) + +1.3.0 / 2014-11-06 +================== + + * added; setTraceFunction() #53 from [jlai](https://github.com/jlai) + +1.2.1 / 2014-09-26 +================== + + * fixed; distinct assignment in toConstructor() #51 from [esco](https://github.com/esco) + +1.2.0 / 2014-09-18 +================== + + * added; stream() support for find() + +1.1.0 / 2014-09-15 +================== + + * add #then for co / koa support + * start checking code coverage + +1.0.0 / 2014-07-07 +================== + + * Remove broken require() calls until they're actually implemented #48 [vkarpov15](https://github.com/vkarpov15) + +0.9.0 / 2014-05-22 +================== + + * added; thunk() support + * release 0.8.0 + +0.8.0 / 2014-05-15 +================== + + * added; support for maxTimeMS #44 [yoitsro](https://github.com/yoitsro) + * updated; devDependency (driver to 1.4.4) + +0.7.0 / 2014-05-02 +================== + + * fixed; pass $maxDistance in $near object as described in docs #43 [vkarpov15](https://github.com/vkarpov15) + * fixed; cloning buffers #42 [gjohnson](https://github.com/gjohnson) + * tests; a little bit more `mongodb` agnostic #34 [refack](https://github.com/refack) + +0.6.0 / 2014-04-01 +================== + + * fixed; Allow $meta args in sort() so text search sorting works #37 [vkarpov15](https://github.com/vkarpov15) + +0.5.3 / 2014-02-22 +================== + + * fixed; cloning mongodb.Binary + +0.5.2 / 2014-01-30 +================== + + * fixed; cloning ObjectId constructors + * fixed; cloning of ReadPreferences #30 [ashtuchkin](https://github.com/ashtuchkin) + * tests; use specific mongodb version #29 [AvianFlu](https://github.com/AvianFlu) + * tests; remove dependency on ObjectId #28 [refack](https://github.com/refack) + * tests; add failing ReadPref test + +0.5.1 / 2014-01-17 +================== + + * added; deprecation notice to tags parameter #27 [ashtuchkin](https://github.com/ashtuchkin) + * readme; add links + +0.5.0 / 2014-01-16 +================== + + * removed; mongodb driver dependency #26 [ashtuchkin](https://github.com/ashtuchkin) + * removed; first class support of read preference tags #26 (still supported though) [ashtuchkin](https://github.com/ashtuchkin) + * added; better ObjectId clone support + * fixed; cloning objects that have no constructor #21 + * docs; cleaned up [ashtuchkin](https://github.com/ashtuchkin) + +0.4.2 / 2014-01-08 +================== + + * updated; debug module 0.7.4 [refack](https://github.com/refack) + +0.4.1 / 2014-01-07 +================== + + * fixed; inclusive/exclusive logic + +0.4.0 / 2014-01-06 +================== + + * added; selected() + * added; selectedInclusively() + * added; selectedExclusively() + +0.3.3 / 2013-11-14 +================== + + * Fix Mongo DB Dependency #20 [rschmukler](https://github.com/rschmukler) + +0.3.2 / 2013-09-06 +================== + + * added; geometry support for near() + +0.3.1 / 2013-08-22 +================== + + * fixed; update retains key order #19 + +0.3.0 / 2013-08-22 +================== + + * less hardcoded isNode env detection #18 [vshulyak](https://github.com/vshulyak) + * added; validation of findAndModify varients + * clone update doc before execution + * stricter env checks + +0.2.7 / 2013-08-2 +================== + + * Now support GeoJSON point values for Query#near + +0.2.6 / 2013-07-30 +================== + + * internally, 'asc' and 'desc' for sorts are now converted into 1 and -1, respectively + +0.2.5 / 2013-07-30 +================== + + * updated docs + * changed internal representation of `sort` to use objects instead of arrays + +0.2.4 / 2013-07-25 +================== + + * updated; sliced to 0.0.5 + +0.2.3 / 2013-07-09 +================== + + * now using a callback in collection.find instead of directly calling toArray() on the cursor [ebensing](https://github.com/ebensing) + +0.2.2 / 2013-07-09 +================== + + * now exposing mongodb export to allow for better testing [ebensing](https://github.com/ebensing) + +0.2.1 / 2013-07-08 +================== + + * select no longer accepts arrays as parameters [ebensing](https://github.com/ebensing) + +0.2.0 / 2013-07-05 +================== + + * use $geoWithin by default + +0.1.2 / 2013-07-02 +================== + + * added use$geoWithin flag [ebensing](https://github.com/ebensing) + * fix read preferences typo [ebensing](https://github.com/ebensing) + * fix reference to old param name in exists() [ebensing](https://github.com/ebensing) + +0.1.1 / 2013-06-24 +================== + + * fixed; $intersects -> $geoIntersects #14 [ebensing](https://github.com/ebensing) + * fixed; Retain key order when copying objects #15 [ebensing](https://github.com/ebensing) + * bump mongodb dev dep + +0.1.0 / 2013-05-06 +================== + + * findAndModify; return the query + * move mquery.proto.canMerge to mquery.canMerge + * overwrite option now works with non-empty objects + * use strict mode + * validate count options + * validate distinct options + * add aggregate to base collection methods + * clone merge arguments + * clone merged update arguments + * move subclass to mquery.prototype.toConstructor + * fixed; maxScan casing + * use regexp-clone + * added; geometry/intersects support + * support $and + * near: do not use "radius" + * callbacks always fire on next turn of loop + * defined collection interface + * remove time from tests + * clarify goals + * updated docs; + +0.0.1 / 2012-12-15 +================== + + * initial release diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mquery/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/LICENSE @@ -0,0 +1,22 @@ +(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/5-2/service/node_modules/mongoose/node_modules/mquery/Makefile b/5-2/service/node_modules/mongoose/node_modules/mquery/Makefile new file mode 100644 index 0000000..dbb2831 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/Makefile @@ -0,0 +1,22 @@ + +test: + @NODE_ENV=test ./node_modules/.bin/mocha $(T) $(TESTS) + +test-cov: + @NODE_ENV=test node \ + node_modules/.bin/istanbul cover \ + ./node_modules/.bin/_mocha \ + -- -u exports \ + +open-cov: + open coverage/lcov-report/index.html + +test-travis: + @NODE_ENV=test node \ + node_modules/.bin/istanbul cover \ + ./node_modules/.bin/_mocha \ + --report lcovonly \ + -- -u exports \ + --bail + +.PHONY: test test-cov open-cov test-travis diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/README.md b/5-2/service/node_modules/mongoose/node_modules/mquery/README.md new file mode 100644 index 0000000..f7bf7f4 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/README.md @@ -0,0 +1,1220 @@ +#mquery +=========== + +`mquery` is a fluent mongodb query builder designed to run in multiple environments. As of v0.1, `mquery` runs on `Node.js` only with support for the MongoDB shell and browser environments planned for upcoming releases. + +##Features + + - fluent query builder api + - custom base query support + - MongoDB 2.4 geoJSON support + - method + option combinations validation + - node.js driver compatibility + - environment detection + - [debug](https://github.com/visionmedia/debug) support + - separated collection implementations for maximum flexibility + +[![Build Status](https://travis-ci.org/aheckmann/mquery.png)](https://travis-ci.org/aheckmann/mquery) + +##Use + +```js +require('mongodb').connect(uri, function (err, db) { + if (err) return handleError(err); + + // get a collection + var collection = db.collection('artists'); + + // pass it to the constructor + mquery(collection).find({..}, callback); + + // or pass it to the collection method + mquery().find({..}).collection(collection).exec(callback) + + // or better yet, create a custom query constructor that has it always set + var Artist = mquery(collection).toConstructor(); + Artist().find(..).where(..).exec(callback) +}) +``` + +`mquery` requires a collection object to work with. In the example above we just pass the collection object created using the official [MongoDB driver](https://github.com/mongodb/node-mongodb-native). + + +##Fluent API + +- [find](#find) +- [findOne](#findOne) +- [count](#count) +- [remove](#remove) +- [update](#update) +- [findOneAndUpdate](#findoneandupdate) +- [findOneAndRemove](#findoneandremove) +- [distinct](#distinct) +- [exec](#exec) +- [stream](#stream) +- [all](#all) +- [and](#and) +- [box](#box) +- [circle](#circle) +- [elemMatch](#elemmatch) +- [equals](#equals) +- [exists](#exists) +- [geometry](#geometry) +- [gt](#gt) +- [gte](#gte) +- [in](#in) +- [intersects](#intersects) +- [lt](#lt) +- [lte](#lte) +- [maxDistance](#maxdistance) +- [mod](#mod) +- [ne](#ne) +- [nin](#nin) +- [nor](#nor) +- [near](#near) +- [or](#or) +- [polygon](#polygon) +- [regex](#regex) +- [select](#select) +- [selected](#selected) +- [selectedInclusively](#selectedinclusively) +- [selectedExclusively](#selectedexclusively) +- [size](#size) +- [slice](#slice) +- [within](#within) +- [where](#where) +- [$where](#where-1) +- [batchSize](#batchsize) +- [comment](#comment) +- [hint](#hint) +- [limit](#limit) +- [maxScan](#maxscan) +- [maxTime](#maxtime) +- [skip](#skip) +- [sort](#sort) +- [read](#read) +- [slaveOk](#slaveok) +- [snapshot](#snapshot) +- [tailable](#tailable) + +## Helpers + +- [collection](#collection) +- [then](#then) +- [thunk](#thunk) +- [merge](#mergeobject) +- [setOptions](#setoptionsoptions) +- [setTraceFunction](#settracefunctionfunc) +- [mquery.setGlobalTraceFunction](#mquerysetglobaltracefunctionfunc) +- [mquery.canMerge](#mquerycanmerge) +- [mquery.use$geoWithin](#mqueryusegeowithin) + +###find() + +Declares this query a _find_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().find() +mquery().find(match) +mquery().find(callback) +mquery().find(match, function (err, docs) { + assert(Array.isArray(docs)); +}) +``` + +###findOne() + +Declares this query a _findOne_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().findOne() +mquery().findOne(match) +mquery().findOne(callback) +mquery().findOne(match, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) +``` + +###count() + +Declares this query a _count_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().count() +mquery().count(match) +mquery().count(callback) +mquery().count(match, function (err, number){ + console.log('we found %d matching documents', number); +}) +``` + +###remove() + +Declares this query a _remove_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().remove() +mquery().remove(match) +mquery().remove(callback) +mquery().remove(match, function (err){}) +``` + +###update() + +Declares this query an _update_ query. Optionally pass an update document, match clause, options or callback. If a callback is passed, the query is executed. To force execution without passing a callback, run `update(true)`. + +```js +mquery().update() +mquery().update(match, updateDocument) +mquery().update(match, updateDocument, options) + +// the following all execute the command +mquery().update(callback) +mquery().update({$set: updateDocument, callback) +mquery().update(match, updateDocument, callback) +mquery().update(match, updateDocument, options, function (err, result){}) +mquery().update(true) // executes (unsafe write) +``` + +#####the update document + +All paths passed that are not `$atomic` operations will become `$set` ops. For example: + +```js +mquery(collection).where({ _id: id }).update({ title: 'words' }, callback) +``` + +becomes + +```js +collection.update({ _id: id }, { $set: { title: 'words' }}, callback) +``` + +This behavior can be overridden using the `overwrite` option (see below). + +#####options + +Options are passed to the `setOptions()` method. + +- overwrite + +Passing an empty object `{ }` as the update document will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option, the update operation will be ignored and the callback executed without sending the command to MongoDB to prevent accidently overwritting documents in the collection. + +```js +var q = mquery(collection).where({ _id: id }).setOptions({ overwrite: true }); +q.update({ }, callback); // overwrite with an empty doc +``` + +The `overwrite` option isn't just for empty objects, it also provides a means to override the default `$set` conversion and send the update document as is. + +```js +// create a base query +var base = mquery({ _id: 108 }).collection(collection).toConstructor(); + +base().findOne(function (err, doc) { + console.log(doc); // { _id: 108, name: 'cajon' }) + + base().setOptions({ overwrite: true }).update({ changed: true }, function (err) { + base.findOne(function (err, doc) { + console.log(doc); // { _id: 108, changed: true }) - the doc was overwritten + }); + }); +}) +``` + +- multi + +Updates only modify a single document by default. To update multiple documents, set the `multi` option to `true`. + +```js +mquery() + .collection(coll) + .update({ name: /^match/ }, { $addToSet: { arr: 4 }}, { multi: true }, callback) + +// another way of doing it +mquery({ name: /^match/ }) + .collection(coll) + .setOptions({ multi: true }) + .update({ $addToSet: { arr: 4 }}, callback) + +// update multiple documents with an empty doc +var q = mquery(collection).where({ name: /^match/ }); +q.setOptions({ multi: true, overwrite: true }) +q.update({ }); +q.update(function (err, result) { + console.log(arguments); +}); +``` + +###findOneAndUpdate() + +Declares this query a _findAndModify_ with update query. Optionally pass a match clause, update document, options, or callback. If a callback is passed, the query is executed. + +When executed, the first matching document (if found) is modified according to the update document and passed back to the callback. + +#####options + +Options are passed to the `setOptions()` method. + +- `new`: boolean - true to return the modified document rather than the original. defaults to true +- `upsert`: boolean - creates the object if it doesn't exist. defaults to false +- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to update + +```js +query.findOneAndUpdate() +query.findOneAndUpdate(updateDocument) +query.findOneAndUpdate(match, updateDocument) +query.findOneAndUpdate(match, updateDocument, options) + +// the following all execute the command +query.findOneAndUpdate(callback) +query.findOneAndUpdate(updateDocument, callback) +query.findOneAndUpdate(match, updateDocument, callback) +query.findOneAndUpdate(match, updateDocument, options, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) + ``` + +###findOneAndRemove() + +Declares this query a _findAndModify_ with remove query. Optionally pass a match clause, options, or callback. If a callback is passed, the query is executed. + +When executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed to the callback. + +#####options + +Options are passed to the `setOptions()` method. + +- `sort`: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove + +```js +A.where().findOneAndRemove() +A.where().findOneAndRemove(match) +A.where().findOneAndRemove(match, options) + +// the following all execute the command +A.where().findOneAndRemove(callback) +A.where().findOneAndRemove(match, callback) +A.where().findOneAndRemove(match, options, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) + ``` + +###distinct() + +Declares this query a _distinct_ query. Optionally pass the distinct field, a match clause or callback. If a callback is passed the query is executed. + +```js +mquery().distinct() +mquery().distinct(match) +mquery().distinct(match, field) +mquery().distinct(field) + +// the following all execute the command +mquery().distinct(callback) +mquery().distinct(field, callback) +mquery().distinct(match, callback) +mquery().distinct(match, field, function (err, result) { + console.log(result); +}) +``` + +###exec() + +Executes the query. + +```js +mquery().findOne().where('route').intersects(polygon).exec(function (err, docs){}) +``` + +###stream() + +Executes the query and returns a stream. + +```js +var stream = mquery().find().stream(options); +stream.on('data', cb); +stream.on('close', fn); +``` + +Note: this only works with `find()` operations. + +Note: returns the stream object directly from the node-mongodb-native driver. (currently streams1 type stream). Any options will be passed along to the [driver method](http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#stream). + +------------- + +###all() + +Specifies an `$all` query condition + +```js +mquery().where('permission').all(['read', 'write']) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/all/) + +###and() + +Specifies arguments for an `$and` condition + +```js +mquery().and([{ color: 'green' }, { status: 'ok' }]) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/and/) + +###box() + +Specifies a `$box` condition + +```js +var lowerLeft = [40.73083, -73.99756] +var upperRight= [40.741404, -73.988135] + +mquery().where('location').within().box(lowerLeft, upperRight) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/box/) + +###circle() + +Specifies a `$center` or `$centerSphere` condition. + +```js +var area = { center: [50, 50], radius: 10, unique: true } +query.where('loc').within().circle(area) +query.circle('loc', area); + +// for spherical calculations +var area = { center: [50, 50], radius: 10, unique: true, spherical: true } +query.where('loc').within().circle(area) +query.circle('loc', area); +``` + +- [MongoDB Documentation - center](http://docs.mongodb.org/manual/reference/operator/center/) +- [MongoDB Documentation - centerSphere](http://docs.mongodb.org/manual/reference/operator/centerSphere/) + +###elemMatch() + +Specifies an `$elemMatch` condition + +```js +query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + +query.elemMatch('comment', function (elem) { + elem.where('author').equals('autobot'); + elem.where('votes').gte(5); +}) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/elemMatch/) + +###equals() + +Specifies the complementary comparison value for the path specified with `where()`. + +```js +mquery().where('age').equals(49); + +// is the same as + +mquery().where({ 'age': 49 }); +``` + +###exists() + +Specifies an `$exists` condition + +```js +// { name: { $exists: true }} +mquery().where('name').exists() +mquery().where('name').exists(true) +mquery().exists('name') + +// { name: { $exists: false }} +mquery().where('name').exists(false); +mquery().exists('name', false); +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/exists/) + +###geometry() + +Specifies a `$geometry` condition + +```js +var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] +query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + +// or +var polyB = [[ 0, 0 ], [ 1, 1 ]] +query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + +// or +var polyC = [ 0, 0 ] +query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + +// or +query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + +// or +query.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] }) +``` + +`geometry()` **must** come after `intersects()`, `within()`, or `near()`. + +The `object` argument must contain `type` and `coordinates` properties. + +- type `String` +- coordinates `Array` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geometry/) + +###gt() + +Specifies a `$gt` query condition. + +```js +mquery().where('clicks').gt(999) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gt/) + +###gte() + +Specifies a `$gte` query condition. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gte/) + +```js +mquery().where('clicks').gte(1000) +``` + +###in() + +Specifies an `$in` query condition. + +```js +mquery().where('author_id').in([3, 48901, 761]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/in/) + +###intersects() + +Declares an `$geoIntersects` query for `geometry()`. + +```js +query.where('path').intersects().geometry({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}) + +// geometry arguments are supported +query.where('path').intersects({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}) +``` + +**Must** be used after `where()`. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoIntersects/) + +###lt() + +Specifies a `$lt` query condition. + +```js +mquery().where('clicks').lt(50) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lt/) + +###lte() + +Specifies a `$lte` query condition. + +```js +mquery().where('clicks').lte(49) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lte/) + +###maxDistance() + +Specifies a `$maxDistance` query condition. + +```js +mquery().where('location').near({ center: [139, 74.3] }).maxDistance(5) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/maxDistance/) + +###mod() + +Specifies a `$mod` condition + +```js +mquery().where('count').mod(2, 0) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/mod/) + +###ne() + +Specifies a `$ne` query condition. + +```js +mquery().where('status').ne('ok') +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/ne/) + +###nin() + +Specifies an `$nin` query condition. + +```js +mquery().where('author_id').nin([3, 48901, 761]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nin/) + +###nor() + +Specifies arguments for an `$nor` condition. + +```js +mquery().nor([{ color: 'green' }, { status: 'ok' }]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nor/) + +###near() + +Specifies arguments for a `$near` or `$nearSphere` condition. + +These operators return documents sorted by distance. + +####Example + +```js +query.where('loc').near({ center: [10, 10] }); +query.where('loc').near({ center: [10, 10], maxDistance: 5 }); +query.near('loc', { center: [10, 10], maxDistance: 5 }); + +// GeoJSON +query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }}); +query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true }); +query.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] }); + +// For a $nearSphere condition, pass the `spherical` option. +query.near({ center: [10, 10], maxDistance: 5, spherical: true }); +``` + +[MongoDB Documentation](http://www.mongodb.org/display/DOCS/Geospatial+Indexing) + +###or() + +Specifies arguments for an `$or` condition. + +```js +mquery().or([{ color: 'red' }, { status: 'emergency' }]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/or/) + +###polygon() + +Specifies a `$polygon` condition + +```js +mquery().where('loc').within().polygon([10,20], [13, 25], [7,15]) +mquery().polygon('loc', [10,20], [13, 25], [7,15]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/polygon/) + +###regex() + +Specifies a `$regex` query condition. + +```js +mquery().where('name').regex(/^sixstepsrecords/) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/regex/) + +###select() + +Specifies which document fields to include or exclude + +```js +// 1 means include, 0 means exclude +mquery().select({ name: 1, address: 1, _id: 0 }) + +// or + +mquery().select('name address -_id') +``` + +#####String syntax + +When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. + +```js +// include a and b, exclude c +query.select('a b -c'); + +// or you may use object notation, useful when +// you have keys already prefixed with a "-" +query.select({a: 1, b: 1, c: 0}); +``` + +_Cannot be used with `distinct()`._ + +###selected() + +Determines if the query has selected any fields. + +```js +var query = mquery(); +query.selected() // false +query.select('-name'); +query.selected() // true +``` + +###selectedInclusively() + +Determines if the query has selected any fields inclusively. + +```js +var query = mquery().select('name'); +query.selectedInclusively() // true + +var query = mquery(); +query.selected() // false +query.select('-name'); +query.selectedInclusively() // false +query.selectedExclusively() // true +``` + +###selectedExclusively() + +Determines if the query has selected any fields exclusively. + +```js +var query = mquery().select('-name'); +query.selectedExclusively() // true + +var query = mquery(); +query.selected() // false +query.select('name'); +query.selectedExclusively() // false +query.selectedInclusively() // true +``` + +###size() + +Specifies a `$size` query condition. + +```js +mquery().where('someArray').size(6) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/size/) + +###slice() + +Specifies a `$slice` projection for a `path` + +```js +mquery().where('comments').slice(5) +mquery().where('comments').slice(-5) +mquery().where('comments').slice([-10, 5]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/projection/slice/) + +###within() + +Sets a `$geoWithin` or `$within` argument for geo-spatial queries. + +```js +mquery().within().box() +mquery().within().circle() +mquery().within().geometry() + +mquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); +mquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); +mquery().where('loc').within({ polygon: [[],[],[],[]] }); + +mquery().where('loc').within([], [], []) // polygon +mquery().where('loc').within([], []) // box +mquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry +``` + +As of mquery 2.0, `$geoWithin` is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see [mquery.use$geoWithin](#mqueryusegeowithin). + +**Must** be used after `where()`. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoWithin/) + +###where() + +Specifies a `path` for use with chaining + +```js +// instead of writing: +mquery().find({age: {$gte: 21, $lte: 65}}); + +// we can instead write: +mquery().where('age').gte(21).lte(65); + +// passing query conditions is permitted too +mquery().find().where({ name: 'vonderful' }) + +// chaining +mquery() +.where('age').gte(21).lte(65) +.where({ 'name': /^vonderful/i }) +.where('friends').slice(10) +.exec(callback) +``` + +###$where() + +Specifies a `$where` condition. + +Use `$where` when you need to select documents using a JavaScript expression. + +```js +query.$where('this.comments.length > 10 || this.name.length > 5').exec(callback) + +query.$where(function () { + return this.comments.length > 10 || this.name.length > 5; +}) +``` + +Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using. + +----------- + +###batchSize() + +Specifies the batchSize option. + +```js +query.batchSize(100) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.batchSize/) + +###comment() + +Specifies the comment option. + +```js +query.comment('login query'); +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/) + +###hint() + +Sets query hints. + +```js +mquery().hint({ indexA: 1, indexB: -1 }) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/hint/) + +###limit() + +Specifies the limit option. + +```js +query.limit(20) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.limit/) + +###maxScan() + +Specifies the maxScan option. + +```js +query.maxScan(100) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/maxScan/) + +###maxTime() + +Specifies the maxTimeMS option. + +```js +query.maxTime(100) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.maxTimeMS/) + + +###skip() + +Specifies the skip option. + +```js +query.skip(100).limit(20) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.skip/) + +###sort() + +Sets the query sort order. + +If an object is passed, key values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + +If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + +```js +// these are equivalent +query.sort({ field: 'asc', test: -1 }); +query.sort('field -test'); +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.sort/) + +###read() + +Sets the readPreference option for the query. + +```js +mquery().read('primary') +mquery().read('p') // same as primary + +mquery().read('primaryPreferred') +mquery().read('pp') // same as primaryPreferred + +mquery().read('secondary') +mquery().read('s') // same as secondary + +mquery().read('secondaryPreferred') +mquery().read('sp') // same as secondaryPreferred + +mquery().read('nearest') +mquery().read('n') // same as nearest +``` + +#####Preferences: + +- `primary` - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. +- `secondary` - Read from secondary if available, otherwise error. +- `primaryPreferred` - Read from primary if available, otherwise a secondary. +- `secondaryPreferred` - Read from a secondary if available, otherwise read from the primary. +- `nearest` - All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + +Aliases + +- `p` primary +- `pp` primaryPreferred +- `s` secondary +- `sp` secondaryPreferred +- `n` nearest + +#####Preference Tags: + +To keep the separation of concerns between `mquery` and your driver +clean, `mquery#read()` no longer handles specifying a second `tags` argument as of version 0.5. +If you need to specify tags, pass any non-string argument as the first argument. +`mquery` will pass this argument untouched to your collections methods later. +For example: + +```js +// example of specifying tags using the Node.js driver +var ReadPref = require('mongodb').ReadPreference; +var preference = new ReadPref('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); +mquery(..).read(preference).exec(); +``` + +Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + +###slaveOk() + +Sets the slaveOk option. `true` allows reading from secondaries. + +**deprecated** use [read()](#read) preferences instead if on mongodb >= 2.2 + +```js +query.slaveOk() // true +query.slaveOk(true) +query.slaveOk(false) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/) + +###snapshot() + +Specifies this query as a snapshot query. + +```js +mquery().snapshot() // true +mquery().snapshot(true) +mquery().snapshot(false) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/snapshot/) + +###tailable() + +Sets tailable option. + +```js +mquery().tailable() <== true +mquery().tailable(true) +mquery().tailable(false) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/) + +##Helpers + +###collection() + +Sets the querys collection. + +```js +mquery().collection(aCollection) +``` + +###then() + +Executes the query and returns a promise which will be resolved with the query results or rejected if the query responds with an error. + +```js +mquery().find(..).then(success, error); +``` + +This is very useful when combined with [co](https://github.com/visionmedia/co) or [koa](https://github.com/koajs/koa), which automatically resolve promise-like objects for you. + +```js +co(function*(){ + var doc = yield mquery().findOne({ _id: 499 }); + console.log(doc); // { _id: 499, name: 'amazing', .. } +})(); +``` + +_NOTE_: +The returned promise is a [bluebird](https://github.com/petkaantonov/bluebird/) promise but this is customizable. If you want to +use your favorite promise library, simply set `mquery.Promise = YourPromiseConstructor`. +Your `Promise` must be [promises A+](http://promisesaplus.com/) compliant. + +###thunk() + +Returns a thunk which when called runs the query's `exec` method passing the results to the callback. + +```js +var thunk = mquery(collection).find({..}).thunk(); + +thunk(function(err, results) { + +}) +``` + +###merge(object) + +Merges other mquery or match condition objects into this one. When an muery instance is passed, its match conditions, field selection and options are merged. + +```js +var drum = mquery({ type: 'drum' }).collection(instruments); +var redDrum = mqery({ color: 'red' }).merge(drum); +redDrum.count(function (err, n) { + console.log('there are %d red drums', n); +}) +``` + +Internally uses `mquery.canMerge` to determine validity. + +###setOptions(options) + +Sets query options. + +```js +mquery().setOptions({ collection: coll, limit: 20 }) +``` + +#####options + +- [tailable](#tailable) * +- [sort](#sort) * +- [limit](#limit) * +- [skip](#skip) * +- [maxScan](#maxscan) * +- [maxTime](#maxtime) * +- [batchSize](#batchSize) * +- [comment](#comment) * +- [snapshot](#snapshot) * +- [hint](#hint) * +- [slaveOk](#slaveOk) * +- [safe](http://docs.mongodb.org/manual/reference/write-concern/): Boolean - passed through to the collection. Setting to `true` is equivalent to `{ w: 1 }` +- [collection](#collection): the collection to query against + +_* denotes a query helper method is also available_ + +###setTraceFunction(func) + +Set a function to trace this query. Useful for profiling or logging. + +```js +function traceFunction (method, queryInfo, query) { + console.log('starting ' + method + ' query'); + + return function (err, result, millis) { + console.log('finished ' + method + ' query in ' + millis + 'ms'); + }; +} + +mquery().setTraceFunction(traceFunction).findOne({name: 'Joe'}, cb); +``` + +The trace function is passed (method, queryInfo, query) + +- method is the name of the method being called (e.g. findOne) +- queryInfo contains information about the query: + - conditions: query conditions/criteria + - options: options such as sort, fields, etc + - doc: document being updated +- query is the query object + +The trace function should return a callback function which accepts: +- err: error, if any +- result: result, if any +- millis: time spent waiting for query result + +NOTE: stream requests are not traced. + +###mquery.setGlobalTraceFunction(func) + +Similar to `setTraceFunction()` but automatically applied to all queries. + +```js +mquery.setTraceFunction(traceFunction); +``` + +###mquery.canMerge(conditions) + +Determines if `conditions` can be merged using `mquery().merge()`. + +```js +var query = mquery({ type: 'drum' }); +var okToMerge = mquery.canMerge(anObject) +if (okToMerge) { + query.merge(anObject); +} +``` + +##mquery.use$geoWithin + +MongoDB 2.4 introduced the `$geoWithin` operator which replaces and is 100% backward compatible with `$within`. As of mquery 0.2, we default to using `$geoWithin` for all `within()` calls. + +If you are running MongoDB < 2.4 this will be problematic. To force `mquery` to be backward compatible and always use `$within`, set the `mquery.use$geoWithin` flag to `false`. + +```js +mquery.use$geoWithin = false; +``` + +##Custom Base Queries + +Often times we want custom base queries that encapsulate predefined criteria. With `mquery` this is easy. First create the query you want to reuse and call its `toConstructor()` method which returns a new subclass of `mquery` that retains all options and criteria of the original. + +```js +var greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor(); + +// use it! +greatMovies().count(function (err, n) { + console.log('There are %d great movies', n); +}); + +greatMovies().where({ name: /^Life/ }).select('name').find(function (err, docs) { + console.log(docs); +}); +``` + +##Validation + +Method and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a `distinct` query does not support specifying options like `hint` or field selection. In this case an error will be thrown so you can catch these mistakes in development. + +##Debug support + +Debug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable: + + DEBUG=mquery node yourprogram.js + +Read the debug module documentation for more details. + +## General compatibility + +#### ObjectIds + +`mquery` clones query arguments before passing them to a `collection` method for execution. +This prevents accidental side-affects to the objects you pass. +To clone `ObjectIds` we need to make some assumptions. + +First, to check if an object is an `ObjectId`, we check its constructors name. If it matches either +`ObjectId` or `ObjectID` we clone it. + +To clone `ObjectIds`, we call its optional `clone` method. If a `clone` method does not exist, we fall +back to calling `new obj.constructor(obj.id)`. We assume, for compatibility with the +Node.js driver, that the `ObjectId` instance has a public `id` property and that +when creating an `ObjectId` instance we can pass that `id` as an argument. + +#### Read Preferences + +`mquery` supports specifying [Read Preferences]() to control from which MongoDB node your query will read. +The Read Preferences spec also support specifying tags. To pass tags, some +drivers (Node.js driver) require passing a special constructor that handles both the read preference and its tags. +If you need to specify tags, pass an instance of your drivers ReadPreference constructor or roll your own. `mquery` will store whatever you provide and pass later to your collection during execution. + +##Future goals + + - mongo shell compatibility + - browser compatibility + +## Installation + + $ npm install mquery + +## License + +[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE) + diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js new file mode 100644 index 0000000..bce3c38 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * methods a collection must implement + */ + +var methods = [ + 'find' + , 'findOne' + , 'update' + , 'remove' + , 'count' + , 'distinct' + , 'findAndModify' + , 'aggregate' + , 'findStream' +]; + +/** + * Collection base class from which implementations inherit + */ + +function Collection () {} + +for (var i = 0, len = methods.length; i < len; ++i) { + var method = methods[i]; + Collection.prototype[method] = notImplemented(method); +} + +module.exports = exports = Collection; +Collection.methods = methods; + +/** + * creates a function which throws an implementation error + */ + +function notImplemented (method) { + return function () { + throw new Error('collection.' + method + ' not implemented'); + } +} + diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/lib/collection/index.js b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/collection/index.js new file mode 100644 index 0000000..e3cf44d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/collection/index.js @@ -0,0 +1,13 @@ +'use strict'; + +var env = require('../env') + +if ('unknown' == env.type) { + throw new Error('Unknown environment') +} + +module.exports = + env.isNode ? require('./node') : + env.isMongo ? require('./collection') : + require('./collection'); + diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/lib/collection/node.js b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/collection/node.js new file mode 100644 index 0000000..f254456 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/collection/node.js @@ -0,0 +1,100 @@ +'use strict'; + +/** + * Module dependencies + */ + +var Collection = require('./collection'); +var utils = require('../utils'); + +function NodeCollection (col) { + this.collection = col; + this.collectionName = col.collectionName; +} + +/** + * inherit from collection base class + */ + +utils.inherits(NodeCollection, Collection); + +/** + * find(match, options, function(err, docs)) + */ + +NodeCollection.prototype.find = function (match, options, cb) { + this.collection.find(match, options, function (err, cursor) { + if (err) return cb(err); + + cursor.toArray(cb); + }); +} + +/** + * findOne(match, options, function(err, doc)) + */ + +NodeCollection.prototype.findOne = function (match, options, cb) { + this.collection.findOne(match, options, cb); +} + +/** + * count(match, options, function(err, count)) + */ + +NodeCollection.prototype.count = function (match, options, cb) { + this.collection.count(match, options, cb); +} + +/** + * distinct(prop, match, options, function(err, count)) + */ + +NodeCollection.prototype.distinct = function (prop, match, options, cb) { + this.collection.distinct(prop, match, options, cb); +} + +/** + * update(match, update, options, function(err[, result])) + */ + +NodeCollection.prototype.update = function (match, update, options, cb) { + this.collection.update(match, update, options, cb); +} + +/** + * remove(match, options, function(err[, result]) + */ + +NodeCollection.prototype.remove = function (match, options, cb) { + this.collection.remove(match, options, cb); +} + +/** + * findAndModify(match, update, options, function(err, doc)) + */ + +NodeCollection.prototype.findAndModify = function (match, update, options, cb) { + var sort = Array.isArray(options.sort) ? options.sort : []; + this.collection.findAndModify(match, sort, update, options, cb); +} + +/** + * var stream = findStream(match, findOptions, streamOptions) + */ + +NodeCollection.prototype.findStream = function(match, findOptions, streamOptions) { + return this.collection.find(match, findOptions).stream(streamOptions); +} + +/** + * aggregation(operators..., function(err, doc)) + * TODO + */ + +/** + * Expose + */ + +module.exports = exports = NodeCollection; + diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/lib/env.js b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/env.js new file mode 100644 index 0000000..3313b46 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/env.js @@ -0,0 +1,22 @@ +'use strict'; + +exports.isNode = 'undefined' != typeof process + && 'object' == typeof module + && 'object' == typeof global + && 'function' == typeof Buffer + && process.argv + +exports.isMongo = !exports.isNode + && 'function' == typeof printjson + && 'function' == typeof ObjectId + && 'function' == typeof rs + && 'function' == typeof sh; + +exports.isBrowser = !exports.isNode + && !exports.isMongo + && 'undefined' != typeof window; + +exports.type = exports.isNode ? 'node' + : exports.isMongo ? 'mongo' + : exports.isBrowser ? 'browser' + : 'unknown' diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/lib/mquery.js b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/mquery.js new file mode 100644 index 0000000..ca07867 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/mquery.js @@ -0,0 +1,2612 @@ +'use strict'; + +/** + * Dependencies + */ + +var slice = require('sliced') +var assert = require('assert') +var util = require('util') +var utils = require('./utils') +var debug = require('debug')('mquery'); + +/** + * Query constructor used for building queries. + * + * ####Example: + * + * var query = new Query({ name: 'mquery' }); + * query.setOptions({ collection: moduleCollection }) + * query.where('age').gte(21).exec(callback); + * + * @param {Object} [criteria] + * @param {Object} [options] + * @api public + */ + +function Query (criteria, options) { + if (!(this instanceof Query)) + return new Query(criteria, options); + + var proto = this.constructor.prototype; + + this.op = proto.op || undefined; + + this.options = {}; + this.setOptions(proto.options); + + this._conditions = proto._conditions + ? utils.clone(proto._conditions) + : {}; + + this._fields = proto._fields + ? utils.clone(proto._fields) + : undefined; + + this._update = proto._update + ? utils.clone(proto._update) + : undefined; + + this._path = proto._path || undefined; + this._distinct = proto._distinct || undefined; + this._collection = proto._collection || undefined; + this._traceFunction = proto._traceFunction || undefined; + + if (options) { + this.setOptions(options); + } + + if (criteria) { + if (criteria.find && criteria.remove && criteria.update) { + // quack quack! + this.collection(criteria); + } else { + this.find(criteria); + } + } +} + +/** + * This is a parameter that the user can set which determines if mquery + * uses $within or $geoWithin for queries. It defaults to true which + * means $geoWithin will be used. If using MongoDB < 2.4 you should + * set this to false. + * + * @api public + * @property use$geoWithin + */ + +var $withinCmd = '$geoWithin'; +Object.defineProperty(Query, 'use$geoWithin', { + get: function ( ) { return $withinCmd == '$geoWithin' } + , set: function (v) { + if (true === v) { + // mongodb >= 2.4 + $withinCmd = '$geoWithin'; + } else { + $withinCmd = '$within'; + } + } +}); + +/** + * Converts this query to a constructor function with all arguments and options retained. + * + * ####Example + * + * // Create a query that will read documents with a "video" category from + * // `aCollection` on the primary node in the replica-set unless it is down, + * // in which case we'll read from a secondary node. + * var query = mquery({ category: 'video' }) + * query.setOptions({ collection: aCollection, read: 'primaryPreferred' }); + * + * // create a constructor based off these settings + * var Video = query.toConstructor(); + * + * // Video is now a subclass of mquery() and works the same way but with the + * // default query parameters and options set. + * + * // run a query with the previous settings but filter for movies with names + * // that start with "Life". + * Video().where({ name: /^Life/ }).exec(cb); + * + * @return {Query} new Query + * @api public + */ + +Query.prototype.toConstructor = function toConstructor () { + function CustomQuery (criteria, options) { + if (!(this instanceof CustomQuery)) + return new CustomQuery(criteria, options); + Query.call(this, criteria, options); + } + + utils.inherits(CustomQuery, Query); + + // set inherited defaults + var p = CustomQuery.prototype; + + p.options = {}; + p.setOptions(this.options); + + p.op = this.op; + p._conditions = utils.clone(this._conditions); + p._fields = utils.clone(this._fields); + p._update = utils.clone(this._update); + p._path = this._path; + p._distinct = this._distinct; + p._collection = this._collection; + p._traceFunction = this._traceFunction; + + return CustomQuery; +} + +/** + * Sets query options. + * + * ####Options: + * + * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * + * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * + * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * + * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * + * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * + * - [maxTime](http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS) * + * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * + * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * + * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * + * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * + * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * + * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) + * - collection the collection to query against + * + * _* denotes a query helper method is also available_ + * + * @param {Object} options + * @api public + */ + +Query.prototype.setOptions = function (options) { + if (!(options && utils.isObject(options))) + return this; + + // set arbitrary options + var methods = utils.keys(options) + , method + + for (var i = 0; i < methods.length; ++i) { + method = methods[i]; + + // use methods if exist (safer option manipulation) + if ('function' == typeof this[method]) { + var args = utils.isArray(options[method]) + ? options[method] + : [options[method]]; + this[method].apply(this, args) + } else { + this.options[method] = options[method]; + } + } + + return this; +} + +/** + * Sets this Querys collection. + * + * @param {Collection} coll + * @return {Query} this + */ + +Query.prototype.collection = function collection (coll) { + this._collection = new Query.Collection(coll); + + return this; +} + +/** + * Specifies a `$where` condition + * + * Use `$where` when you need to select documents using a JavaScript expression. + * + * ####Example + * + * query.$where('this.comments.length > 10 || this.name.length > 5') + * + * query.$where(function () { + * return this.comments.length > 10 || this.name.length > 5; + * }) + * + * @param {String|Function} js javascript string or function + * @return {Query} this + * @memberOf Query + * @method $where + * @api public + */ + +Query.prototype.$where = function (js) { + this._conditions.$where = js; + return this; +} + +/** + * Specifies a `path` for use with chaining. + * + * ####Example + * + * // instead of writing: + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * // we can instead write: + * User.where('age').gte(21).lte(65); + * + * // passing query conditions is permitted + * User.find().where({ name: 'vonderful' }) + * + * // chaining + * User + * .where('age').gte(21).lte(65) + * .where('name', /^vonderful/i) + * .where('friends').slice(10) + * .exec(callback) + * + * @param {String} [path] + * @param {Object} [val] + * @return {Query} this + * @api public + */ + +Query.prototype.where = function () { + if (!arguments.length) return this; + if (!this.op) this.op = 'find'; + + var type = typeof arguments[0]; + + if ('string' == type) { + this._path = arguments[0]; + + if (2 === arguments.length) { + this._conditions[this._path] = arguments[1]; + } + + return this; + } + + if ('object' == type && !Array.isArray(arguments[0])) { + return this.merge(arguments[0]); + } + + throw new TypeError('path must be a string or object'); +} + +/** + * Specifies the complementary comparison value for paths specified with `where()` + * + * ####Example + * + * User.where('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @param {Object} val + * @return {Query} this + * @api public + */ + +Query.prototype.equals = function equals (val) { + this._ensurePath('equals'); + var path = this._path; + this._conditions[path] = val; + return this; +} + +/** + * Specifies arguments for an `$or` condition. + * + * ####Example + * + * query.or([{ color: 'red' }, { status: 'emergency' }]) + * + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.or = function or (array) { + var or = this._conditions.$or || (this._conditions.$or = []); + if (!utils.isArray(array)) array = [array]; + or.push.apply(or, array); + return this; +} + +/** + * Specifies arguments for a `$nor` condition. + * + * ####Example + * + * query.nor([{ color: 'green' }, { status: 'ok' }]) + * + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.nor = function nor (array) { + var nor = this._conditions.$nor || (this._conditions.$nor = []); + if (!utils.isArray(array)) array = [array]; + nor.push.apply(nor, array); + return this; +} + +/** + * Specifies arguments for a `$and` condition. + * + * ####Example + * + * query.and([{ color: 'green' }, { status: 'ok' }]) + * + * @see $and http://docs.mongodb.org/manual/reference/operator/and/ + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.and = function and (array) { + var and = this._conditions.$and || (this._conditions.$and = []); + if (!Array.isArray(array)) array = [array]; + and.push.apply(and, array); + return this; +} + +/** + * Specifies a $gt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * Thing.find().where('age').gt(21) + * + * // or + * Thing.find().gt('age', 21) + * + * @method gt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $gte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method gte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $lt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $lte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $ne query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method ne + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $in query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method in + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $nin query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method nin + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $all query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method all + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $size query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method size + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $regex query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method regex + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $maxDistance query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method maxDistance + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/*! + * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance + * + * Thing.where('type').nin(array) + */ + +'gt gte lt lte ne in nin all regex size maxDistance'.split(' ').forEach(function ($conditional) { + Query.prototype[$conditional] = function () { + var path, val; + + if (1 === arguments.length) { + this._ensurePath($conditional); + val = arguments[0]; + path = this._path; + } else { + val = arguments[1]; + path = arguments[0]; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds['$' + $conditional] = val; + return this; + }; +}) + +/** + * Specifies a `$mod` condition + * + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @api public + */ + +Query.prototype.mod = function () { + var val, path; + + if (1 === arguments.length) { + this._ensurePath('mod') + val = arguments[0]; + path = this._path; + } else if (2 === arguments.length && !utils.isArray(arguments[1])) { + this._ensurePath('mod') + val = slice(arguments); + path = this._path; + } else if (3 === arguments.length) { + val = slice(arguments, 1); + path = arguments[0]; + } else { + val = arguments[1]; + path = arguments[0]; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$mod = val; + return this; +} + +/** + * Specifies an `$exists` condition + * + * ####Example + * + * // { name: { $exists: true }} + * Thing.where('name').exists() + * Thing.where('name').exists(true) + * Thing.find().exists('name') + * + * // { name: { $exists: false }} + * Thing.where('name').exists(false); + * Thing.find().exists('name', false); + * + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @api public + */ + +Query.prototype.exists = function () { + var path, val; + + if (0 === arguments.length) { + this._ensurePath('exists'); + path = this._path; + val = true; + } else if (1 === arguments.length) { + if ('boolean' === typeof arguments[0]) { + this._ensurePath('exists'); + path = this._path; + val = arguments[0]; + } else { + path = arguments[0]; + val = true; + } + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$exists = val; + return this; +} + +/** + * Specifies an `$elemMatch` condition + * + * ####Example + * + * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) + * + * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + * + * query.elemMatch('comment', function (elem) { + * elem.where('author').equals('autobot'); + * elem.where('votes').gte(5); + * }) + * + * query.where('comment').elemMatch(function (elem) { + * elem.where({ author: 'autobot' }); + * elem.where('votes').gte(5); + * }) + * + * @param {String|Object|Function} path + * @param {Object|Function} criteria + * @return {Query} this + * @api public + */ + +Query.prototype.elemMatch = function () { + if (null == arguments[0]) + throw new TypeError("Invalid argument"); + + var fn, path, criteria; + + if ('function' === typeof arguments[0]) { + this._ensurePath('elemMatch'); + path = this._path; + fn = arguments[0]; + } else if (utils.isObject(arguments[0])) { + this._ensurePath('elemMatch'); + path = this._path; + criteria = arguments[0]; + } else if ('function' === typeof arguments[1]) { + path = arguments[0]; + fn = arguments[1]; + } else if (arguments[1] && utils.isObject(arguments[1])) { + path = arguments[0]; + criteria = arguments[1]; + } else { + throw new TypeError("Invalid argument"); + } + + if (fn) { + criteria = new Query; + fn(criteria); + criteria = criteria._conditions; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$elemMatch = criteria; + return this; +} + +// Spatial queries + +/** + * Sugar for geo-spatial queries. + * + * ####Example + * + * query.within().box() + * query.within().circle() + * query.within().geometry() + * + * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); + * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); + * query.where('loc').within({ polygon: [[],[],[],[]] }); + * + * query.where('loc').within([], [], []) // polygon + * query.where('loc').within([], []) // box + * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry + * + * ####NOTE: + * + * Must be used after `where()`. + * + * @memberOf Query + * @return {Query} this + * @api public + */ + +Query.prototype.within = function within () { + // opinionated, must be used after where + this._ensurePath('within'); + this._geoComparison = $withinCmd; + + if (0 === arguments.length) { + return this; + } + + if (2 === arguments.length) { + return this.box.apply(this, arguments); + } else if (2 < arguments.length) { + return this.polygon.apply(this, arguments); + } + + var area = arguments[0]; + + if (!area) + throw new TypeError('Invalid argument'); + + if (area.center) + return this.circle(area); + + if (area.box) + return this.box.apply(this, area.box); + + if (area.polygon) + return this.polygon.apply(this, area.polygon); + + if (area.type && area.coordinates) + return this.geometry(area); + + throw new TypeError('Invalid argument'); +} + +/** + * Specifies a $box condition + * + * ####Example + * + * var lowerLeft = [40.73083, -73.99756] + * var upperRight= [40.741404, -73.988135] + * + * query.where('loc').within().box(lowerLeft, upperRight) + * query.box('loc', lowerLeft, upperRight ) + * + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see Query#within #query_Query-within + * @param {String} path + * @param {Object} val + * @return {Query} this + * @api public + */ + +Query.prototype.box = function () { + var path, box; + + if (3 === arguments.length) { + // box('loc', [], []) + path = arguments[0]; + box = [arguments[1], arguments[2]]; + } else if (2 === arguments.length) { + // box([], []) + this._ensurePath('box'); + path = this._path; + box = [arguments[0], arguments[1]]; + } else { + throw new TypeError("Invalid argument"); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison || $withinCmd] = { '$box': box }; + return this; +} + +/** + * Specifies a $polygon condition + * + * ####Example + * + * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) + * query.polygon('loc', [10,20], [13, 25], [7,15]) + * + * @param {String|Array} [path] + * @param {Array|Object} [val] + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.polygon = function () { + var val, path; + + if ('string' == typeof arguments[0]) { + // polygon('loc', [],[],[]) + path = arguments[0]; + val = slice(arguments, 1); + } else { + // polygon([],[],[]) + this._ensurePath('polygon'); + path = this._path; + val = slice(arguments); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison || $withinCmd] = { '$polygon': val }; + return this; +} + +/** + * Specifies a $center or $centerSphere condition. + * + * ####Example + * + * var area = { center: [50, 50], radius: 10, unique: true } + * query.where('loc').within().circle(area) + * query.center('loc', area); + * + * // for spherical calculations + * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } + * query.where('loc').within().circle(area) + * query.center('loc', area); + * + * @param {String} [path] + * @param {Object} area + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.circle = function () { + var path, val; + + if (1 === arguments.length) { + this._ensurePath('circle'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } else { + throw new TypeError("Invalid argument"); + } + + if (!('radius' in val && val.center)) + throw new Error('center and radius are required'); + + var conds = this._conditions[path] || (this._conditions[path] = {}); + + var type = val.spherical + ? '$centerSphere' + : '$center'; + + var wKey = this._geoComparison || $withinCmd; + conds[wKey] = {}; + conds[wKey][type] = [val.center, val.radius]; + + if ('unique' in val) + conds[wKey].$uniqueDocs = !! val.unique; + + return this; +} + +/** + * Specifies a `$near` or `$nearSphere` condition + * + * These operators return documents sorted by distance. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10] }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); + * query.near('loc', { center: [10, 10], maxDistance: 5 }); + * query.near({ center: { type: 'Point', coordinates: [..] }}) + * query.near().geometry({ type: 'Point', coordinates: [..] }) + * + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.near = function near () { + var path, val; + + this._geoComparison = '$near'; + + if (0 === arguments.length) { + return this; + } else if (1 === arguments.length) { + this._ensurePath('near'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } else { + throw new TypeError("Invalid argument"); + } + + if (!val.center) { + throw new Error('center is required'); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + + var type = val.spherical + ? '$nearSphere' + : '$near'; + + // center could be a GeoJSON object or an Array + if (Array.isArray(val.center)) { + conds[type] = val.center; + + var radius = 'maxDistance' in val + ? val.maxDistance + : null; + + if (null != radius) { + conds.$maxDistance = radius; + } + } else { + // GeoJSON? + if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) { + throw new Error(util.format("Invalid GeoJSON specified for %s", type)); + } + conds[type] = { $geometry : val.center }; + + // MongoDB 2.6 insists on maxDistance being in $near / $nearSphere + if ('maxDistance' in val) { + conds[type]['$maxDistance'] = val.maxDistance; + } + } + + return this; +} + +/** + * Declares an intersects query for `geometry()`. + * + * ####Example + * + * query.where('path').intersects().geometry({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * query.where('path').intersects({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * @param {Object} [arg] + * @return {Query} this + * @api public + */ + +Query.prototype.intersects = function intersects () { + // opinionated, must be used after where + this._ensurePath('intersects'); + + this._geoComparison = '$geoIntersects'; + + if (0 === arguments.length) { + return this; + } + + var area = arguments[0]; + + if (null != area && area.type && area.coordinates) + return this.geometry(area); + + throw new TypeError('Invalid argument'); +} + +/** + * Specifies a `$geometry` condition + * + * ####Example + * + * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] + * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + * + * // or + * var polyB = [[ 0, 0 ], [ 1, 1 ]] + * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + * + * // or + * var polyC = [ 0, 0 ] + * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + * + * // or + * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + * + * ####NOTE: + * + * `geometry()` **must** come after either `intersects()` or `within()`. + * + * The `object` argument must contain `type` and `coordinates` properties. + * - type {String} + * - coordinates {Array} + * + * The most recent path passed to `where()` is used. + * + * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. + * @return {Query} this + * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @api public + */ + +Query.prototype.geometry = function geometry () { + if (!('$within' == this._geoComparison || + '$geoWithin' == this._geoComparison || + '$near' == this._geoComparison || + '$geoIntersects' == this._geoComparison)) { + throw new Error('geometry() must come after `within()`, `intersects()`, or `near()'); + } + + var val, path; + + if (1 === arguments.length) { + this._ensurePath('geometry'); + path = this._path; + val = arguments[0]; + } else { + throw new TypeError("Invalid argument"); + } + + if (!(val.type && Array.isArray(val.coordinates))) { + throw new TypeError('Invalid argument'); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison] = { $geometry: val }; + + return this; +} + +// end spatial + +/** + * Specifies which document fields to include or exclude + * + * ####String syntax + * + * When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. + * + * ####Example + * + * // include a and b, exclude c + * query.select('a b -c'); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * query.select({a: 1, b: 1, c: 0}); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @see SchemaType + * @api public + */ + +Query.prototype.select = function select () { + var arg = arguments[0]; + if (!arg) return this; + + if (arguments.length !== 1) { + throw new Error("Invalid select: select only takes 1 argument"); + } + + this._validate('select'); + + var fields = this._fields || (this._fields = {}); + var type = typeof arg; + + if ('string' == type || 'object' == type && 'number' == typeof arg.length && !Array.isArray(arg)) { + if ('string' == type) + arg = arg.split(/\s+/); + + for (var i = 0, len = arg.length; i < len; ++i) { + var field = arg[i]; + if (!field) continue; + var include = '-' == field[0] ? 0 : 1; + if (include === 0) field = field.substring(1); + fields[field] = include; + } + + return this; + } + + if (utils.isObject(arg) && !Array.isArray(arg)) { + var keys = utils.keys(arg); + for (var i = 0; i < keys.length; ++i) { + fields[keys[i]] = arg[keys[i]]; + } + return this; + } + + throw new TypeError('Invalid select() argument. Must be string or object.'); +} + +/** + * Specifies a $slice condition for a `path` + * + * ####Example + * + * query.slice('comments', 5) + * query.slice('comments', -5) + * query.slice('comments', [10, 5]) + * query.where('comments').slice(5) + * query.where('comments').slice([-10, 5]) + * + * @param {String} [path] + * @param {Number} val number/range of elements to slice + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements + * @api public + */ + +Query.prototype.slice = function () { + if (0 === arguments.length) + return this; + + this._validate('slice'); + + var path, val; + + if (1 === arguments.length) { + var arg = arguments[0]; + if (typeof arg === 'object' && !Array.isArray(arg)) { + var keys = Object.keys(arg); + var numKeys = keys.length; + for (var i = 0; i < numKeys; ++i) { + this.slice(keys[i], arg[keys[i]]); + } + return this; + } + this._ensurePath('slice'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + if ('number' === typeof arguments[0]) { + this._ensurePath('slice'); + path = this._path; + val = slice(arguments); + } else { + path = arguments[0]; + val = arguments[1]; + } + } else if (3 === arguments.length) { + path = arguments[0]; + val = slice(arguments, 1); + } + + var myFields = this._fields || (this._fields = {}); + myFields[path] = { '$slice': val }; + return this; +} + +/** + * Sets the sort order + * + * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1. + * + * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + * + * ####Example + * + * // these are equivalent + * query.sort({ field: 'asc', test: -1 }); + * query.sort('field -test'); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @api public + */ + +Query.prototype.sort = function (arg) { + if (!arg) return this; + + this._validate('sort'); + + var type = typeof arg; + + if (1 === arguments.length && 'string' == type) { + arg = arg.split(/\s+/); + + for (var i = 0, len = arg.length; i < len; ++i) { + var field = arg[i]; + if (!field) continue; + var ascend = '-' == field[0] ? -1 : 1; + if (ascend === -1) field = field.substring(1); + push(this.options, field, ascend); + } + + return this; + } + + if (utils.isObject(arg)) { + var keys = utils.keys(arg); + for (var i = 0; i < keys.length; ++i) { + var field = keys[i]; + push(this.options, field, arg[field]); + } + + return this; + } + + throw new TypeError('Invalid sort() argument. Must be a string or object.'); +} + +/*! + * @ignore + */ + +function push (opts, field, value) { + if (value && value.$meta) { + var s = opts.sort || (opts.sort = {}); + s[field] = { $meta : value.$meta }; + return; + } + + var val = String(value || 1).toLowerCase(); + if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) { + if (utils.isArray(value)) value = '['+value+']'; + throw new TypeError('Invalid sort value: {' + field + ': ' + value + ' }'); + } + // store `sort` in a sane format + var s = opts.sort || (opts.sort = {}); + var valueStr = value.toString() + .replace("asc", "1") + .replace("ascending", "1") + .replace("desc", "-1") + .replace("descending", "-1"); + s[field] = parseInt(valueStr, 10); +} + +/** + * Specifies the limit option. + * + * ####Example + * + * query.limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method limit + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D + * @api public + */ +/** + * Specifies the skip option. + * + * ####Example + * + * query.skip(100).limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method skip + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D + * @api public + */ +/** + * Specifies the maxScan option. + * + * ####Example + * + * query.maxScan(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method maxScan + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan + * @api public + */ +/** + * Specifies the batchSize option. + * + * ####Example + * + * query.batchSize(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method batchSize + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D + * @api public + */ +/** + * Specifies the `comment` option. + * + * ####Example + * + * query.comment('login query') + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method comment + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment + * @api public + */ + +/*! + * limit, skip, maxScan, batchSize, comment + * + * Sets these associated options. + * + * query.comment('feed query'); + */ + +;['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function (method) { + Query.prototype[method] = function (v) { + this._validate(method); + this.options[method] = v; + return this; + }; +}) + +/** + * Specifies the maxTimeMS option. + * + * ####Example + * + * query.maxTime(100) + * + * @method maxTime + * @memberOf Query + * @param {Number} val + * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS + * @api public + */ + +Query.prototype.maxTime = function (v) { + this._validate('maxTime'); + this.options.maxTimeMS = v; + return this; +}; + +/** + * Specifies this query as a `snapshot` query. + * + * ####Example + * + * mquery().snapshot() // true + * mquery().snapshot(true) + * mquery().snapshot(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D + * @return {Query} this + * @api public + */ + +Query.prototype.snapshot = function () { + this._validate('snapshot'); + + this.options.snapshot = arguments.length + ? !! arguments[0] + : true + + return this; +} + +/** + * Sets query hints. + * + * ####Example + * + * query.hint({ indexA: 1, indexB: -1}) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object} val a hint object + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint + * @api public + */ + +Query.prototype.hint = function () { + if (0 === arguments.length) return this; + + this._validate('hint'); + + var arg = arguments[0]; + if (utils.isObject(arg)) { + var hint = this.options.hint || (this.options.hint = {}); + + // must keep object keys in order so don't use Object.keys() + for (var k in arg) { + hint[k] = arg[k]; + } + + return this; + } + + throw new TypeError('Invalid hint. ' + arg); +} + +/** + * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences. + * + * ####Example: + * + * query.slaveOk() // true + * query.slaveOk(true) + * query.slaveOk(false) + * + * @deprecated use read() preferences instead if on mongodb >= 2.2 + * @param {Boolean} v defaults to true + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see read() + * @return {Query} this + * @api public + */ + +Query.prototype.slaveOk = function (v) { + this.options.slaveOk = arguments.length ? !!v : true; + return this; +} + +/** + * Sets the readPreference option for the query. + * + * ####Example: + * + * new Query().read('primary') + * new Query().read('p') // same as primary + * + * new Query().read('primaryPreferred') + * new Query().read('pp') // same as primaryPreferred + * + * new Query().read('secondary') + * new Query().read('s') // same as secondary + * + * new Query().read('secondaryPreferred') + * new Query().read('sp') // same as secondaryPreferred + * + * new Query().read('nearest') + * new Query().read('n') // same as nearest + * + * // you can also use mongodb.ReadPreference class to also specify tags + * new Query().read(mongodb.ReadPreference('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])) + * + * ####Preferences: + * + * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. + * secondary Read from secondary if available, otherwise error. + * primaryPreferred Read from primary if available, otherwise a secondary. + * secondaryPreferred Read from a secondary if available, otherwise read from the primary. + * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + * + * Aliases + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + * + * @param {String|ReadPreference} pref one of the listed preference options or their aliases + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + * @return {Query} this + * @api public + */ + +Query.prototype.read = function (pref) { + if (arguments.length > 1 && !Query.prototype.read.deprecationWarningIssued) { + console.error("Deprecation warning: 'tags' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead."); + Query.prototype.read.deprecationWarningIssued = true; + } + this.options.readPreference = utils.readPref(pref); + return this; +} + +/** + * Sets tailable option. + * + * ####Example + * + * query.tailable() <== true + * query.tailable(true) + * query.tailable(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Boolean} v defaults to true + * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors + * @api public + */ + +Query.prototype.tailable = function () { + this._validate('tailable'); + + this.options.tailable = arguments.length + ? !! arguments[0] + : true; + + return this; +} + +/** + * Merges another Query or conditions object into this one. + * + * When a Query is passed, conditions, field selection and options are merged. + * + * @param {Query|Object} source + * @return {Query} this + */ + +Query.prototype.merge = function (source) { + if (!source) + return this; + + if (!Query.canMerge(source)) + throw new TypeError('Invalid argument. Expected instanceof mquery or plain object'); + + if (source instanceof Query) { + // if source has a feature, apply it to ourselves + + if (source._conditions) { + utils.merge(this._conditions, source._conditions); + } + + if (source._fields) { + this._fields || (this._fields = {}); + utils.merge(this._fields, source._fields); + } + + if (source.options) { + this.options || (this.options = {}); + utils.merge(this.options, source.options); + } + + if (source._update) { + this._update || (this._update = {}); + utils.mergeClone(this._update, source._update); + } + + if (source._distinct) { + this._distinct = source._distinct; + } + + return this; + } + + // plain object + utils.merge(this._conditions, source); + + return this; +} + +/** + * Finds documents. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.find() + * query.find(callback) + * query.find({ name: 'Burning Lights' }, callback) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.find = function (criteria, callback) { + this.op = 'find'; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + var self = this + , conds = this._conditions + , options = this._optionsForExec() + + options.fields = this._fieldsForExec() + + debug('find', this._collection.collectionName, conds, options); + callback = this._wrapCallback('find', callback, { + conditions: conds + , options: options + }); + + this._collection.find(conds, options, utils.tick(callback)); + return this; +} + +/** + * Executes the query as a findOne() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.findOne().where('name', /^Burning/); + * + * query.findOne({ name: /^Burning/ }) + * + * query.findOne({ name: /^Burning/ }, callback); // executes + * + * query.findOne(function (err, doc) { + * if (err) return handleError(err); + * if (doc) { + * // doc may be null if no document matched + * + * } + * }); + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.findOne = function (criteria, callback) { + this.op = 'findOne'; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + var self = this + , conds = this._conditions + , options = this._optionsForExec() + + options.fields = this._fieldsForExec(); + + debug('findOne', this._collection.collectionName, conds, options); + callback = this._wrapCallback('findOne', callback, { + conditions: conds + , options: options + }); + + this._collection.findOne(conds, options, utils.tick(callback)); + + return this; +} + +/** + * Exectues the query as a count() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.count().where('color', 'black').exec(callback); + * + * query.count({ color: 'black' }).count(callback) + * + * query.count({ color: 'black' }, callback) + * + * query.where('color', 'black').count(function (err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count + * @api public + */ + +Query.prototype.count = function (criteria, callback) { + this.op = 'count'; + this._validate(); + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + var conds = this._conditions + , options = this._optionsForExec() + + debug('count', this._collection.collectionName, conds, options); + callback = this._wrapCallback('count', callback, { + conditions: conds + , options: options + }); + + this._collection.count(conds, options, utils.tick(callback)); + return this; +} + +/** + * Declares or executes a distinct() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * distinct(criteria, field, fn) + * distinct(criteria, field) + * distinct(field, fn) + * distinct(field) + * distinct(fn) + * distinct() + * + * @param {Object|Query} [criteria] + * @param {String} [field] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct + * @api public + */ + +Query.prototype.distinct = function (criteria, field, callback) { + this.op = 'distinct'; + this._validate(); + + if (!callback) { + switch (typeof field) { + case 'function': + callback = field; + if ('string' == typeof criteria) { + field = criteria; + criteria = undefined; + } + break; + case 'undefined': + case 'string': + break; + default: + throw new TypeError('Invalid `field` argument. Must be string or function') + break; + } + + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = field = undefined; + break; + case 'string': + field = criteria; + criteria = undefined; + break; + } + } + + if ('string' == typeof field) { + this._distinct = field; + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) { + return this; + } + + if (!this._distinct) { + throw new Error('No value for `distinct` has been declared'); + } + + var conds = this._conditions + , options = this._optionsForExec() + + debug('distinct', this._collection.collectionName, conds, options); + callback = this._wrapCallback('distinct', callback, { + conditions: conds + , options: options + }); + + this._collection.distinct(this._distinct, conds, options, utils.tick(callback)); + + return this; +} + +/** + * Declare and/or execute this query as an update() operation. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * mquery({ _id: id }).update({ title: 'words' }, ...) + * + * becomes + * + * collection.update({ _id: id }, { $set: { title: 'words' }}, ...) + * + * ####Note + * + * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. + * + * var q = mquery(collection).where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).update(); // not executed + * + * var q = mquery(collection).where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe + * + * // keys that are not $atomic ops become $set. + * // this executes the same command as the previous example. + * q.update({ name: 'bob' }).where({ _id: id }).exec(); + * + * var q = mquery(collection).update(); // not executed + * + * // overwriting with empty docs + * var q.where({ _id: id }).setOptions({ overwrite: true }) + * q.update({ }, callback); // executes + * + * // multi update with overwrite to empty doc + * var q = mquery(collection).where({ _id: id }); + * q.setOptions({ multi: true, overwrite: true }) + * q.update({ }); + * q.update(callback); // executed + * + * // multi updates + * mquery() + * .collection(coll) + * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) + * // more multi updates + * mquery({ }) + * .collection(coll) + * .setOptions({ multi: true }) + * .update({ $set: { arr: [] }}, callback) + * + * // single update by default + * mquery({ email: 'address@example.com' }) + * .collection(coll) + * .update({ $inc: { counter: 1 }}, callback) + * + * // summary + * update(criteria, doc, opts, cb) // executes + * update(criteria, doc, opts) + * update(criteria, doc, cb) // executes + * update(criteria, doc) + * update(doc, cb) // executes + * update(doc) + * update(cb) // executes + * update(true) // executes (unsafe write) + * update() + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.update = function update (criteria, doc, options, callback) { + this.op = 'update'; + var force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; + } + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (doc) { + this._mergeUpdate(doc); + } + + if (utils.isObject(options)) { + // { overwrite: true } + this.setOptions(options); + } + + // we are done if we don't have callback and they are + // not forcing an unsafe write. + if (!(force || callback)) + return this; + + if (!this._update || + !this.options.overwrite && 0 === utils.keys(this._update).length) { + callback && utils.soon(callback.bind(null, null, 0)); + return this; + } + + options = this._optionsForExec(); + if (!callback) options.safe = false; + + var criteria = this._conditions; + doc = this._updateForExec(); + + debug('update', this._collection.collectionName, criteria, doc, options); + callback = this._wrapCallback('update', callback, { + conditions: criteria + , doc: doc + , options: options + }); + + this._collection.update(criteria, doc, options, utils.tick(callback)); + + return this; +} + +/** + * Declare and/or execute this query as a remove() operation. + * + * ####Example + * + * mquery(collection).remove({ artist: 'Anne Murray' }, callback) + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. + * + * // not executed + * var query = mquery(collection).remove({ name: 'Anne Murray' }) + * + * // executed + * mquery(collection).remove({ name: 'Anne Murray' }, callback) + * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback) + * + * // executed without a callback (unsafe write) + * query.exec() + * + * // summary + * query.remove(conds, fn); // executes + * query.remove(conds) + * query.remove(fn) // executes + * query.remove() + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.remove = function (criteria, callback) { + this.op = 'remove'; + var force; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } else if (true === criteria) { + force = criteria; + criteria = undefined; + } + + if (!(force || callback)) + return this; + + var options = this._optionsForExec() + if (!callback) options.safe = false; + + var conds = this._conditions; + + debug('remove', this._collection.collectionName, conds, options); + callback = this._wrapCallback('remove', callback, { + conditions: conds + , options: options + }); + + this._collection.remove(conds, options, utils.tick(callback)); + + return this; +} + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. + * + * ####Available options + * + * - `new`: bool - true to return the modified document rather than the original. defaults to true + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * + * ####Examples + * + * query.findOneAndUpdate(conditions, update, options, callback) // executes + * query.findOneAndUpdate(conditions, update, options) // returns Query + * query.findOneAndUpdate(conditions, update, callback) // executes + * query.findOneAndUpdate(conditions, update) // returns Query + * query.findOneAndUpdate(update, callback) // returns Query + * query.findOneAndUpdate(update) // returns Query + * query.findOneAndUpdate(callback) // executes + * query.findOneAndUpdate() // returns Query + * + * @param {Object|Query} [query] + * @param {Object} [doc] + * @param {Object} [options] + * @param {Function} [callback] + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @return {Query} this + * @api public + */ + +Query.prototype.findOneAndUpdate = function (criteria, doc, options, callback) { + this.op = 'findOneAndUpdate'; + this._validate(); + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = {}; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + options = undefined; + break; + case 1: + if ('function' == typeof criteria) { + callback = criteria; + criteria = options = doc = undefined; + } else { + doc = criteria; + criteria = options = undefined; + } + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + // apply doc + if (doc) { + this._mergeUpdate(doc); + } + + options && this.setOptions(options); + + if (!callback) return this; + return this._findAndModify('update', callback); +} + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * + * ####Examples + * + * A.where().findOneAndRemove(conditions, options, callback) // executes + * A.where().findOneAndRemove(conditions, options) // return Query + * A.where().findOneAndRemove(conditions, callback) // executes + * A.where().findOneAndRemove(conditions) // returns Query + * A.where().findOneAndRemove(callback) // executes + * A.where().findOneAndRemove() // returns Query + * + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Query.prototype.findOneAndRemove = function (conditions, options, callback) { + this.op = 'findOneAndRemove'; + this._validate(); + + if ('function' == typeof options) { + callback = options; + options = undefined; + } else if ('function' == typeof conditions) { + callback = conditions; + conditions = undefined; + } + + // apply conditions + if (Query.canMerge(conditions)) { + this.merge(conditions); + } + + // apply options + options && this.setOptions(options); + + if (!callback) return this; + + return this._findAndModify('remove', callback); +} + +/** + * _findAndModify + * + * @param {String} type - either "remove" or "update" + * @param {Function} callback + * @api private + */ + +Query.prototype._findAndModify = function (type, callback) { + assert.equal('function', typeof callback); + + var opts = this._optionsForExec() + , self = this + , fields + , sort + , doc + + if ('remove' == type) { + opts.remove = true; + } else { + if (!('new' in opts)) opts.new = true; + if (!('upsert' in opts)) opts.upsert = false; + + doc = this._updateForExec() + if (!doc) { + if (opts.upsert) { + // still need to do the upsert to empty doc + doc = { $set: {} }; + } else { + return this.findOne(callback); + } + } + } + + var fields = this._fieldsForExec(); + if (fields) { + opts.fields = fields; + } + + var conds = this._conditions; + + debug('findAndModify', this._collection.collectionName, conds, doc, opts); + callback = this._wrapCallback('findAndModify', callback, { + conditions: conds + , doc: doc + , options: opts + }); + + this._collection + .findAndModify(conds, doc, opts, utils.tick(callback)); + + return this; +} + +/** + * Wrap callback to add tracing + * + * @param {Function} callback + * @param {Object} [queryInfo] + * @api private + */ +Query.prototype._wrapCallback = function (method, callback, queryInfo) { + var traceFunction = this._traceFunction || Query.traceFunction; + + if (traceFunction) { + queryInfo.collectionName = this._collection.collectionName; + + var traceCallback = traceFunction && + traceFunction.call(null, method, queryInfo, this); + + var startTime = new Date().getTime(); + + return function wrapperCallback (err, result) { + if (traceCallback) { + var millis = new Date().getTime() - startTime; + traceCallback.call(null, err, result, millis); + } + + if (callback) { + callback.apply(null, arguments); + } + }; + } + + return callback; +} + +/** + * Add trace function that gets called when the query is executed. + * The function will be called with (method, queryInfo, query) and + * should return a callback function which will be called + * with (err, result, millis) when the query is complete. + * + * queryInfo is an object containing: { + * collectionName: , + * conditions: , + * options: , + * doc: [document to update, if applicable] + * } + * + * NOTE: Does not trace stream queries. + * + * @param {Function} traceFunction + * @return {Query} this + * @api public + */ +Query.prototype.setTraceFunction = function (traceFunction) { + this._traceFunction = traceFunction; + return this; +} + +/** + * Executes the query + * + * ####Examples + * + * query.exec(); + * query.exec(callback); + * query.exec('update'); + * query.exec('find', callback); + * + * @param {String|Function} [operation] + * @param {Function} [callback] + * @api public + */ + +Query.prototype.exec = function exec (op, callback) { + switch (typeof op) { + case 'function': + callback = op; + op = null; + break; + case 'string': + this.op = op; + break; + } + + assert.ok(this.op, "Missing query type: (find, update, etc)"); + + if ('update' == this.op || 'remove' == this.op) { + callback || (callback = true); + } + + this[this.op](callback); +} + +/** + * Returns a thunk which when called runs this.exec() + * + * The thunk receives a callback function which will be + * passed to `this.exec()` + * + * @return {Function} + * @api public + */ + +Query.prototype.thunk = function() { + var self = this; + return function(cb) { + self.exec(cb); + } +} + +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @return {Promise} + * @api public + */ + +Query.prototype.then = function(resolve, reject) { + var self = this; + var promise = new Query.Promise(function(success, error) { + self.exec(function(err, val) { + if (err) error(err); + else success(val); + self = success = error = null; + }); + }); + return promise.then(resolve, reject); +} + +/** + * Returns a stream for the given find query. + * + * @throws Error if operation is not a find + * @returns {Stream} Node 0.8 style + */ + +Query.prototype.stream = function(streamOptions) { + if ('find' != this.op) + throw new Error('stream() is only available for find'); + + var conds = this._conditions; + + var options = this._optionsForExec() + options.fields = this._fieldsForExec() + + debug('stream', this._collection.collectionName, conds, options, streamOptions); + + return this._collection.findStream(conds, options, streamOptions); +} + +/** + * Determines if field selection has been made. + * + * @return {Boolean} + * @api public + */ + +Query.prototype.selected = function selected () { + return !! (this._fields && Object.keys(this._fields).length > 0); +} + +/** + * Determines if inclusive field selection has been made. + * + * query.selectedInclusively() // false + * query.select('name') + * query.selectedInclusively() // true + * query.selectedExlusively() // false + * + * @returns {Boolean} + */ + +Query.prototype.selectedInclusively = function selectedInclusively () { + if (!this._fields) return false; + + var keys = Object.keys(this._fields); + if (0 === keys.length) return false; + + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (0 === this._fields[key]) return false; + if (this._fields[key] && + typeof this._fields[key] === 'object' && + this._fields[key].$meta) { + return false; + } + } + + return true; +} + +/** + * Determines if exclusive field selection has been made. + * + * query.selectedExlusively() // false + * query.select('-name') + * query.selectedExlusively() // true + * query.selectedInclusively() // false + * + * @returns {Boolean} + */ + +Query.prototype.selectedExclusively = function selectedExclusively () { + if (!this._fields) return false; + + var keys = Object.keys(this._fields); + if (0 === keys.length) return false; + + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (0 === this._fields[key]) return true; + } + + return false; +} + +/** + * Merges `doc` with the current update object. + * + * @param {Object} doc + */ + +Query.prototype._mergeUpdate = function (doc) { + if (!this._update) this._update = {}; + if (doc instanceof Query) { + if (doc._update) { + utils.mergeClone(this._update, doc._update); + } + } else { + utils.mergeClone(this._update, doc); + } +} + +/** + * Returns default options. + * + * @return {Object} + * @api private + */ + +Query.prototype._optionsForExec = function () { + var options = utils.clone(this.options, { retainKeyOrder: true }); + return options; +} + +/** + * Returns fields selection for this query. + * + * @return {Object} + * @api private + */ + +Query.prototype._fieldsForExec = function () { + return utils.clone(this._fields, { retainKeyOrder: true }); +} + +/** + * Return an update document with corrected $set operations. + * + * @api private + */ + +Query.prototype._updateForExec = function () { + var update = utils.clone(this._update, { retainKeyOrder: true }) + , ops = utils.keys(update) + , i = ops.length + , ret = {} + , hasKeys + , val + + while (i--) { + var op = ops[i]; + + if (this.options.overwrite) { + ret[op] = update[op]; + continue; + } + + if ('$' !== op[0]) { + // fix up $set sugar + if (!ret.$set) { + if (update.$set) { + ret.$set = update.$set; + } else { + ret.$set = {}; + } + } + ret.$set[op] = update[op]; + ops.splice(i, 1); + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if ('$set' === op) { + if (!ret.$set) { + ret[op] = update[op]; + } + } else { + ret[op] = update[op]; + } + } + + return ret; +} + +/** + * Make sure _path is set. + * + * @parmam {String} method + */ + +Query.prototype._ensurePath = function (method) { + if (!this._path) { + var msg = method + '() must be used after where() ' + + 'when called with these arguments' + throw new Error(msg); + } +} + +/*! + * Permissions + */ + +Query.permissions = require('./permissions'); + +Query._isPermitted = function (a, b) { + var denied = Query.permissions[b]; + if (!denied) return true; + return true !== denied[a]; +} + +Query.prototype._validate = function (action) { + var fail; + var validator; + + if (undefined === action) { + + validator = Query.permissions[this.op]; + if ('function' != typeof validator) return true; + + fail = validator(this); + + } else if (!Query._isPermitted(action, this.op)) { + fail = action; + } + + if (fail) { + throw new Error(fail + ' cannot be used with ' + this.op); + } +} + +/** + * Determines if `conds` can be merged using `mquery().merge()` + * + * @param {Object} conds + * @return {Boolean} + */ + +Query.canMerge = function (conds) { + return conds instanceof Query || utils.isObject(conds); +} + +/** + * Set a trace function that will get called whenever a + * query is executed. + * + * See `setTraceFunction()` for details. + * + * @param {Object} conds + * @return {Boolean} + */ +Query.setGlobalTraceFunction = function (traceFunction) { + Query.traceFunction = traceFunction; +} + +/*! + * Exports. + */ + +Query.utils = utils; +Query.env = require('./env') +Query.Collection = require('./collection'); +Query.BaseCollection = require('./collection/collection'); +Query.Promise = require('bluebird'); +module.exports = exports = Query; + +// TODO +// test utils diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/lib/permissions.js b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/permissions.js new file mode 100644 index 0000000..5008a97 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/permissions.js @@ -0,0 +1,90 @@ +'use strict'; + +var denied = exports; + +denied.distinct = function (self) { + if (self._fields && Object.keys(self._fields).length > 0) { + return 'field selection and slice' + } + + var keys = Object.keys(denied.distinct); + var err; + + keys.every(function (option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +}; +denied.distinct.select = +denied.distinct.slice = +denied.distinct.sort = +denied.distinct.limit = +denied.distinct.skip = +denied.distinct.batchSize = +denied.distinct.comment = +denied.distinct.maxScan = +denied.distinct.snapshot = +denied.distinct.hint = +denied.distinct.tailable = true; + + +// aggregation integration + + +denied.findOneAndUpdate = +denied.findOneAndRemove = function (self) { + var keys = Object.keys(denied.findOneAndUpdate); + var err; + + keys.every(function (option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +} +denied.findOneAndUpdate.limit = +denied.findOneAndUpdate.skip = +denied.findOneAndUpdate.batchSize = +denied.findOneAndUpdate.maxScan = +denied.findOneAndUpdate.snapshot = +denied.findOneAndUpdate.hint = +denied.findOneAndUpdate.tailable = +denied.findOneAndUpdate.comment = true; + + +denied.count = function (self) { + if (self._fields && Object.keys(self._fields).length > 0) { + return 'field selection and slice' + } + + var keys = Object.keys(denied.count); + var err; + + keys.every(function (option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +} + +denied.count.select = +denied.count.slice = +denied.count.sort = +denied.count.batchSize = +denied.count.comment = +denied.count.maxScan = +denied.count.snapshot = +denied.count.tailable = true; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/lib/utils.js b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/utils.js new file mode 100644 index 0000000..6707ce2 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/lib/utils.js @@ -0,0 +1,331 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +var RegExpClone = require('regexp-clone') + +/** + * Clones objects + * + * @param {Object} obj the object to clone + * @param {Object} options + * @return {Object} the cloned object + * @api private + */ + +var clone = exports.clone = function clone (obj, options) { + if (obj === undefined || obj === null) + return obj; + + if (Array.isArray(obj)) + return exports.cloneArray(obj, options); + + if (obj.constructor) { + if (/ObjectI[dD]$/.test(obj.constructor.name)) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.id); + } + + if ('ReadPreference' === obj._type && obj.isValid && obj.toObject) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.mode, clone(obj.tags, options)); + } + + if ('Binary' == obj._bsontype && obj.buffer && obj.value) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.value(true), obj.sub_type); + } + + if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) + return new obj.constructor(+obj); + + if ('RegExp' === obj.constructor.name) + return RegExpClone(obj); + + if ('Buffer' === obj.constructor.name) + return exports.cloneBuffer(obj); + } + + if (isObject(obj)) + return exports.cloneObject(obj, options); + + if (obj.valueOf) + return obj.valueOf(); +}; + +/*! + * ignore + */ + +var cloneObject = exports.cloneObject = function cloneObject (obj, options) { + var retainKeyOrder = options && options.retainKeyOrder + , minimize = options && options.minimize + , ret = {} + , hasKeys + , keys + , val + , k + , i + + if (retainKeyOrder) { + for (k in obj) { + val = clone(obj[k], options); + + if (!minimize || ('undefined' !== typeof val)) { + hasKeys || (hasKeys = true); + ret[k] = val; + } + } + } else { + // faster + + keys = Object.keys(obj); + i = keys.length; + + while (i--) { + k = keys[i]; + val = clone(obj[k], options); + + if (!minimize || ('undefined' !== typeof val)) { + if (!hasKeys) hasKeys = true; + ret[k] = val; + } + } + } + + return minimize + ? hasKeys && ret + : ret; +}; + +var cloneArray = exports.cloneArray = function cloneArray (arr, options) { + var ret = []; + for (var i = 0, l = arr.length; i < l; i++) + ret.push(clone(arr[i], options)); + return ret; +}; + +/** + * process.nextTick helper. + * + * Wraps the given `callback` in a try/catch. If an error is + * caught it will be thrown on nextTick. + * + * node-mongodb-native had a habit of state corruption when + * an error was immediately thrown from within a collection + * method (find, update, etc) callback. + * + * @param {Function} [callback] + * @api private + */ + +var tick = exports.tick = function tick (callback) { + if ('function' !== typeof callback) return; + return function () { + // callbacks should always be fired on the next + // turn of the event loop. A side benefit is + // errors thrown from executing the callback + // will not cause drivers state to be corrupted + // which has historically been a problem. + var args = arguments; + soon(function(){ + callback.apply(this, args); + }); + } +} + +/** + * Merges `from` into `to` without overwriting existing properties. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +var merge = exports.merge = function merge (to, from) { + var keys = Object.keys(from) + , i = keys.length + , key + + while (i--) { + key = keys[i]; + if ('undefined' === typeof to[key]) { + to[key] = from[key]; + } else { + if (exports.isObject(from[key])) { + merge(to[key], from[key]); + } else { + to[key] = from[key]; + } + } + } +} + +/** + * Same as merge but clones the assigned values. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +var mergeClone = exports.mergeClone = function mergeClone (to, from) { + var keys = Object.keys(from) + , i = keys.length + , key + + while (i--) { + key = keys[i]; + if ('undefined' === typeof to[key]) { + // make sure to retain key order here because of a bug handling the $each + // operator in mongodb 2.4.4 + to[key] = clone(from[key], { retainKeyOrder : 1}); + } else { + if (exports.isObject(from[key])) { + mergeClone(to[key], from[key]); + } else { + // make sure to retain key order here because of a bug handling the + // $each operator in mongodb 2.4.4 + to[key] = clone(from[key], { retainKeyOrder : 1}); + } + } + } +} + +/** + * Read pref helper (mongo 2.2 drivers support this) + * + * Allows using aliases instead of full preference names: + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * @param {String} pref + */ + +exports.readPref = function readPref (pref) { + switch (pref) { + case 'p': + pref = 'primary'; + break; + case 'pp': + pref = 'primaryPreferred'; + break; + case 's': + pref = 'secondary'; + break; + case 'sp': + pref = 'secondaryPreferred'; + break; + case 'n': + pref = 'nearest'; + break; + } + + return pref; +} + +/** + * Object.prototype.toString.call helper + */ + +var _toString = Object.prototype.toString; +var toString = exports.toString = function (arg) { + return _toString.call(arg); +} + +/** + * Determines if `arg` is an object. + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @return {Boolean} + */ + +var isObject = exports.isObject = function (arg) { + return '[object Object]' == exports.toString(arg); +} + +/** + * Determines if `arg` is an array. + * + * @param {Object} + * @return {Boolean} + * @see nodejs utils + */ + +var isArray = exports.isArray = function (arg) { + return Array.isArray(arg) || + 'object' == typeof arg && '[object Array]' == exports.toString(arg); +} + +/** + * Object.keys helper + */ + +exports.keys = Object.keys || function (obj) { + var keys = []; + for (var k in obj) if (obj.hasOwnProperty(k)) { + keys.push(k); + } + return keys; +} + +/** + * Basic Object.create polyfill. + * Only one argument is supported. + * + * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create + */ + +exports.create = 'function' == typeof Object.create + ? Object.create + : create; + +function create (proto) { + if (arguments.length > 1) { + throw new Error("Adding properties is not supported") + } + + function F () {} + F.prototype = proto; + return new F; +} + +/** + * inheritance + */ + +exports.inherits = function (ctor, superCtor) { + ctor.prototype = exports.create(superCtor.prototype); + ctor.prototype.constructor = ctor; +} + +/** + * nextTick helper + * compat with node 0.10 which behaves differently than previous versions + */ + +var soon = exports.soon = 'function' == typeof setImmediate + ? setImmediate + : process.nextTick; + +/** + * Clones the contents of a buffer. + * + * @param {Buffer} buff + * @return {Buffer} + */ + +exports.cloneBuffer = function (buff) { + var dupe = new Buffer(buff.length); + buff.copy(dupe, 0, 0, buff.length); + return dupe; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE new file mode 100644 index 0000000..a3966cf --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Petka Antonov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions:

+ +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md new file mode 100644 index 0000000..5e92095 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md @@ -0,0 +1,676 @@ + + Promises/A+ logo + +[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) +[![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) + + +# Introduction + +Bluebird is a fully featured [promise](#what-are-promises-and-why-should-i-use-them) library with focus on innovative features and performance + + + +# Topics + +- [Features](#features) +- [Quick start](#quick-start) +- [API Reference and examples](API.md) +- [Support](#support) +- [What are promises and why should I use them?](#what-are-promises-and-why-should-i-use-them) +- [Questions and issues](#questions-and-issues) +- [Error handling](#error-handling) +- [Development](#development) + - [Testing](#testing) + - [Benchmarking](#benchmarks) + - [Custom builds](#custom-builds) + - [For library authors](#for-library-authors) +- [What is the sync build?](#what-is-the-sync-build) +- [License](#license) +- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets) +- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) +- [Changelog](changelog.md) +- [Optimization guide](#optimization-guide) + +# Features +bluebird logo + +- [Promises A+](http://promisesaplus.com) +- [Synchronous inspection](API.md#synchronous-inspection) +- [Concurrency coordination](API.md#collections) +- [Promisification on steroids](API.md#promisification) +- [Resource management through a parallel of python `with`/C# `using`](API.md#resource-management) +- [Cancellation and timeouts](API.md#cancellation) +- [Parallel for C# `async` and `await`](API.md#generators) +- Mind blowing utilities such as + - [`.bind()`](API.md#binddynamic-thisarg---promise) + - [`.call()`](API.md#callstring-propertyname--dynamic-arg---promise) + - [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) + - [And](API.md#core) [much](API.md#timers) [more](API.md#utility)! +- [Practical debugging solutions and sane defaults](#error-handling) +- [Sick performance](benchmark/) + +
+ +# Quick start + +## Node.js + + npm install bluebird + +Then: + +```js +var Promise = require("bluebird"); +``` + +## Browsers + +There are many ways to use bluebird in browsers: + +- Direct downloads + - Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js) + - Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js) +- You may use browserify on the main export +- You may use the [bower](http://bower.io) package. + +When using script tags the global variables `Promise` and `P` (alias for `Promise`) become available. + +A [minimal bluebird browser build](#custom-builds) is ≈38.92KB minified*, 11.65KB gzipped and has no external dependencies. + +*Google Closure Compiler using Simple. + +#### Browser support + +Browsers that [implement ECMA-262, edition 3](http://en.wikipedia.org/wiki/Ecmascript#Implementations) and later are supported. + +[![Selenium Test Status](https://saucelabs.com/browser-matrix/petka_antonov.svg)](https://saucelabs.com/u/petka_antonov) + +**Note** that in ECMA-262, edition 3 (IE7, IE8 etc.) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`. + +Also, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome, Firefox and Internet Explorer 10+. + +After quick start, see [API Reference and examples](API.md) + +
+ +# Support + +- Mailing list: [bluebird-js@googlegroups.com](https://groups.google.com/forum/#!forum/bluebird-js) +- IRC: #promises @freenode +- StackOverflow: [bluebird tag](http://stackoverflow.com/questions/tagged/bluebird) +- Bugs and feature requests: [github issue tracker](https://github.com/petkaantonov/bluebird/issues?state=open) + +
+ +# What are promises and why should I use them? + +You should use promises to turn this: + +```js +fs.readFile("file.json", function(err, val) { + if( err ) { + console.error("unable to read file"); + } + else { + try { + val = JSON.parse(val); + console.log(val.success); + } + catch( e ) { + console.error("invalid json in file"); + } + } +}); +``` + +Into this: + +```js +fs.readFileAsync("file.json").then(JSON.parse).then(function(val) { + console.log(val.success); +}) +.catch(SyntaxError, function(e) { + console.error("invalid json in file"); +}) +.catch(function(e) { + console.error("unable to read file") +}); +``` + +*If you are wondering "there is no `readFileAsync` method on `fs` that returns a promise", see [promisification](API.md#promisification)* + +Actually you might notice the latter has a lot in common with code that would do the same using synchronous I/O: + +```js +try { + var val = JSON.parse(fs.readFileSync("file.json")); + console.log(val.success); +} +//Syntax actually not supported in JS but drives the point +catch(SyntaxError e) { + console.error("invalid json in file"); +} +catch(Error e) { + console.error("unable to read file") +} +``` + +And that is the point - being able to have something that is a lot like `return` and `throw` in synchronous code. + +You can also use promises to improve code that was written with callback helpers: + + +```js +//Copyright Plato http://stackoverflow.com/a/19385911/995876 +//CC BY-SA 2.5 +mapSeries(URLs, function (URL, done) { + var options = {}; + needle.get(URL, options, function (error, response, body) { + if (error) { + return done(error) + } + try { + var ret = JSON.parse(body); + return done(null, ret); + } + catch (e) { + done(e); + } + }); +}, function (err, results) { + if (err) { + console.log(err) + } else { + console.log('All Needle requests successful'); + // results is a 1 to 1 mapping in order of URLs > needle.body + processAndSaveAllInDB(results, function (err) { + if (err) { + return done(err) + } + console.log('All Needle requests saved'); + done(null); + }); + } +}); +``` + +Is more pleasing to the eye when done with promises: + +```js +Promise.promisifyAll(needle); +var options = {}; + +var current = Promise.resolve(); +Promise.map(URLs, function(URL) { + current = current.then(function () { + return needle.getAsync(URL, options); + }); + return current; +}).map(function(responseAndBody){ + return JSON.parse(responseAndBody[1]); +}).then(function (results) { + return processAndSaveAllInDB(results); +}).then(function(){ + console.log('All Needle requests saved'); +}).catch(function (e) { + console.log(e); +}); +``` + +Also promises don't just give you correspondences for synchronous features but can also be used as limited event emitters or callback aggregators. + +More reading: + + - [Promise nuggets](https://promise-nuggets.github.io/) + - [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html) + - [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1) + - [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets) + - [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) + +# Questions and issues + +If you find a bug in bluebird or have a feature request, file an issue in the [github issue tracker](https://github.com/petkaantonov/bluebird/issues). Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. + +# Error handling + +This is a problem every promise library needs to handle in some way. Unhandled rejections/exceptions don't really have a good agreed-on asynchronous correspondence. The problem is that it is impossible to predict the future and know if a rejected promise will eventually be handled. + +There are two common pragmatic attempts at solving the problem that promise libraries do. + +The more popular one is to have the user explicitly communicate that they are done and any unhandled rejections should be thrown, like so: + +```js +download().then(...).then(...).done(); +``` + +For handling this problem, in my opinion, this is completely unacceptable and pointless. The user must remember to explicitly call `.done` and that cannot be justified when the problem is forgetting to create an error handler in the first place. + +The second approach, which is what bluebird by default takes, is to call a registered handler if a rejection is unhandled by the start of a second turn. The default handler is to write the stack trace to `stderr` or `console.error` in browsers. This is close to what happens with synchronous code - your code doesn't work as expected and you open console and see a stack trace. Nice. + +Of course this is not perfect, if your code for some reason needs to swoop in and attach error handler to some promise after the promise has been hanging around a while then you will see annoying messages. In that case you can use the `.done()` method to signal that any hanging exceptions should be thrown. + +If you want to override the default handler for these possibly unhandled rejections, you can pass yours like so: + +```js +Promise.onPossiblyUnhandledRejection(function(error){ + throw error; +}); +``` + +If you want to also enable long stack traces, call: + +```js +Promise.longStackTraces(); +``` + +right after the library is loaded. + +In node.js use the environment flag `BLUEBIRD_DEBUG`: + +``` +BLUEBIRD_DEBUG=1 node server.js +``` + +to enable long stack traces in all instances of bluebird. + +Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, even after using every trick to optimize them. + +Long stack traces are enabled by default in the debug build. + +#### Expected and unexpected errors + +A practical problem with Promises/A+ is that it models Javascript `try-catch` too closely for its own good. Therefore by default promises inherit `try-catch` warts such as the inability to specify the error types that the catch block is eligible for. It is an anti-pattern in every other language to use catch-all handlers because they swallow exceptions that you might not know about. + +Now, Javascript does have a perfectly fine and working way of creating error type hierarchies. It is still quite awkward to use them with the built-in `try-catch` however: + +```js +try { + //code +} +catch(e) { + if( e instanceof WhatIWantError) { + //handle + } + else { + throw e; + } +} +``` + +Without such checking, unexpected errors would be silently swallowed. However, with promises, bluebird brings the future (hopefully) here now and extends the `.catch` to [accept potential error type eligibility](API.md#catchfunction-errorclass-function-handler---promise). + +For instance here it is expected that some evil or incompetent entity will try to crash our server from `SyntaxError` by providing syntactically invalid JSON: + +```js +getJSONFromSomewhere().then(function(jsonString) { + return JSON.parse(jsonString); +}).then(function(object) { + console.log("it was valid json: ", object); +}).catch(SyntaxError, function(e){ + console.log("don't be evil"); +}); +``` + +Here any kind of unexpected error will automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`. + +Ok, so, that's pretty neat. But actually not many libraries define error types and it is in fact a complete ghetto out there with ad hoc strings being attached as some arbitrary property name like `.name`, `.type`, `.code`, not having any property at all or even throwing strings as errors and so on. So how can we still listen for expected errors? + +Bluebird defines a special error type `OperationalError` (you can get a reference from `Promise.OperationalError`). This type of error is given as rejection reason by promisified methods when +their underlying library gives an untyped, but expected error. Primitives such as strings, and error objects that are directly created like `new Error("database didn't respond")` are considered untyped. + +Example of such library is the node core library `fs`. So if we promisify it, we can catch just the errors we want pretty easily and have programmer errors be redirected to unhandled rejection handler so that we notice them: + +```js +//Read more about promisification in the API Reference: +//API.md +var fs = Promise.promisifyAll(require("fs")); + +fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) { + console.log("Successful json") +}).catch(SyntaxError, function (e) { + console.error("file contains invalid json"); +}).catch(Promise.OperationalError, function (e) { + console.error("unable to read file, because: ", e.message); +}); +``` + +The last `catch` handler is only invoked when the `fs` module explicitly used the `err` argument convention of async callbacks to inform of an expected error. The `OperationalError` instance will contain the original error in its `.cause` property but it does have a direct copy of the `.message` and `.stack` too. In this code any unexpected error - be it in our code or the `fs` module - would not be caught by these handlers and therefore not swallowed. + +Since a `catch` handler typed to `Promise.OperationalError` is expected to be used very often, it has a neat shorthand: + +```js +.error(function (e) { + console.error("unable to read file, because: ", e.message); +}); +``` + +See [API documentation for `.error()`](API.md#error-rejectedhandler----promise) + +Finally, Bluebird also supports predicate-based filters. If you pass a +predicate function instead of an error type, the predicate will receive +the error as an argument. The return result will be used to determine whether +the error handler should be called. + +Predicates should allow for very fine grained control over caught errors: +pattern matching, error typesets with set operations and many other techniques +can be implemented on top of them. + +Example of using a predicate-based filter: + +```js +var Promise = require("bluebird"); +var request = Promise.promisify(require("request")); + +function clientError(e) { + return e.code >= 400 && e.code < 500; +} + +request("http://www.google.com").then(function(contents){ + console.log(contents); +}).catch(clientError, function(e){ + //A client error like 400 Bad Request happened +}); +``` + +**Danger:** The JavaScript language allows throwing primitive values like strings. Throwing primitives can lead to worse or no stack traces. Primitives [are not exceptions](http://www.devthought.com/2011/12/22/a-string-is-not-an-error/). You should consider always throwing Error objects when handling exceptions. + +
+ +#### How do long stack traces differ from e.g. Q? + +Bluebird attempts to have more elaborate traces. Consider: + +```js +Error.stackTraceLimit = 25; +Q.longStackSupport = true; +Q().then(function outer() { + return Q().then(function inner() { + return Q().then(function evenMoreInner() { + a.b.c.d(); + }).catch(function catcher(e){ + console.error(e.stack); + }); + }) +}); +``` + +You will see + + ReferenceError: a is not defined + at evenMoreInner (:7:13) + From previous event: + at inner (:6:20) + +Compare to: + +```js +Error.stackTraceLimit = 25; +Promise.longStackTraces(); +Promise.resolve().then(function outer() { + return Promise.resolve().then(function inner() { + return Promise.resolve().then(function evenMoreInner() { + a.b.c.d() + }).catch(function catcher(e){ + console.error(e.stack); + }); + }); +}); +``` + + ReferenceError: a is not defined + at evenMoreInner (:7:13) + From previous event: + at inner (:6:36) + From previous event: + at outer (:5:32) + From previous event: + at :4:21 + at Object.InjectedScript._evaluateOn (:572:39) + at Object.InjectedScript._evaluateAndWrap (:531:52) + at Object.InjectedScript.evaluate (:450:21) + + +A better and more practical example of the differences can be seen in gorgikosev's [debuggability competition](https://github.com/spion/async-compare#debuggability). + +
+ +# Development + +For development tasks such as running benchmarks or testing, you need to clone the repository and install dev-dependencies. + +Install [node](http://nodejs.org/) and [npm](https://npmjs.org/) + + git clone git@github.com:petkaantonov/bluebird.git + cd bluebird + npm install + +## Testing + +To run all tests, run + + node tools/test + +If you need to run generator tests run the `tool/test.js` script with `--harmony` argument and node 0.11+: + + node-dev --harmony tools/test + +You may specify an individual test file to run with the `--run` script flag: + + node tools/test --run=cancel.js + + +This enables output from the test and may give a better idea where the test is failing. The paramter to `--run` can be any file name located in `test/mocha` folder. + +#### Testing in browsers + +To run the test in a browser instead of node, pass the flag `--browser` to the test tool + + node tools/test --run=cancel.js --browser + +This will automatically create a server (default port 9999) and open it in your default browser once the tests have been compiled. + +Keep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active. + +#### Supported options by the test tool + +The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-browser`. + + - `--run=String`. Which tests to run (or compile when testing in browser). Default `"all"`. Can also be a glob string (relative to ./test/mocha folder) + - `--cover=String`. Create code coverage using the String as istanbul reporter. Coverage is created in the ./coverage folder. No coverage is created by default, default reporter is `"html"` (use `--cover` to use default reporter). + - `--browser` - Whether to compile tests for browsers. Default `false`. + - `--port=Number` - Whe port where local server is hosted when testing in browser. Default `9999` + - `--execute-browser-tests` - Whether to execute the compiled tests for browser when using `--browser`. Default `true`. + - `--open-browser` - Whether to open the default browser when executing browser tests. Default `true`. + - `--fake-timers` - Whether to use fake timers (`setTimeout` etc) when running tests in node. Default `true`. + - `--js-hint` - Whether to run JSHint on source files. Default `true`. + - `--saucelabs` Wheter to create a tunnel to sauce labs and run tests in their VMs instead of your browser when compiling tests for browser.Default `false`. + +## Benchmarks + +To run a benchmark, run the given command for a benchmark while on the project root. Requires bash (on windows the mingw32 that comes with git works fine too). + +Node 0.11.2+ is required to run the generator examples. + +### 1\. DoxBee sequential + +Currently the most relevant benchmark is @gorkikosev's benchmark in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where n amount of users are making a request in parallel to execute some mixed async/sync action. The benchmark has been modified to include a warm-up phase to minimize any JITing during timed sections. + +Command: `bench doxbee` + +### 2\. Made-up parallel + +This made-up scenario runs 15 shimmed queries in parallel. + +Command: `bench parallel` + +## Custom builds + +Custom builds for browsers are supported through a command-line utility. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
The following features can be disabled
Feature(s)Command line identifier
.any and Promise.anyany
.race and Promise.racerace
.call and .getcall_get
.filter and Promise.filterfilter
.map and Promise.mapmap
.reduce and Promise.reducereduce
.props and Promise.propsprops
.settle and Promise.settlesettle
.some and Promise.somesome
.nodeifynodeify
Promise.coroutine and Promise.spawngenerators
Progressionprogress
Promisificationpromisify
Cancellationcancel
Timerstimers
Resource managementusing
+ + +Make sure you have cloned the repo somewhere and did `npm install` successfully. + +After that you can run: + + node tools/build --features="core" + + +The above builds the most minimal build you can get. You can add more features separated by spaces from the above list: + + node tools/build --features="core filter map reduce" + +The custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features. + +Note that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build +a full version afterwards (after having taken a copy of the bluebird.js somewhere): + + node tools/build --debug --main --zalgo --browser --minify + +#### Supported options by the build tool + +The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`. + + - `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`. + - `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`. + - `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`. + - `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`. + - `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`. + - `--features=String` - See [custom builds](#custom-builds) + +
+ +## For library authors + +Building a library that depends on bluebird? You should know about a few features. + +If your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require("bluebird")`. Instead you should create a file +that creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains: + +```js + //NOTE the function call right after +module.exports = require("bluebird/js/main/promise")(); +``` + +Your library can then use `var Promise = require("bluebird-extended");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic. + +You should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---promise) which makes it easy to provide a dual callback/promise API. + +
+ +## What is the sync build? + +You may now use sync build by: + + var Promise = require("bluebird/zalgo"); + +The sync build is provided to see how forced asynchronity affects benchmarks. It should not be used in real code due to the implied hazards. + +The normal async build gives Promises/A+ guarantees about asynchronous resolution of promises. Some people think this affects performance or just plain love their code having a possibility +of stack overflow errors and non-deterministic behavior. + +The sync build skips the async call trampoline completely, e.g code like: + + async.invoke( this.fn, this, val ); + +Appears as this in the sync build: + + this.fn(val); + +This should pressure the CPU slightly less and thus the sync build should perform better. Indeed it does, but only marginally. The biggest performance boosts are from writing efficient Javascript, not from compromising determinism. + +Note that while some benchmarks are waiting for the next event tick, the CPU is actually not in use during that time. So the resulting benchmark result is not completely accurate because on node.js you only care about how much the CPU is taxed. Any time spent on CPU is time the whole process (or server) is paralyzed. And it is not graceful like it would be with threads. + + +```js +var cache = new Map(); //ES6 Map or DataStructures/Map or whatever... +function getResult(url) { + var resolver = Promise.pending(); + if (cache.has(url)) { + resolver.resolve(cache.get(url)); + } + else { + http.get(url, function(err, content) { + if (err) resolver.reject(err); + else { + cache.set(url, content); + resolver.resolve(content); + } + }); + } + return resolver.promise; +} + + + +//The result of console.log is truly random without async guarantees +function guessWhatItPrints( url ) { + var i = 3; + getResult(url).then(function(){ + i = 4; + }); + console.log(i); +} +``` + +# Optimization guide + +Articles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome. + +A single cohesive guide compiled from the articles will probably be done eventually. + +# License + +The MIT License (MIT) + +Copyright (c) 2014 Petka Antonov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..46729e1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md @@ -0,0 +1,1643 @@ +## 2.9.26 (2015-05-25) + +Bugfixes: + + - Fix crash in NW [#624](.) + - Fix [`.return()`](.) not supporting `undefined` as return value [#627](.) + +## 2.9.25 (2015-04-28) + +Bugfixes: + + - Fix crash in node 0.8 + +## 2.9.24 (2015-04-02) + +Bugfixes: + + - Fix not being able to load multiple bluebird copies introduced in 2.9.22 ([#559](.), [#561](.), [#560](.)). + +## 2.9.23 (2015-04-02) + +Bugfixes: + + - Fix node.js domain propagation ([#521](.)). + +## 2.9.22 (2015-04-02) + + - Fix `.promisify` crashing in phantom JS ([#556](.)) + +## 2.9.21 (2015-03-30) + + - Fix error object's `'stack'`' overwriting causing an error when its defined to be a setter that throws an error ([#552](.)). + +## 2.9.20 (2015-03-29) + +Bugfixes: + + - Fix regression where there is a long delay between calling `.cancel()` and promise actually getting cancelled in Chrome when long stack traces are enabled + +## 2.9.19 (2015-03-29) + +Bugfixes: + + - Fix crashing in Chrome when long stack traces are disabled + +## 2.9.18 (2015-03-29) + +Bugfixes: + + - Fix settlePromises using trampoline + +## 2.9.17 (2015-03-29) + + +Bugfixes: + + - Fix Chrome DevTools async stack traceability ([#542](.)). + +## 2.9.16 (2015-03-28) + +Features: + + - Use setImmediate if available + +## 2.9.15 (2015-03-26) + +Features: + + - Added `.asCallback` alias for `.nodeify`. + +Bugfixes: + + - Don't always use nextTick, but try to pick up setImmediate or setTimeout in NW. Fixes [#534](.), [#525](.) + - Make progress a core feature. Fixes [#535](.) Note that progress has been removed in 3.x - this is only a fix necessary for 2.x custom builds. + +## 2.9.14 (2015-03-12) + +Bugfixes: + + - Always use process.nextTick. Fixes [#525](.) + +## 2.9.13 (2015-02-27) + +Bugfixes: + + - Fix .each, .filter, .reduce and .map callbacks being called synchornously if the input is immediate. ([#513](.)) + +## 2.9.12 (2015-02-19) + +Bugfixes: + + - Fix memory leak introduced in 2.9.0 ([#502](.)) + +## 2.9.11 (2015-02-19) + +Bugfixes: + + - Fix [#503](.) + +## 2.9.10 (2015-02-18) + +Bugfixes: + + - Fix [#501](.) + +## 2.9.9 (2015-02-12) + +Bugfixes: + + - Fix `TypeError: Cannot assign to read only property 'length'` when jsdom has declared a read-only length for all objects to inherit. + +## 2.9.8 (2015-02-10) + +Bugfixes: + + - Fix regression introduced in 2.9.7 where promisify didn't properly dynamically look up methods on `this` + +## 2.9.7 (2015-02-08) + +Bugfixes: + + - Fix `promisify` not retaining custom properties of the function. This enables promisifying the `"request"` module's export function and its methods at the same time. + - Fix `promisifyAll` methods being dependent on `this` when they are not originally dependent on `this`. This enables e.g. passing promisified `fs` functions directly as callbacks without having to bind them to `fs`. + - Fix `process.nextTick` being used over `setImmediate` in node. + +## 2.9.6 (2015-02-02) + +Bugfixes: + + - Node environment detection can no longer be fooled + +## 2.9.5 (2015-02-02) + +Misc: + + - Warn when [`.then()`](.) is passed non-functions + +## 2.9.4 (2015-01-30) + +Bugfixes: + + - Fix [.timeout()](.) not calling `clearTimeout` with the proper handle in node causing the process to wait for unneeded timeout. This was a regression introduced in 2.9.1. + +## 2.9.3 (2015-01-27) + +Bugfixes: + + - Fix node-webkit compatibility issue ([#467](https://github.com/petkaantonov/bluebird/pull/467)) + - Fix long stack trace support in recent firefox versions + +## 2.9.2 (2015-01-26) + +Bugfixes: + + - Fix critical bug regarding to using promisifyAll in browser that was introduced in 2.9.0 ([#466](https://github.com/petkaantonov/bluebird/issues/466)). + +Misc: + + - Add `"browser"` entry point to package.json + +## 2.9.1 (2015-01-24) + +Features: + + - If a bound promise is returned by the callback to [`Promise.method`](#promisemethodfunction-fn---function) and [`Promise.try`](#promisetryfunction-fn--arraydynamicdynamic-arguments--dynamic-ctx----promise), the returned promise will be bound to the same value + +## 2.9.0 (2015-01-24) + +Features: + + - Add [`Promise.fromNode`](API.md#promisefromnodefunction-resolver---promise) + - Add new paramter `value` for [`Promise.bind`](API.md#promisebinddynamic-thisarg--dynamic-value---promise) + +Bugfixes: + + - Fix several issues with [`cancellation`](API.md#cancellation) and [`.bind()`](API.md#binddynamic-thisarg---promise) interoperation when `thisArg` is a promise or thenable + - Fix promises created in [`disposers`](API#disposerfunction-disposer---disposer) not having proper long stack trace context + - Fix [`Promise.join`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) sometimes passing the passed in callback function as the last argument to itself. + +Misc: + + - Reduce minified full browser build file size by not including unused code generation functionality. + - Major internal refactoring related to testing code and source code file layout + +## 2.8.2 (2015-01-20) + +Features: + + - [Global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) are now fired both as DOM3 events and as legacy events in browsers + +## 2.8.1 (2015-01-20) + +Bugfixes: + + - Fix long stack trace stiching consistency when rejected from thenables + +## 2.8.0 (2015-01-19) + +Features: + + - Major debuggability improvements: + - Long stack traces have been re-designed. They are now much more readable, + succint, relevant and consistent across bluebird features. + - Long stack traces are supported now in IE10+ + +## 2.7.1 (2015-01-15) + +Bugfixes: + + - Fix [#447](https://github.com/petkaantonov/bluebird/issues/447) + +## 2.7.0 (2015-01-15) + +Features: + + - Added more context to stack traces originating from coroutines ([#421](https://github.com/petkaantonov/bluebird/issues/421)) + - Implemented [global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) ([#428](https://github.com/petkaantonov/bluebird/issues/428), [#357](https://github.com/petkaantonov/bluebird/issues/357)) + - [Custom promisifiers](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-promisifier) are now passed the default promisifier which can be used to add enhancements on top of normal node promisification + - [Promisification filters](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-filter) are now passed `passesDefaultFilter` boolean + +Bugfixes: + + - Fix `.noConflict()` call signature ([#446]()) + - Fix `Promise.method`ified functions being called with `undefined` when they were called with no arguments + +## 2.6.4 (2015-01-12) + +Bugfixes: + + - `OperationalErrors` thrown by promisified functions retain custom properties, such as `.code` and `.path`. + +## 2.6.3 (2015-01-12) + +Bugfixes: + + - Fix [#429](https://github.com/petkaantonov/bluebird/issues/429) + - Fix [#432](https://github.com/petkaantonov/bluebird/issues/432) + - Fix [#433](https://github.com/petkaantonov/bluebird/issues/433) + +## 2.6.2 (2015-01-07) + +Bugfixes: + + - Fix [#426](https://github.com/petkaantonov/bluebird/issues/426) + +## 2.6.1 (2015-01-07) + +Bugfixes: + + - Fixed built browser files not being included in the git tag release for bower + +## 2.6.0 (2015-01-06) + +Features: + + - Significantly improve parallel promise performance and memory usage (+50% faster, -50% less memory) + + +## 2.5.3 (2014-12-30) + +## 2.5.2 (2014-12-29) + +Bugfixes: + + - Fix bug where already resolved promise gets attached more handlers while calling its handlers resulting in some handlers not being called + - Fix bug where then handlers are not called in the same order as they would run if Promises/A+ 2.3.2 was implemented as adoption + - Fix bug where using `Object.create(null)` as a rejection reason would crash bluebird + +## 2.5.1 (2014-12-29) + +Bugfixes: + + - Fix `.finally` throwing null error when it is derived from a promise that is resolved with a promise that is resolved with a promise + +## 2.5.0 (2014-12-28) + +Features: + + - [`.get`](#API.md#https://github.com/petkaantonov/bluebird/blob/master/API.md#getstring-propertyname---promise) now supports negative indexing. + +Bugfixes: + + - Fix bug with `Promise.method` wrapped function returning a promise that never resolves if the function returns a promise that is resolved with another promise + - Fix bug with `Promise.delay` never resolving if the value is a promise that is resolved with another promise + +## 2.4.3 (2014-12-28) + +Bugfixes: + + - Fix memory leak as described in [this Promises/A+ spec issue](https://github.com/promises-aplus/promises-spec/issues/179). + +## 2.4.2 (2014-12-21) + +Bugfixes: + + - Fix bug where spread rejected handler is ignored in case of rejection + - Fix synchronous scheduler passed to `setScheduler` causing infinite loop + +## 2.4.1 (2014-12-20) + +Features: + + - Error messages now have links to wiki pages for additional information + - Promises now clean up all references (to handlers, child promises etc) as soon as possible. + +## 2.4.0 (2014-12-18) + +Features: + + - Better filtering of bluebird internal calls in long stack traces, especially when using minified file in browsers + - Small performance improvements for all collection methods + - Promises now delete references to handlers attached to them as soon as possible + - Additional stack traces are now output on stderr/`console.warn` for errors that are thrown in the process/window from rejected `.done()` promises. See [#411](https://github.com/petkaantonov/bluebird/issues/411) + +## 2.3.11 (2014-10-31) + +Bugfixes: + + - Fix [#371](https://github.com/petkaantonov/bluebird/issues/371), [#373](https://github.com/petkaantonov/bluebird/issues/373) + + +## 2.3.10 (2014-10-28) + +Features: + + - `Promise.method` no longer wraps primitive errors + - `Promise.try` no longer wraps primitive errors + +## 2.3.7 (2014-10-25) + +Bugfixes: + + - Fix [#359](https://github.com/petkaantonov/bluebird/issues/359), [#362](https://github.com/petkaantonov/bluebird/issues/362) and [#364](https://github.com/petkaantonov/bluebird/issues/364) + +## 2.3.6 (2014-10-15) + +Features: + + - Implement [`.reflect()`](API.md#reflect---promisepromiseinspection) + +## 2.3.5 (2014-10-06) + +Bugfixes: + + - Fix issue when promisifying methods whose names contain the string 'args' + +## 2.3.4 (2014-09-27) + + - `P` alias was not declared inside WebWorkers + +## 2.3.3 (2014-09-27) + +Bugfixes: + + - Fix [#318](https://github.com/petkaantonov/bluebird/issues/318), [#314](https://github.com/petkaantonov/bluebird/issues/#314) + +## 2.3.2 (2014-08-25) + +Bugfixes: + + - `P` alias for `Promise` now exists in global scope when using browser builds without a module loader, fixing an issue with firefox extensions + +## 2.3.1 (2014-08-23) + +Features: + + - `.using` can now be used with disposers created from different bluebird copy + +## 2.3.0 (2014-08-13) + +Features: + + - [`.bind()`](API.md#binddynamic-thisarg---promise) and [`Promise.bind()`](API.md#promisebinddynamic-thisarg---promise) now await for the resolution of the `thisArg` if it's a promise or a thenable + +Bugfixes: + + - Fix [#276](https://github.com/petkaantonov/bluebird/issues/276) + +## 2.2.2 (2014-07-14) + + - Fix [#259](https://github.com/petkaantonov/bluebird/issues/259) + +## 2.2.1 (2014-07-07) + + - Fix multiline error messages only showing the first line + +## 2.2.0 (2014-07-07) + +Bugfixes: + + - `.any` and `.some` now consistently reject with RangeError when input array contains too few promises + - Fix iteration bug with `.reduce` when input array contains already fulfilled promises + +## 2.1.3 (2014-06-18) + +Bugfixes: + + - Fix [#235](https://github.com/petkaantonov/bluebird/issues/235) + +## 2.1.2 (2014-06-15) + +Bugfixes: + + - Fix [#232](https://github.com/petkaantonov/bluebird/issues/232) + +## 2.1.1 (2014-06-11) + +## 2.1.0 (2014-06-11) + +Features: + + - Add [`promisifier`](API.md#option-promisifier) option to `Promise.promisifyAll()` + - Improve performance of `.props()` and collection methods when used with immediate values + + +Bugfixes: + + - Fix a bug where .reduce calls the callback for an already visited item + - Fix a bug where stack trace limit is calculated to be too small, which resulted in too short stack traces + +Add undocumented experimental `yieldHandler` option to `Promise.coroutine` + +## 2.0.7 (2014-06-08) +## 2.0.6 (2014-06-07) +## 2.0.5 (2014-06-05) +## 2.0.4 (2014-06-05) +## 2.0.3 (2014-06-05) +## 2.0.2 (2014-06-04) +## 2.0.1 (2014-06-04) + +## 2.0.0 (2014-06-04) + +#What's new in 2.0 + +- [Resource management](API.md#resource-management) - never leak resources again +- [Promisification](API.md#promisification) on steroids - entire modules can now be promisified with one line of code +- [`.map()`](API.md#mapfunction-mapper--object-options---promise), [`.each()`](API.md#eachfunction-iterator---promise), [`.filter()`](API.md#filterfunction-filterer--object-options---promise), [`.reduce()`](API.md#reducefunction-reducer--dynamic-initialvalue---promise) reimagined from simple sugar to powerful concurrency coordination tools +- [API Documentation](API.md) has been reorganized and more elaborate examples added +- Deprecated [progression](#progression-migration) and [deferreds](#deferred-migration) +- Improved performance and readability + +Features: + +- Added [`using()`](API.md#promiseusingpromisedisposer-promise-promisedisposer-promise--function-handler---promise) and [`disposer()`](API.md#disposerfunction-disposer---disposer) +- [`.map()`](API.md#mapfunction-mapper--object-options---promise) now calls the handler as soon as items in the input array become fulfilled +- Added a concurrency option to [`.map()`](API.md#mapfunction-mapper--object-options---promise) +- [`.filter()`](API.md#filterfunction-filterer--object-options---promise) now calls the handler as soon as items in the input array become fulfilled +- Added a concurrency option to [`.filter()`](API.md#filterfunction-filterer--object-options---promise) +- [`.reduce()`](API.md#reducefunction-reducer--dynamic-initialvalue---promise) now calls the handler as soon as items in the input array become fulfilled, but in-order +- Added [`.each()`](API.md#eachfunction-iterator---promise) +- [`Promise.resolve()`](API.md#promiseresolvedynamic-value---promise) behaves like `Promise.cast`. `Promise.cast` deprecated. +- [Synchronous inspection](API.md#synchronous-inspection): Removed `.inspect()`, added [`.value()`](API.md#value---dynamic) and [`.reason()`](API.md#reason---dynamic) +- [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) now takes a function as the last argument +- Added [`Promise.setScheduler()`](API.md#promisesetschedulerfunction-scheduler---void) +- [`.cancel()`](API.md#cancelerror-reason---promise) supports a custom cancellation reason +- [`.timeout()`](API.md#timeoutint-ms--string-message---promise) now cancels the promise instead of rejecting it +- [`.nodeify()`](API.md#nodeifyfunction-callback--object-options---promise) now supports passing multiple success results when mapping promises to nodebacks +- Added `suffix` and `filter` options to [`Promise.promisifyAll()`](API.md#promisepromisifyallobject-target--object-options---object) + +Breaking changes: + +- Sparse array holes are not skipped by collection methods but treated as existing elements with `undefined` value +- `.map()` and `.filter()` do not call the given mapper or filterer function in any specific order +- Removed the `.inspect()` method +- Yielding an array from a coroutine is not supported by default. You can use [`coroutine.addYieldHandler()`](API.md#promisecoroutineaddyieldhandlerfunction-handler---void) to configure the old behavior (or any behavior you want). +- [`.any()`](API.md#any---promise) and [`.some()`](API.md#someint-count---promise) no longer use an array as the rejection reason. [`AggregateError`](API.md#aggregateerror) is used instead. + + +## 1.2.4 (2014-04-27) + +Bugfixes: + + - Fix promisifyAll causing a syntax error when a method name is not a valid identifier + - Fix syntax error when es5.js is used in strict mode + +## 1.2.3 (2014-04-17) + +Bugfixes: + + - Fix [#179](https://github.com/petkaantonov/bluebird/issues/179) + +## 1.2.2 (2014-04-09) + +Bugfixes: + + - Promisified methods from promisifyAll no longer call the original method when it is overriden + - Nodeify doesn't pass second argument to the callback if the promise is fulfilled with `undefined` + +## 1.2.1 (2014-03-31) + +Bugfixes: + + - Fix [#168](https://github.com/petkaantonov/bluebird/issues/168) + +## 1.2.0 (2014-03-29) + +Features: + + - New method: [`.value()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#value---dynamic) + - New method: [`.reason()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#reason---dynamic) + - New method: [`Promise.onUnhandledRejectionHandled()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promiseonunhandledrejectionhandledfunction-handler---undefined) + - `Promise.map()`, `.map()`, `Promise.filter()` and `.filter()` start calling their callbacks as soon as possible while retaining a correct order. See [`8085922f`](https://github.com/petkaantonov/bluebird/commit/8085922fb95a9987fda0cf2337598ab4a98dc315). + +Bugfixes: + + - Fix [#165](https://github.com/petkaantonov/bluebird/issues/165) + - Fix [#166](https://github.com/petkaantonov/bluebird/issues/166) + +## 1.1.1 (2014-03-18) + +Bugfixes: + + - [#138](https://github.com/petkaantonov/bluebird/issues/138) + - [#144](https://github.com/petkaantonov/bluebird/issues/144) + - [#148](https://github.com/petkaantonov/bluebird/issues/148) + - [#151](https://github.com/petkaantonov/bluebird/issues/151) + +## 1.1.0 (2014-03-08) + +Features: + + - Implement [`Promise.prototype.tap()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#tapfunction-handler---promise) + - Implement [`Promise.coroutine.addYieldHandler()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisecoroutineaddyieldhandlerfunction-handler---void) + - Deprecate `Promise.prototype.spawn` + +Bugfixes: + + - Fix already rejected promises being reported as unhandled when handled through collection methods + - Fix browserisfy crashing from checking `process.version.indexOf` + +## 1.0.8 (2014-03-03) + +Bugfixes: + + - Fix active domain being lost across asynchronous boundaries in Node.JS 10.xx + +## 1.0.7 (2014-02-25) + +Bugfixes: + + - Fix handled errors being reported + +## 1.0.6 (2014-02-17) + +Bugfixes: + + - Fix bug with unhandled rejections not being reported + when using `Promise.try` or `Promise.method` without + attaching further handlers + +## 1.0.5 (2014-02-15) + +Features: + + - Node.js performance: promisified functions try to check amount of passed arguments in most optimal order + - Node.js promisified functions will have same `.length` as the original function minus one (for the callback parameter) + +## 1.0.4 (2014-02-09) + +Features: + + - Possibly unhandled rejection handler will always get a stack trace, even if the rejection or thrown error was not an error + - Unhandled rejections are tracked per promise, not per error. So if you create multiple branches from a single ancestor and that ancestor gets rejected, each branch with no error handler with the end will cause a possibly unhandled rejection handler invocation + +Bugfixes: + + - Fix unhandled non-writable objects or primitives not reported by possibly unhandled rejection handler + +## 1.0.3 (2014-02-05) + +Bugfixes: + + - [#93](https://github.com/petkaantonov/bluebird/issues/88) + +## 1.0.2 (2014-02-04) + +Features: + + - Significantly improve performance of foreign bluebird thenables + +Bugfixes: + + - [#88](https://github.com/petkaantonov/bluebird/issues/88) + +## 1.0.1 (2014-01-28) + +Features: + + - Error objects that have property `.isAsync = true` will now be caught by `.error()` + +Bugfixes: + + - Fix TypeError and RangeError shims not working without `new` operator + +## 1.0.0 (2014-01-12) + +Features: + + - `.filter`, `.map`, and `.reduce` no longer skip sparse array holes. This is a backwards incompatible change. + - Like `.map` and `.filter`, `.reduce` now allows returning promises and thenables from the iteration function. + +Bugfixes: + + - [#58](https://github.com/petkaantonov/bluebird/issues/58) + - [#61](https://github.com/petkaantonov/bluebird/issues/61) + - [#64](https://github.com/petkaantonov/bluebird/issues/64) + - [#60](https://github.com/petkaantonov/bluebird/issues/60) + +## 0.11.6-1 (2013-12-29) + +## 0.11.6-0 (2013-12-29) + +Features: + + - You may now return promises and thenables from the filterer function used in `Promise.filter` and `Promise.prototype.filter`. + + - `.error()` now catches additional sources of rejections: + + - Rejections originating from `Promise.reject` + + - Rejections originating from thenables using + the `reject` callback + + - Rejections originating from promisified callbacks + which use the `errback` argument + + - Rejections originating from `new Promise` constructor + where the `reject` callback is called explicitly + + - Rejections originating from `PromiseResolver` where + `.reject()` method is called explicitly + +Bugfixes: + + - Fix `captureStackTrace` being called when it was `null` + - Fix `Promise.map` not unwrapping thenables + +## 0.11.5-1 (2013-12-15) + +## 0.11.5-0 (2013-12-03) + +Features: + + - Improve performance of collection methods + - Improve performance of promise chains + +## 0.11.4-1 (2013-12-02) + +## 0.11.4-0 (2013-12-02) + +Bugfixes: + + - Fix `Promise.some` behavior with arguments like negative integers, 0... + - Fix stack traces of synchronously throwing promisified functions' + +## 0.11.3-0 (2013-12-02) + +Features: + + - Improve performance of generators + +Bugfixes: + + - Fix critical bug with collection methods. + +## 0.11.2-0 (2013-12-02) + +Features: + + - Improve performance of all collection methods + +## 0.11.1-0 (2013-12-02) + +Features: + +- Improve overall performance. +- Improve performance of promisified functions. +- Improve performance of catch filters. +- Improve performance of .finally. + +Bugfixes: + +- Fix `.finally()` rejecting if passed non-function. It will now ignore non-functions like `.then`. +- Fix `.finally()` not converting thenables returned from the handler to promises. +- `.spread()` now rejects if the ultimate value given to it is not spreadable. + +## 0.11.0-0 (2013-12-02) + +Features: + + - Improve overall performance when not using `.bind()` or cancellation. + - Promises are now not cancellable by default. This is backwards incompatible change - see [`.cancellable()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#cancellable---promise) + - [`Promise.delay`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisedelaydynamic-value-int-ms---promise) + - [`.delay()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#delayint-ms---promise) + - [`.timeout()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#timeoutint-ms--string-message---promise) + +## 0.10.14-0 (2013-12-01) + +Bugfixes: + + - Fix race condition when mixing 3rd party asynchrony. + +## 0.10.13-1 (2013-11-30) + +## 0.10.13-0 (2013-11-30) + +Bugfixes: + + - Fix another bug with progression. + +## 0.10.12-0 (2013-11-30) + +Bugfixes: + + - Fix bug with progression. + +## 0.10.11-4 (2013-11-29) + +## 0.10.11-2 (2013-11-29) + +Bugfixes: + + - Fix `.race()` not propagating bound values. + +## 0.10.11-1 (2013-11-29) + +Features: + + - Improve performance of `Promise.race` + +## 0.10.11-0 (2013-11-29) + +Bugfixes: + + - Fixed `Promise.promisifyAll` invoking property accessors. Only data properties with function values are considered. + +## 0.10.10-0 (2013-11-28) + +Features: + + - Disable long stack traces in browsers by default. Call `Promise.longStackTraces()` to enable them. + +## 0.10.9-1 (2013-11-27) + +Bugfixes: + + - Fail early when `new Promise` is constructed incorrectly + +## 0.10.9-0 (2013-11-27) + +Bugfixes: + + - Promise.props now takes a [thenable-for-collection](https://github.com/petkaantonov/bluebird/blob/f41edac61b7c421608ff439bb5a09b7cffeadcf9/test/mocha/props.js#L197-L217) + - All promise collection methods now reject when a promise-or-thenable-for-collection turns out not to give a collection + +## 0.10.8-0 (2013-11-25) + +Features: + + - All static collection methods take thenable-for-collection + +## 0.10.7-0 (2013-11-25) + +Features: + + - throw TypeError when thenable resolves with itself + - Make .race() and Promise.race() forever pending on empty collections + +## 0.10.6-0 (2013-11-25) + +Bugfixes: + + - Promise.resolve and PromiseResolver.resolve follow thenables too. + +## 0.10.5-0 (2013-11-24) + +Bugfixes: + + - Fix infinite loop when thenable resolves with itself + +## 0.10.4-1 (2013-11-24) + +Bugfixes: + + - Fix a file missing from build. (Critical fix) + +## 0.10.4-0 (2013-11-24) + +Features: + + - Remove dependency of es5-shim and es5-sham when using ES3. + +## 0.10.3-0 (2013-11-24) + +Features: + + - Improve performance of `Promise.method` + +## 0.10.2-1 (2013-11-24) + +Features: + + - Rename PromiseResolver#asCallback to PromiseResolver#callback + +## 0.10.2-0 (2013-11-24) + +Features: + + - Remove memoization of thenables + +## 0.10.1-0 (2013-11-21) + +Features: + + - Add methods `Promise.resolve()`, `Promise.reject()`, `Promise.defer()` and `.resolve()`. + +## 0.10.0-1 (2013-11-17) + +## 0.10.0-0 (2013-11-17) + +Features: + + - Implement `Promise.method()` + - Implement `.return()` + - Implement `.throw()` + +Bugfixes: + + - Fix promises being able to use themselves as resolution or follower value + +## 0.9.11-1 (2013-11-14) + +Features: + + - Implicit `Promise.all()` when yielding an array from generators + +## 0.9.11-0 (2013-11-13) + +Bugfixes: + + - Fix `.spread` not unwrapping thenables + +## 0.9.10-2 (2013-11-13) + +Features: + + - Improve performance of promisified functions on V8 + +Bugfixes: + + - Report unhandled rejections even when long stack traces are disabled + - Fix `.error()` showing up in stack traces + +## 0.9.10-1 (2013-11-05) + +Bugfixes: + + - Catch filter method calls showing in stack traces + +## 0.9.10-0 (2013-11-05) + +Bugfixes: + + - Support primitives in catch filters + +## 0.9.9-0 (2013-11-05) + +Features: + + - Add `Promise.race()` and `.race()` + +## 0.9.8-0 (2013-11-01) + +Bugfixes: + + - Fix bug with `Promise.try` not unwrapping returned promises and thenables + +## 0.9.7-0 (2013-10-29) + +Bugfixes: + + - Fix bug with build files containing duplicated code for promise.js + +## 0.9.6-0 (2013-10-28) + +Features: + + - Improve output of reporting unhandled non-errors + - Implement RejectionError wrapping and `.error()` method + +## 0.9.5-0 (2013-10-27) + +Features: + + - Allow fresh copies of the library to be made + +## 0.9.4-1 (2013-10-27) + +## 0.9.4-0 (2013-10-27) + +Bugfixes: + + - Rollback non-working multiple fresh copies feature + +## 0.9.3-0 (2013-10-27) + +Features: + + - Allow fresh copies of the library to be made + - Add more components to customized builds + +## 0.9.2-1 (2013-10-25) + +## 0.9.2-0 (2013-10-25) + +Features: + + - Allow custom builds + +## 0.9.1-1 (2013-10-22) + +Bugfixes: + + - Fix unhandled rethrown exceptions not reported + +## 0.9.1-0 (2013-10-22) + +Features: + + - Improve performance of `Promise.try` + - Extend `Promise.try` to accept arguments and ctx to make it more usable in promisification of synchronous functions. + +## 0.9.0-0 (2013-10-18) + +Features: + + - Implement `.bind` and `Promise.bind` + +Bugfixes: + + - Fix `.some()` when argument is a pending promise that later resolves to an array + +## 0.8.5-1 (2013-10-17) + +Features: + + - Enable process wide long stack traces through BLUEBIRD_DEBUG environment variable + +## 0.8.5-0 (2013-10-16) + +Features: + + - Improve performance of all collection methods + +Bugfixes: + + - Fix .finally passing the value to handlers + - Remove kew from benchmarks due to bugs in the library breaking the benchmark + - Fix some bluebird library calls potentially appearing in stack traces + +## 0.8.4-1 (2013-10-15) + +Bugfixes: + + - Fix .pending() call showing in long stack traces + +## 0.8.4-0 (2013-10-15) + +Bugfixes: + + - Fix PromiseArray and its sub-classes swallowing possibly unhandled rejections + +## 0.8.3-3 (2013-10-14) + +Bugfixes: + + - Fix AMD-declaration using named module. + +## 0.8.3-2 (2013-10-14) + +Features: + + - The mortals that can handle it may now release Zalgo by `require("bluebird/zalgo");` + +## 0.8.3-1 (2013-10-14) + +Bugfixes: + + - Fix memory leak when using the same promise to attach handlers over and over again + +## 0.8.3-0 (2013-10-13) + +Features: + + - Add `Promise.props()` and `Promise.prototype.props()`. They work like `.all()` for object properties. + +Bugfixes: + + - Fix bug with .some returning garbage when sparse arrays have rejections + +## 0.8.2-2 (2013-10-13) + +Features: + + - Improve performance of `.reduce()` when `initialValue` can be synchronously cast to a value + +## 0.8.2-1 (2013-10-12) + +Bugfixes: + + - Fix .npmignore having irrelevant files + +## 0.8.2-0 (2013-10-12) + +Features: + + - Improve performance of `.some()` + +## 0.8.1-0 (2013-10-11) + +Bugfixes: + + - Remove uses of dynamic evaluation (`new Function`, `eval` etc) when strictly not necessary. Use feature detection to use static evaluation to avoid errors when dynamic evaluation is prohibited. + +## 0.8.0-3 (2013-10-10) + +Features: + + - Add `.asCallback` property to `PromiseResolver`s + +## 0.8.0-2 (2013-10-10) + +## 0.8.0-1 (2013-10-09) + +Features: + + - Improve overall performance. Be able to sustain infinite recursion when using promises. + +## 0.8.0-0 (2013-10-09) + +Bugfixes: + + - Fix stackoverflow error when function calls itself "synchronously" from a promise handler + +## 0.7.12-2 (2013-10-09) + +Bugfixes: + + - Fix safari 6 not using `MutationObserver` as a scheduler + - Fix process exceptions interfering with internal queue flushing + +## 0.7.12-1 (2013-10-09) + +Bugfixes: + + - Don't try to detect if generators are available to allow shims to be used + +## 0.7.12-0 (2013-10-08) + +Features: + + - Promisification now consider all functions on the object and its prototype chain + - Individual promisifcation uses current `this` if no explicit receiver is given + - Give better stack traces when promisified callbacks throw or errback primitives such as strings by wrapping them in an `Error` object. + +Bugfixes: + + - Fix runtime APIs throwing synchronous errors + +## 0.7.11-0 (2013-10-08) + +Features: + + - Deprecate `Promise.promisify(Object target)` in favor of `Promise.promisifyAll(Object target)` to avoid confusion with function objects + - Coroutines now throw error when a non-promise is `yielded` + +## 0.7.10-1 (2013-10-05) + +Features: + + - Make tests pass Internet Explorer 8 + +## 0.7.10-0 (2013-10-05) + +Features: + + - Create browser tests + +## 0.7.9-1 (2013-10-03) + +Bugfixes: + + - Fix promise cast bug when thenable fulfills using itself as the fulfillment value + +## 0.7.9-0 (2013-10-03) + +Features: + + - More performance improvements when long stack traces are enabled + +## 0.7.8-1 (2013-10-02) + +Features: + + - Performance improvements when long stack traces are enabled + +## 0.7.8-0 (2013-10-02) + +Bugfixes: + + - Fix promisified methods not turning synchronous exceptions into rejections + +## 0.7.7-1 (2013-10-02) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.7-0 (2013-10-01) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.6-0 (2013-09-29) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.5-0 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.4-1 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.4-0 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.3-1 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.3-0 (2013-09-27) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.2-0 (2013-09-27) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-5 (2013-09-26) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-4 (2013-09-25) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-3 (2013-09-25) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-2 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-1 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-0 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.0-1 (2013-09-23) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.0-0 (2013-09-23) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-2 (2013-09-20) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-1 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-0 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.4-1 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.4-0 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-4 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-3 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-2 (2013-09-16) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-1 (2013-09-16) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-0 (2013-09-15) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.2-1 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.2-0 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.1-0 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.0-0 (2013-09-13) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-6 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-5 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-4 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-3 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-2 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-1 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.8-1 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.8-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.7-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.6-1 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.6-0 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.5-1 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.5-0 (2013-09-09) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.4-1 (2013-09-08) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.4-0 (2013-09-08) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.3-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.2-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.1-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.0-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.4.0-0 (2013-09-06) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.3.0-1 (2013-09-06) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.3.0 (2013-09-06) diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js new file mode 100644 index 0000000..69a6ffd --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js @@ -0,0 +1,5105 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2014 Petka Antonov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions:

+ * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +/** + * bluebird build version 2.9.26 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers +*/ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + } +}; + +Async.prototype._getDomain = function() {}; + +if (!true) { +if (util.isNode) { + var EventsModule = _dereq_("events"); + + var domainGetter = function() { + var domain = process.domain; + if (domain === null) return undefined; + return domain; + }; + + if (EventsModule.usingDomains) { + Async.prototype._getDomain = domainGetter; + } else { + var descriptor = + Object.getOwnPropertyDescriptor(EventsModule, "usingDomains"); + + if (descriptor) { + if (!descriptor.configurable) { + process.on("domainsActivated", function() { + Async.prototype._getDomain = domainGetter; + }); + } else { + var usingDomains = false; + Object.defineProperty(EventsModule, "usingDomains", { + configurable: false, + enumerable: true, + get: function() { + return usingDomains; + }, + set: function(value) { + if (usingDomains || !value) return; + usingDomains = true; + Async.prototype._getDomain = domainGetter; + util.toFastProperties(process); + process.emit("domainsActivated"); + } + }); + } + } + } +} +} + +function AsyncInvokeLater(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + var domain = this._getDomain(); + if (domain !== undefined) { + var fn = domain.bind(promise._settlePromises); + this._normalQueue.push(fn, promise, undefined); + } else { + this._normalQueue._pushOne(promise); + } + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 0); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + setTimeout(function() { + promise._settlePromises(); + }, 0); + } + }; +} + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = new Async(); +module.exports.firstLineError = firstLineError; + +},{"./queue.js":28,"./schedule.js":31,"./util.js":38,"events":39}],3:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + this._setBoundTo(thisArg); + if (this._isPending()) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, ret._progress, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, ret._progress, ret, context); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 131072; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~131072); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.bind = function (thisArg, value) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + + if (maybePromise instanceof Promise) { + maybePromise._then(function(thisArg) { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + }, ret._reject, ret._progress, ret, null); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + } + return ret; +}; +}; + +},{}],4:[function(_dereq_,module,exports){ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = _dereq_("./promise.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; + +},{"./promise.js":23}],5:[function(_dereq_,module,exports){ +"use strict"; +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} + +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!true) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; + } + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; + } + } + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + if (!true) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } + } + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; + +function namedGetter(obj) { + return obj[this]; +} +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; + +},{"./util.js":38}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var errors = _dereq_("./errors.js"); +var async = _dereq_("./async.js"); +var CancellationError = errors.CancellationError; + +Promise.prototype._cancel = function (reason) { + if (!this.isCancellable()) return this; + var parent; + var promiseToReject = this; + while ((parent = promiseToReject._cancellationParent) !== undefined && + parent.isCancellable()) { + promiseToReject = parent; + } + this._unsetCancellable(); + promiseToReject._target()._rejectCallback(reason, false, true); +}; + +Promise.prototype.cancel = function (reason) { + if (!this.isCancellable()) return this; + if (reason === undefined) reason = new CancellationError(); + async.invokeLater(this._cancel, this, reason); + return this; +}; + +Promise.prototype.cancellable = function () { + if (this._cancellable()) return this; + async.enableTrampoline(); + this._setCancellable(); + this._cancellationParent = undefined; + return this; +}; + +Promise.prototype.uncancellable = function () { + var ret = this.then(); + ret._unsetCancellable(); + return ret; +}; + +Promise.prototype.fork = function (didFulfill, didReject, didProgress) { + var ret = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + + ret._setCancellable(); + ret._cancellationParent = undefined; + return ret; +}; +}; + +},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var warn; + +function CapturedTrace(parent) { + this._parent = parent; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.parent = function() { + return this._parent; +}; + +CapturedTrace.prototype.hasParent = function() { + return this._parent !== undefined; +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = CapturedTrace.parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = stackFramePattern.test(line) || + " (No stack trace)" === line; + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +CapturedTrace.parseStackAndMessage = function(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +}; + +CapturedTrace.formatAndLogError = function(error, title) { + if (typeof console !== "undefined") { + var message; + if (typeof error === "object" || typeof error === "function") { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof warn === "function") { + warn(message); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +}; + +CapturedTrace.unhandledRejection = function (reason) { + CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: "); +}; + +CapturedTrace.isSupported = function () { + return typeof captureStackTrace === "function"; +}; + +CapturedTrace.fireRejectionEvent = +function(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); + } + } + + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + } +}; + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj.toString(); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} +CapturedTrace.setBounds = function(firstLineError, lastLineError) { + if (!CapturedTrace.isSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow) { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); + } + }; + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; + } + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); + } + return true; + }; + } +})(); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + warn = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + warn = function(message) { + process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + warn = function(message) { + console.warn("%c" + message, "color: red"); + }; + } +} + +return CapturedTrace; +}; + +},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util.js"); +var errors = _dereq_("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = _dereq_("./es5.js").keys; +var TypeError = errors.TypeError; + +function CatchFilter(instances, callback, promise) { + this._instances = instances; + this._callback = callback; + this._promise = promise; +} + +function safePredicate(predicate, e) { + var safeObject = {}; + var retfilter = tryCatch(predicate).call(safeObject, e); + + if (retfilter === errorObj) return retfilter; + + var safeKeys = keys(safeObject); + if (safeKeys.length) { + errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); + return errorObj; + } + return retfilter; +} + +CatchFilter.prototype.doFilter = function (e) { + var cb = this._callback; + var promise = this._promise; + var boundTo = promise._boundTo; + for (var i = 0, len = this._instances.length; i < len; ++i) { + var item = this._instances[i]; + var itemIsErrorType = item === Error || + (item != null && item.prototype instanceof Error); + + if (itemIsErrorType && e instanceof item) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } else if (typeof item === "function" && !itemIsErrorType) { + var shouldHandle = safePredicate(item, e); + if (shouldHandle === errorObj) { + e = errorObj.e; + break; + } else if (shouldHandle) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } + } + } + NEXT_FILTER.e = e; + return NEXT_FILTER; +}; + +return CatchFilter; +}; + +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace, isDebugging) { +var contextStack = []; +function Context() { + this._trace = new CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.pop(); + } +}; + +function createContext() { + if (isDebugging()) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} + +Promise.prototype._peekContext = peekContext; +Promise.prototype._pushContext = Context.prototype._pushContext; +Promise.prototype._popContext = Context.prototype._popContext; + +return createContext; +}; + +},{}],10:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var async = _dereq_("./async.js"); +var Warning = _dereq_("./errors.js").Warning; +var util = _dereq_("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +if (debugging) { + async.disableTrampolineIfNecessary(); +} + +Promise.prototype._ensurePossibleRejectionHandled = function () { + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + CapturedTrace.fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._getCarriedStackTrace() || this._settledValue; + this._setUnhandledRejectionIsNotified(); + CapturedTrace.fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 524288; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~524288); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 524288) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 2097152; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~2097152); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 2097152) > 0; +}; + +Promise.prototype._setCarriedStackTrace = function (capturedTrace) { + this._bitField = this._bitField | 1048576; + this._fulfillmentHandler0 = capturedTrace; +}; + +Promise.prototype._isCarryingStackTrace = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._getCarriedStackTrace = function () { + return this._isCarryingStackTrace() + ? this._fulfillmentHandler0 + : undefined; +}; + +Promise.prototype._captureStackTrace = function () { + if (debugging) { + this._trace = new CapturedTrace(this._peekContext()); + } + return this; +}; + +Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { + if (debugging && canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = CapturedTrace.parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +}; + +Promise.prototype._warn = function(message) { + var warning = new Warning(message); + var ctx = this._peekContext(); + if (ctx) { + ctx.attachExtraTrace(warning); + } else { + var parsed = CapturedTrace.parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + CapturedTrace.formatAndLogError(warning, ""); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + unhandledRejectionHandled = typeof fn === "function" ? fn : undefined; +}; + +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && + debugging === false + ) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); + } + debugging = CapturedTrace.isSupported(); + if (debugging) { + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; + +},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util.js"); +var isPrimitive = util.isPrimitive; +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; + +module.exports = function(Promise) { +var returner = function () { + return this; +}; +var thrower = function () { + throw this; +}; +var returnUndefined = function() {}; +var throwUndefined = function() { + throw undefined; +}; + +var wrapper = function (value, action) { + if (action === 1) { + return function () { + throw value; + }; + } else if (action === 2) { + return function () { + return value; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value === undefined) return this.then(returnUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; + +},{"./util.js":38}],12:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, null, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, null, INTERNAL); +}; +}; + +},{}],13:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util.js"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} + +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; + + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + +} +inherits(OperationalError, Error); + +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; + +},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} + +},{}],15:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseMap = Promise.map; + +Promise.prototype.filter = function (fn, options) { + return PromiseMap(this, fn, options, INTERNAL); +}; + +Promise.filter = function (promises, fn, options) { + return PromiseMap(promises, fn, options, INTERNAL); +}; +}; + +},{}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = _dereq_("./util.js"); +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, reasonOrValue, + promise.isFulfilled()); + } + } + + if (promise.isRejected()) { + NEXT_FILTER.e = reasonOrValue; + return NEXT_FILTER; + } else { + return reasonOrValue; + } +} + +function tapHandler(value) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo, value) + : handler(value); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, value, true); + } + } + return value; +} + +Promise.prototype._passThroughHandler = function (handler, isFinally) { + if (typeof handler !== "function") return this.then(); + + var promiseAndHandler = { + promise: this, + handler: handler + }; + + return this._then( + isFinally ? finallyHandler : tapHandler, + isFinally ? finallyHandler : undefined, undefined, + promiseAndHandler, undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThroughHandler(handler, true); +}; + +Promise.prototype.tap = function (handler) { + return this._passThroughHandler(handler, false); +}; +}; + +},{"./util.js":38}],17:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = _dereq_("./errors.js"); +var TypeError = errors.TypeError; +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; +} + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._next(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + if (result === errorObj) { + return this._promise._rejectCallback(result.e, false, true); + } + + var value = result.value; + if (result.done === true) { + this._promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._throw( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise._then( + this._next, + this._throw, + undefined, + this, + null + ); + } +}; + +PromiseSpawn.prototype._throw = function (reason) { + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._next = function (value) { + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + spawn._generator = generator; + spawn._next(undefined); + return spawn.promise(); + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; + +},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!true) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var caller = function(count) { + var values = []; + for (var i = 1; i <= count; ++i) values.push("holder.p" + i); + return new Function("holder", " \n\ + 'use strict'; \n\ + var callback = holder.fn; \n\ + return callback(values); \n\ + ".replace(/values/g, values.join(", "))); + }; + var thenCallbacks = []; + var callers = [undefined]; + for (var i = 1; i <= 5; ++i) { + thenCallbacks.push(thenCallback(i)); + callers.push(caller(i)); + } + + var Holder = function(total, fn) { + this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; + this.fn = fn; + this.total = total; + this.now = 0; + }; + + Holder.prototype.callers = callers; + Holder.prototype.checkFulfillment = function(promise) { + var now = this.now; + now++; + var total = this.total; + if (now >= total) { + var handler = this.callers[total]; + promise._pushContext(); + var ret = tryCatch(handler)(this); + promise._popContext(); + if (ret === errorObj) { + promise._rejectCallback(ret.e, false, true); + } else { + promise._resolveCallback(ret); + } + } else { + this.now = now; + } + }; + + var reject = function (reason) { + this._reject(reason); + }; +} +} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!true) { + if (last < 6 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var holder = new Holder(last, fn); + var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + } else if (maybePromise._isFulfilled()) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else { + ret._reject(maybePromise._reason()); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + return ret; + } + } + } + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; + +},{"./util.js":38}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var PENDING = {}; +var EMPTY_ARRAY = []; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._callback = fn; + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + async.invoke(init, this, undefined); +} +util.inherits(MappingPromiseArray, PromiseArray); +function init() {this._init$(undefined, -2);} + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + if (values[index] === PENDING) { + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return; + } + if (preservedValues !== null) preservedValues[index] = value; + + var callback = this._callback; + var receiver = this._promise._boundTo; + this._promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + this._promise._popContext(); + if (ret === errorObj) return this._reject(ret.e); + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + if (limit >= 1) this._inFlight++; + values[index] = PENDING; + return maybePromise._proxyPromiseArray(this, index); + } else if (maybePromise._isFulfilled()) { + ret = maybePromise._value(); + } else { + return this._reject(maybePromise._reason()); + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + + } +}; + +MappingPromiseArray.prototype._drainQueue = function () { + var queue = this._queue; + var limit = this._limit; + var values = this._values; + while (queue.length > 0 && this._inFlight < limit) { + if (this._isResolved()) return; + var index = queue.pop(); + this._promiseFulfilled(values[index], index); + } +}; + +MappingPromiseArray.prototype._filter = function (booleans, values) { + var len = values.length; + var ret = new Array(len); + var j = 0; + for (var i = 0; i < len; ++i) { + if (booleans[i]) ret[j++] = values[i]; + } + ret.length = j; + this._resolve(ret); +}; + +MappingPromiseArray.prototype.preservedValues = function () { + return this._preservedValues; +}; + +function map(promises, fn, options, _filter) { + var limit = typeof options === "object" && options !== null + ? options.concurrency + : 0; + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter); +} + +Promise.prototype.map = function (fn, options) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + + return map(this, fn, options, null).promise(); +}; + +Promise.map = function (promises, fn, options, _filter) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + return map(promises, fn, options, _filter).promise(); +}; + + +}; + +},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn, args, ctx) { + if (typeof fn !== "function") { + return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = util.isArray(args) + ? tryCatch(fn).apply(ctx, args) + : tryCatch(fn).call(ctx, args); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false, true); + } else { + this._resolveCallback(value, true); + } +}; +}; + +},{"./util.js":38}],21:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundTo; + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var target = promise._target(); + var newReason = target._getCarriedStackTrace(); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundTo, reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = +Promise.prototype.nodeify = function (nodeback, options) { + if (typeof nodeback == "function") { + var adapter = successAdapter; + if (options !== undefined && Object(options).spread) { + adapter = spreadAdapter; + } + this._then( + adapter, + errorAdapter, + undefined, + this, + nodeback + ); + } + return this; +}; +}; + +},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +Promise.prototype.progressed = function (handler) { + return this._then(undefined, undefined, handler, undefined, undefined); +}; + +Promise.prototype._progress = function (progressValue) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._target()._progressUnchecked(progressValue); + +}; + +Promise.prototype._progressHandlerAt = function (index) { + return index === 0 + ? this._progressHandler0 + : this[(index << 2) + index - 5 + 2]; +}; + +Promise.prototype._doProgressWith = function (progression) { + var progressValue = progression.value; + var handler = progression.handler; + var promise = progression.promise; + var receiver = progression.receiver; + + var ret = tryCatch(handler).call(receiver, progressValue); + if (ret === errorObj) { + if (ret.e != null && + ret.e.name !== "StopProgressPropagation") { + var trace = util.canAttachTrace(ret.e) + ? ret.e : new Error(util.toString(ret.e)); + promise._attachExtraTrace(trace); + promise._progress(ret.e); + } + } else if (ret instanceof Promise) { + ret._then(promise._progress, null, null, promise, undefined); + } else { + promise._progress(ret); + } +}; + + +Promise.prototype._progressUnchecked = function (progressValue) { + var len = this._length(); + var progress = this._progress; + for (var i = 0; i < len; i++) { + var handler = this._progressHandlerAt(i); + var promise = this._promiseAt(i); + if (!(promise instanceof Promise)) { + var receiver = this._receiverAt(i); + if (typeof handler === "function") { + handler.call(receiver, progressValue, promise); + } else if (receiver instanceof PromiseArray && + !receiver._isResolved()) { + receiver._promiseProgressed(progressValue, promise); + } + continue; + } + + if (typeof handler === "function") { + async.invoke(this._doProgressWith, this, { + handler: handler, + promise: promise, + receiver: this._receiverAt(i), + value: progressValue + }); + } else { + async.invoke(progress, promise, progressValue); + } + } +}; +}; + +},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); +}; +var reflect = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var errors = _dereq_("./errors.js"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {e: null}; +var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = _dereq_("./captured_trace.js")(); +var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + _dereq_("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = _dereq_("./promise_resolver.js"); +var nodebackForPromise = PromiseResolver._nodebackForPromise; +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function Promise(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); + } + if (this.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._progressHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._settledValue = undefined; + if (resolver !== INTERNAL) this._resolveFromResolver(resolver); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (typeof item === "function") { + catchInstances[j++] = item; + } else { + return Promise.reject( + new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); + } + } + catchInstances.length = j; + fn = arguments[i]; + var catchFilter = new CatchFilter(catchInstances, fn, this); + return this._then(undefined, catchFilter.doFilter, undefined, + catchFilter, undefined); + } + return this._then(undefined, fn, undefined, undefined, undefined); +}; + +Promise.prototype.reflect = function () { + return this._then(reflect, reflect, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject, didProgress) { + if (isDebugging() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, didProgress, + undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject, didProgress) { + var promise = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (didFulfill, didReject) { + return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); +}; + +Promise.prototype.isCancellable = function () { + return !this.isResolved() && + this._cancellable(); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = function(fn) { + var ret = new Promise(INTERNAL); + var result = tryCatch(fn)(nodebackForPromise(ret)); + if (result === errorObj) { + ret._rejectCallback(result.e, true, true); + } + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.defer = Promise.pending = function () { + var promise = new Promise(INTERNAL); + return new PromiseResolver(promise); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + var val = ret; + ret = new Promise(INTERNAL); + ret._fulfillUnchecked(val); + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + didProgress, + receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var ret = haveInternalData ? internalData : new Promise(INTERNAL); + + if (!haveInternalData) { + ret._propagateFrom(this, 4 | 1); + ret._captureStackTrace(); + } + + var target = this._target(); + if (target !== this) { + if (receiver === undefined) receiver = this._boundTo; + if (!haveInternalData) ret._setIsMigrated(); + } + + var callbackIndex = + target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); + + if (target._isResolved() && !target._isSettlePromisesQueued()) { + async.invoke( + target._settlePromiseAtPostResolution, target, callbackIndex); + } + + return ret; +}; + +Promise.prototype._settlePromiseAtPostResolution = function (index) { + if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); + this._settlePromiseAt(index); +}; + +Promise.prototype._length = function () { + return this._bitField & 131071; +}; + +Promise.prototype._isFollowingOrFulfilledOrRejected = function () { + return (this._bitField & 939524096) > 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 536870912) === 536870912; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -131072) | + (len & 131071); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 536870912; +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 33554432; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 33554432) > 0; +}; + +Promise.prototype._cancellable = function () { + return (this._bitField & 67108864) > 0; +}; + +Promise.prototype._setCancellable = function () { + this._bitField = this._bitField | 67108864; +}; + +Promise.prototype._unsetCancellable = function () { + this._bitField = this._bitField & (~67108864); +}; + +Promise.prototype._setIsMigrated = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._unsetIsMigrated = function () { + this._bitField = this._bitField & (~4194304); +}; + +Promise.prototype._isMigrated = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 + ? this._receiver0 + : this[ + index * 5 - 5 + 4]; + if (ret === undefined && this._isBound()) { + return this._boundTo; + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return index === 0 + ? this._promise0 + : this[index * 5 - 5 + 3]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return index === 0 + ? this._fulfillmentHandler0 + : this[index * 5 - 5 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return index === 0 + ? this._rejectionHandler0 + : this[index * 5 - 5 + 1]; +}; + +Promise.prototype._migrateCallbacks = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var progress = follower._progressHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (promise instanceof Promise) promise._setIsMigrated(); + this._addCallbacks(fulfill, reject, progress, promise, receiver); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + progress, + promise, + receiver +) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + if (receiver !== undefined) this._receiver0 = receiver; + if (typeof fulfill === "function" && !this._isCarryingStackTrace()) + this._fulfillmentHandler0 = fulfill; + if (typeof reject === "function") this._rejectionHandler0 = reject; + if (typeof progress === "function") this._progressHandler0 = progress; + } else { + var base = index * 5 - 5; + this[base + 3] = promise; + this[base + 4] = receiver; + if (typeof fulfill === "function") + this[base + 0] = fulfill; + if (typeof reject === "function") + this[base + 1] = reject; + if (typeof progress === "function") + this[base + 2] = progress; + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + if (index === 0) { + this._promise0 = promiseSlotValue; + this._receiver0 = receiver; + } else { + var base = index * 5 - 5; + this[base + 3] = promiseSlotValue; + this[base + 4] = receiver; + } + this._setLength(index + 1); +}; + +Promise.prototype._proxyPromiseArray = function (promiseArray, index) { + this._setProxyHandlers(promiseArray, index); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (this._isFollowingOrFulfilledOrRejected()) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false, true); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + var propagationFlags = 1 | (shouldBind ? 4 : 0); + this._propagateFrom(maybePromise, propagationFlags); + var promise = maybePromise._target(); + if (promise._isPending()) { + var len = this._length(); + for (var i = 0; i < len; ++i) { + promise._migrateCallbacks(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (promise._isFulfilled()) { + this._fulfillUnchecked(promise._value()); + } else { + this._rejectUnchecked(promise._reason(), + promise._getCarriedStackTrace()); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { + if (!shouldNotMarkOriginatingFromRejection) { + util.markAsOriginatingFromRejection(reason); + } + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, hasStack ? undefined : trace); +}; + +Promise.prototype._resolveFromResolver = function (resolver) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = tryCatch(resolver)(function(value) { + if (promise === null) return; + promise._resolveCallback(value); + promise = null; + }, function (reason) { + if (promise === null) return; + promise._rejectCallback(reason, synchronous); + promise = null; + }); + synchronous = false; + this._popContext(); + + if (r !== undefined && r === errorObj && promise !== null) { + promise._rejectCallback(r.e, true, true); + promise = null; + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + if (promise._isRejected()) return; + promise._pushContext(); + var x; + if (receiver === APPLY && !this._isRejected()) { + x = tryCatch(handler).apply(this._boundTo, value); + } else { + x = tryCatch(handler).call(receiver, value); + } + promise._popContext(); + + if (x === errorObj || x === promise || x === NEXT_FILTER) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false, true); + } else { + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._cleanValues = function () { + if (this._cancellable()) { + this._cancellationParent = undefined; + } +}; + +Promise.prototype._propagateFrom = function (parent, flags) { + if ((flags & 1) > 0 && parent._cancellable()) { + this._setCancellable(); + this._cancellationParent = parent; + } + if ((flags & 4) > 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +}; + +Promise.prototype._fulfill = function (value) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._fulfillUnchecked(value); +}; + +Promise.prototype._reject = function (reason, carriedStackTrace) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._rejectUnchecked(reason, carriedStackTrace); +}; + +Promise.prototype._settlePromiseAt = function (index) { + var promise = this._promiseAt(index); + var isPromise = promise instanceof Promise; + + if (isPromise && promise._isMigrated()) { + promise._unsetIsMigrated(); + return async.invoke(this._settlePromiseAt, this, index); + } + var handler = this._isFulfilled() + ? this._fulfillmentHandlerAt(index) + : this._rejectionHandlerAt(index); + + var carriedStackTrace = + this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; + var value = this._settledValue; + var receiver = this._receiverAt(index); + + + this._clearCallbackDataAtIndex(index); + + if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof PromiseArray) { + if (!receiver._isResolved()) { + if (this._isFulfilled()) { + receiver._promiseFulfilled(value, promise); + } + else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (this._isFulfilled()) { + promise._fulfill(value); + } else { + promise._reject(value, carriedStackTrace); + } + } + + if (index >= 4 && (index & 31) === 4) + async.invokeLater(this._setLength, this, 0); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + if (index === 0) { + if (!this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = undefined; + } + this._rejectionHandler0 = + this._progressHandler0 = + this._receiver0 = + this._promise0 = undefined; + } else { + var base = index * 5 - 5; + this[base + 3] = + this[base + 4] = + this[base + 0] = + this[base + 1] = + this[base + 2] = undefined; + } +}; + +Promise.prototype._isSettlePromisesQueued = function () { + return (this._bitField & + -1073741824) === -1073741824; +}; + +Promise.prototype._setSettlePromisesQueued = function () { + this._bitField = this._bitField | -1073741824; +}; + +Promise.prototype._unsetSettlePromisesQueued = function () { + this._bitField = this._bitField & (~-1073741824); +}; + +Promise.prototype._queueSettlePromises = function() { + async.settlePromises(this); + this._setSettlePromisesQueued(); +}; + +Promise.prototype._fulfillUnchecked = function (value) { + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err, undefined); + } + this._setFulfilled(); + this._settledValue = value; + this._cleanValues(); + + if (this._length() > 0) { + this._queueSettlePromises(); + } +}; + +Promise.prototype._rejectUncheckedCheckError = function (reason) { + var trace = util.ensureErrorObject(reason); + this._rejectUnchecked(reason, trace === reason ? undefined : trace); +}; + +Promise.prototype._rejectUnchecked = function (reason, trace) { + if (reason === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err); + } + this._setRejected(); + this._settledValue = reason; + this._cleanValues(); + + if (this._isFinal()) { + async.throwLater(function(e) { + if ("stack" in e) { + async.invokeFirst( + CapturedTrace.unhandledRejection, undefined, e); + } + throw e; + }, trace === undefined ? reason : trace); + return; + } + + if (trace !== undefined && trace !== reason) { + this._setCarriedStackTrace(trace); + } + + if (this._length() > 0) { + this._queueSettlePromises(); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._settlePromises = function () { + this._unsetSettlePromisesQueued(); + var len = this._length(); + for (var i = 0; i < len; i++) { + this._settlePromiseAt(i); + } +}; + +Promise._makeSelfResolutionError = makeSelfResolutionError; +_dereq_("./progress.js")(Promise, PromiseArray); +_dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +_dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +_dereq_("./direct_resolve.js")(Promise); +_dereq_("./synchronous_inspection.js")(Promise); +_dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./cancel.js')(Promise); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +_dereq_('./nodeify.js')(Promise); +_dereq_('./call_get.js')(Promise); +_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./settle.js')(Promise, PromiseArray); +_dereq_('./some.js')(Promise, PromiseArray, apiRejection); +_dereq_('./promisify.js')(Promise, INTERNAL); +_dereq_('./any.js')(Promise); +_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./timers.js')(Promise, INTERNAL); +_dereq_('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._progressHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + p._settledValue = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + CapturedTrace.setBounds(async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = _dereq_("./util.js"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + var parent; + if (values instanceof Promise) { + parent = values; + promise._propagateFrom(parent, 1 | 4); + } + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + this._values = values; + if (values._isFulfilled()) { + values = values._value(); + if (!isArray(values)) { + var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + this.__hardReject__(err); + return; + } + } else if (values._isPending()) { + values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + return; + } else { + this._reject(values._reason()); + return; + } + } else if (!isArray(values)) { + this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var promise = this._promise; + for (var i = 0; i < len; ++i) { + var isResolved = this._isResolved(); + var maybePromise = tryConvertToPromise(values[i], promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (isResolved) { + maybePromise._unsetRejectionIsUnhandled(); + } else if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, i); + } else if (maybePromise._isFulfilled()) { + this._promiseFulfilled(maybePromise._value(), i); + } else { + this._promiseRejected(maybePromise._reason(), i); + } + } else if (!isResolved) { + this._promiseFulfilled(maybePromise, i); + } + } +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype.__hardReject__ = +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false, true); +}; + +PromiseArray.prototype._promiseProgressed = function (progressValue, index) { + this._promise._progress({ + index: index, + value: progressValue + }); +}; + + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +PromiseArray.prototype._promiseRejected = function (reason, index) { + this._totalResolved++; + this._reject(reason); +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util.js":38}],25:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = _dereq_("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = _dereq_("./es5.js"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise) { + return function(err, value) { + if (promise === null) return; + + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (arguments.length > 2) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + promise._fulfill(args); + } else { + promise._fulfill(value); + } + + promise = null; + }; +} + + +var PromiseResolver; +if (!haveGetters) { + PromiseResolver = function (promise) { + this.promise = promise; + this.asCallback = nodebackForPromise(promise); + this.callback = this.asCallback; + }; +} +else { + PromiseResolver = function (promise) { + this.promise = promise; + }; +} +if (haveGetters) { + var prop = { + get: function() { + return nodebackForPromise(this.promise); + } + }; + es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); + es5.defineProperty(PromiseResolver.prototype, "callback", prop); +} + +PromiseResolver._nodebackForPromise = nodebackForPromise; + +PromiseResolver.prototype.toString = function () { + return "[object PromiseResolver]"; +}; + +PromiseResolver.prototype.resolve = +PromiseResolver.prototype.fulfill = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._resolveCallback(value); +}; + +PromiseResolver.prototype.reject = function (reason) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._rejectCallback(reason); +}; + +PromiseResolver.prototype.progress = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._progress(value); +}; + +PromiseResolver.prototype.cancel = function (err) { + this.promise.cancel(err); +}; + +PromiseResolver.prototype.timeout = function () { + this.reject(new TimeoutError("timeout")); +}; + +PromiseResolver.prototype.isResolved = function () { + return this.promise.isResolved(); +}; + +PromiseResolver.prototype.toJSON = function () { + return this.promise.toJSON(); +}; + +module.exports = PromiseResolver; + +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = _dereq_("./util.js"); +var nodebackForPromise = _dereq_("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = _dereq_("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyPropsPattern = + /^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/; +var defaultFilter = function(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} + +function isPromisified(fn) { + try { + return fn.__isPromisified__ === true; + } + catch (e) { + return false; + } +} + +function hasPromisified(obj, key, suffix) { + var val = util.getDataPropertyOrDefault(obj, key + suffix, + defaultPromisified); + return val ? isPromisified(val) : false; +} +function checkValid(ret, suffix, suffixRegexp) { + for (var i = 0; i < ret.length; i += 2) { + var key = ret[i]; + if (suffixRegexp.test(key)) { + var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); + for (var j = 0; j < ret.length; j += 2) { + if (ret[j] === keyWithoutAsyncSuffix) { + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a" + .replace("%s", suffix)); + } + } + } + } +} + +function promisifiableMethods(obj, suffix, suffixRegexp, filter) { + var keys = util.inheritedDataKeys(obj); + var ret = []; + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var value = obj[key]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} + +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!true) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { + var ret = [likelyArgumentCount]; + var min = Math.max(0, likelyArgumentCount - 1 - 3); + for(var i = likelyArgumentCount - 1; i >= min; --i) { + ret.push(i); + } + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { + ret.push(i); + } + return ret; +}; + +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; + +var parameterCount = function(fn) { + if (typeof fn.length === "number") { + return Math.max(Math.min(fn.length, 1023 + 1), 0); + } + return 0; +}; + +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn) { + var newParameterCount = Math.max(0, parameterCount(fn) - 1); + var argumentOrder = switchCaseArgumentOrder(newParameterCount); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; + + function generateCallForArgumentCount(count) { + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; + } + return ret.replace("{{args}}", args).replace(", ", comma); + } + + function generateArgumentSwitchCase() { + var ret = ""; + for (var i = 0; i < argumentOrder.length; ++i) { + ret += "case " + argumentOrder[i] +":" + + generateCallForArgumentCount(argumentOrder[i]); + } + + ret += " \n\ + default: \n\ + var args = new Array(len + 1); \n\ + var i = 0; \n\ + for (var i = 0; i < len; ++i) { \n\ + args[i] = arguments[i]; \n\ + } \n\ + args[i] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); + return ret; + } + + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "INTERNAL","'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + return promise; \n\ + }; \n\ + ret.__isPromisified__ = true; \n\ + return ret; \n\ + " + .replace("Parameters", parameterDeclaration(newParameterCount)) + .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode))( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + INTERNAL + ); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } + function promisified() { + var _receiver = receiver; + if (receiver === THIS) _receiver = this; + var promise = new Promise(INTERNAL); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; + var fn = nodebackForPromise(promise); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + return promise; + } + promisified.__isPromisified__ = true; + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier) { + var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); + var methods = + promisifiableMethods(obj, suffix, suffixRegexp, filter); + + for (var i = 0, len = methods.length; i < len; i+= 2) { + var key = methods[i]; + var fn = methods[i+1]; + var promisifiedKey = key + suffix; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver) { + return makeNodePromisified(callback, receiver, undefined, callback); +} + +Promise.promisify = function (fn, receiver) { + if (typeof fn !== "function") { + throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + if (isPromisified(fn)) { + return fn; + } + var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + util.copyDescriptors(fn, ret, propsFilter); + return ret; +}; + +Promise.promisifyAll = function (target, options) { + if (typeof target !== "function" && typeof target !== "object") { + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a"); + } + options = Object(options); + var suffix = options.suffix; + if (typeof suffix !== "string") suffix = defaultSuffix; + var filter = options.filter; + if (typeof filter !== "function") filter = defaultFilter; + var promisifier = options.promisifier; + if (typeof promisifier !== "function") promisifier = makeNodePromisified; + + if (!util.isIdentifier(suffix)) { + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); + } + + var keys = util.inheritedDataKeys(target); + for (var i = 0; i < keys.length; ++i) { + var value = target[keys[i]]; + if (keys[i] !== "constructor" && + util.isClass(value)) { + promisifyAll(value.prototype, suffix, filter, promisifier); + promisifyAll(value, suffix, filter, promisifier); + } + } + + return promisifyAll(target, suffix, filter, promisifier); +}; +}; + + +},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var isObject = util.isObject; +var es5 = _dereq_("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; +}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val = {}; + var keyOffset = this.length(); + for (var i = 0, len = this.length(); i < len; ++i) { + val[this._values[i + keyOffset]] = this._values[i]; + } + this._resolve(val); + } +}; + +PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { + this._promise._progress({ + key: this._values[index + this.length()], + value: value + }); +}; + +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; + +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); + + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } + + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 4); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; + +},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; + +},{}],29:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = _dereq_("./util.js").isArray; + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else if (!isArray(promises)) { + return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 4 | 1); + } + var fulfill = ret._fulfill; + var reject = ret._reject; + for (var i = 0, len = promises.length; i < len; ++i) { + var val = promises[i]; + + if (val === undefined && !(i in promises)) { + continue; + } + + Promise.cast(val)._then(fulfill, reject, undefined, ret, null); + } + return ret; +} + +Promise.race = function (promises) { + return race(promises, undefined); +}; + +Promise.prototype.race = function () { + return race(this, undefined); +}; + +}; + +},{"./util.js":38}],30:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +function ReductionPromiseArray(promises, fn, accum, _each) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._preservedValues = _each === INTERNAL ? [] : null; + this._zerothIsAccum = (accum === undefined); + this._gotAccum = false; + this._reducingIndex = (this._zerothIsAccum ? 1 : 0); + this._valuesPhase = undefined; + var maybePromise = tryConvertToPromise(accum, this._promise); + var rejected = false; + var isPromise = maybePromise instanceof Promise; + if (isPromise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, -1); + } else if (maybePromise._isFulfilled()) { + accum = maybePromise._value(); + this._gotAccum = true; + } else { + this._reject(maybePromise._reason()); + rejected = true; + } + } + if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; + this._callback = fn; + this._accum = accum; + if (!rejected) async.invoke(init, this, undefined); +} +function init() { + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._init = function () {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); + } +}; + +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + values[index] = value; + var length = this.length(); + var preservedValues = this._preservedValues; + var isEach = preservedValues !== null; + var gotAccum = this._gotAccum; + var valuesPhase = this._valuesPhase; + var valuesPhaseIndex; + if (!valuesPhase) { + valuesPhase = this._valuesPhase = new Array(length); + for (valuesPhaseIndex=0; valuesPhaseIndex 10) || (version[0] > 0) + ? function(fn) { global.setImmediate(fn); } : process.nextTick; + + if (!schedule) { + if (typeof setImmediate !== "undefined") { + schedule = setImmediate; + } else if (typeof setTimeout !== "undefined") { + schedule = setTimeout; + } else { + schedule = noAsyncScheduler; + } + } +} else if (typeof MutationObserver !== "undefined") { + schedule = function(fn) { + var div = document.createElement("div"); + var observer = new MutationObserver(fn); + observer.observe(div, {attributes: true}); + return function() { div.classList.toggle("foo"); }; + }; + schedule.isStatic = true; +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; + +},{"./util.js":38}],32:[function(_dereq_,module,exports){ +"use strict"; +module.exports = + function(Promise, PromiseArray) { +var PromiseInspection = Promise.PromiseInspection; +var util = _dereq_("./util.js"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 268435456; + ret._settledValue = value; + this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 134217728; + ret._settledValue = reason; + this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return new SettledPromiseArray(this).promise(); +}; +}; + +},{"./util.js":38}],33:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = _dereq_("./util.js"); +var RangeError = _dereq_("./errors.js").RangeError; +var AggregateError = _dereq_("./errors.js").AggregateError; +var isArray = util.isArray; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + this._addFulfilled(value); + if (this._fulfilled() === this.howMany()) { + this._values.length = this.howMany(); + if (this.howMany() === 1 && this._unwrap) { + this._resolve(this._values[0]); + } else { + this._resolve(this._values); + } + } + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + e.push(this._values[i]); + } + this._reject(e); + } +}; + +SomePromiseArray.prototype._fulfilled = function () { + return this._totalResolved; +}; + +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); +}; + +SomePromiseArray.prototype._addRejected = function (reason) { + this._values.push(reason); +}; + +SomePromiseArray.prototype._addFulfilled = function (value) { + this._values[this._totalResolved++] = value; +}; + +SomePromiseArray.prototype._canPossiblyFulfill = function () { + return this.length() - this._rejected(); +}; + +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); +}; + +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; + +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} + +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; + +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; + +Promise._SomePromiseArray = SomePromiseArray; +}; + +},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValue = promise._settledValue; + } + else { + this._bitField = 0; + this._settledValue = undefined; + } +} + +PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.isFulfilled = +Promise.prototype._isFulfilled = function () { + return (this._bitField & 268435456) > 0; +}; + +PromiseInspection.prototype.isRejected = +Promise.prototype._isRejected = function () { + return (this._bitField & 134217728) > 0; +}; + +PromiseInspection.prototype.isPending = +Promise.prototype._isPending = function () { + return (this._bitField & 402653184) === 0; +}; + +PromiseInspection.prototype.isResolved = +Promise.prototype._isResolved = function () { + return (this._bitField & 402653184) > 0; +}; + +Promise.prototype.isPending = function() { + return this._target()._isPending(); +}; + +Promise.prototype.isRejected = function() { + return this._target()._isRejected(); +}; + +Promise.prototype.isFulfilled = function() { + return this._target()._isFulfilled(); +}; + +Promise.prototype.isResolved = function() { + return this._target()._isResolved(); +}; + +Promise.prototype._value = function() { + return this._settledValue; +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue; +}; + +Promise.prototype.value = function() { + var target = this._target(); + if (!target.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return target._settledValue; +}; + +Promise.prototype.reason = function() { + var target = this._target(); + if (!target.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + target._unsetRejectionIsUnhandled(); + return target._settledValue; +}; + + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],35:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) { + return obj; + } + else if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfillUnchecked, + ret._rejectUncheckedCheckError, + ret._progressUnchecked, + ret, + null + ); + return ret; + } + var then = util.tryCatch(getThen)(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + return doThenable(obj, then, context); + } + } + return obj; +} + +function getThen(obj) { + return obj.then; +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, + resolveFromThenable, + rejectFromThenable, + progressFromThenable); + synchronous = false; + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolveFromThenable(value) { + if (!promise) return; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + promise._resolveCallback(value); + } + promise = null; + } + + function rejectFromThenable(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + + function progressFromThenable(value) { + if (!promise) return; + if (typeof promise._progress === "function") { + promise._progress(value); + } + } + return ret; +} + +return tryConvertToPromise; +}; + +},{"./util.js":38}],36:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + if (typeof message !== "string") { + message = "operation timed out"; + } + var err = new TimeoutError(message); + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._cancel(err); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (value, ms) { + if (ms === undefined) { + ms = value; + value = undefined; + var ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, ms); + return ret; + } + ms = +ms; + return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); +}; + +Promise.prototype.delay = function (ms) { + return delay(this, ms); +}; + +function successClear(value) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + return value; +} + +function failureClear(reason) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret = this.then().cancellable(); + ret._cancellationParent = this; + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; + +},{"./util.js":38}],37:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = _dereq_("./errors.js").TypeError; + var inherits = _dereq_("./util.js").inherits; + var PromiseInspection = Promise.PromiseInspection; + + function inspectionMapper(inspections) { + var len = inspections.length; + for (var i = 0; i < len; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + return Promise.reject(inspection.error()); + } + inspections[i] = inspection._settledValue; + } + return inspections; + } + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + if (maybePromise !== thenable && + typeof thenable._isDisposable === "function" && + typeof thenable._getDisposer === "function" && + thenable._isDisposable()) { + maybePromise._setDisposable(thenable._getDisposer()); + } + return maybePromise; + } + function dispose(resources, inspection) { + var i = 0; + var len = resources.length; + var ret = Promise.defer(); + function iterator() { + if (i >= len) return ret.resolve(); + var maybePromise = castPreservingDisposable(resources[i++]); + if (maybePromise instanceof Promise && + maybePromise._isDisposable()) { + try { + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); + } catch (e) { + return thrower(e); + } + if (maybePromise instanceof Promise) { + return maybePromise._then(iterator, thrower, + null, null, null); + } + } + iterator(); + } + iterator(); + return ret.promise; + } + + function disposerSuccess(value) { + var inspection = new PromiseInspection(); + inspection._settledValue = value; + inspection._bitField = 268435456; + return dispose(this, inspection).thenReturn(value); + } + + function disposerFail(reason) { + var inspection = new PromiseInspection(); + inspection._settledValue = reason; + inspection._bitField = 134217728; + return dispose(this, inspection).thenThrow(reason); + } + + function Disposer(data, promise, context) { + this._data = data; + this._promise = promise; + this._context = context; + } + + Disposer.prototype.data = function () { + return this._data; + }; + + Disposer.prototype.promise = function () { + return this._promise; + }; + + Disposer.prototype.resource = function () { + if (this.promise().isFulfilled()) { + return this.promise().value(); + } + return null; + }; + + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== null + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; + + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); + }; + + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); + + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); + }; + + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); + } + return value; + } + + Promise.using = function () { + var len = arguments.length; + if (len < 2) return apiRejection( + "you must pass at least 2 arguments to Promise.using"); + var fn = arguments[len - 1]; + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } + } + resources[i] = resource; + } + + var promise = Promise.settle(resources) + .then(inspectionMapper) + .then(function(vals) { + promise._pushContext(); + var ret; + try { + ret = fn.apply(undefined, vals); + } finally { + promise._popContext(); + } + return ret; + }) + ._then( + disposerSuccess, disposerFail, undefined, resources, undefined); + resources.promise = promise; + return promise; + }; + + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 262144; + this._disposer = disposer; + }; + + Promise.prototype._isDisposable = function () { + return (this._bitField & 262144) > 0; + }; + + Promise.prototype._getDisposer = function () { + return this._disposer; + }; + + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~262144); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); + }; + +}; + +},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var canEvaluate = typeof navigator == "undefined"; +var haveGetters = (function(){ + try { + var o = {}; + es5.defineProperty(o, "f", { + get: function () { + return 3; + } + }); + return o.f === 3; + } + catch (e) { + return false; + } + +})(); + +var errorObj = {e: {}}; +var tryCatchTarget; +function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } + } + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return !isPrimitive(value); +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); +} + +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; +} + +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} + +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; +} + + +var wrapsPrimitiveReceiver = (function() { + return this !== "string"; +}).call("string"); + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + if (es5.isES5) { + var oProto = Object.prototype; + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && obj !== oProto) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function f() {} + f.prototype = obj; + var l = 8; + while (l--) new f(); + return obj; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + haveGetters: haveGetters, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" +}; +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5.js":14}],39:[function(_dereq_,module,exports){ +// 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. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } + throw TypeError('Uncaught, unspecified "error" event.'); + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + handler.apply(this, args); + } + } else if (isObject(handler)) { + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + var m; + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + var ret; + if (!emitter._events || !emitter._events[type]) + ret = 0; + else if (isFunction(emitter._events[type])) + ret = 1; + else + ret = emitter._events[type].length; + return ret; +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}]},{},[4])(4) +}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js new file mode 100644 index 0000000..679f778 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2014 Petka Antonov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions:

+ * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +/** + * bluebird build version 2.9.26 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers +*/ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,r;return function n(t,e,r){function i(s,a){if(!e[s]){if(!t[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=e[s]={exports:{}};t[s][0].call(l.exports,function(e){var r=t[s][1][e];return i(r?r:e)},l,l.exports,n,t,e,r)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0},r.prototype.throwLater=function(t,e){1===arguments.length&&(e=t,t=function(){throw e});var r=this._getDomain();if(void 0!==r&&(t=r.bind(t)),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(n){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")}},r.prototype._getDomain=function(){};l.hasDevTools?(r.prototype.invokeLater=function(t,e,r){this._trampolineEnabled?n.call(this,t,e,r):setTimeout(function(){t.call(e,r)},100)},r.prototype.invoke=function(t,e,r){this._trampolineEnabled?i.call(this,t,e,r):setTimeout(function(){t.call(e,r)},0)},r.prototype.settlePromises=function(t){this._trampolineEnabled?o.call(this,t):setTimeout(function(){t._settlePromises()},0)}):(r.prototype.invokeLater=n,r.prototype.invoke=i,r.prototype.settlePromises=o),r.prototype.invokeFirst=function(t,e,r){var n=this._getDomain();void 0!==n&&(t=n.bind(t)),this._normalQueue.unshift(t,e,r),this._queueTick()},r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var r=t.shift(),n=t.shift();e.call(r,n)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=new r,e.exports.firstLineError=s},{"./queue.js":28,"./schedule.js":31,"./util.js":38,events:39}],3:[function(t,e){"use strict";e.exports=function(t,e,r){var n=function(t,e){this._reject(e)},i=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(n,n,null,this,t)},o=function(t,e){this._setBoundTo(t),this._isPending()&&this._resolveCallback(e.target)},s=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(n){var a=r(n),u=new t(e);u._propagateFrom(this,1);var c=this._target();if(a instanceof t){var l={promiseRejectionQueued:!1,promise:u,target:c,bindingPromise:a};c._then(e,i,u._progress,u,l),a._then(o,s,u._progress,u,l)}else u._setBoundTo(n),u._resolveCallback(c);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=131072|this._bitField,this._boundTo=t):this._bitField=-131073&this._bitField},t.prototype._isBound=function(){return 131072===(131072&this._bitField)},t.bind=function(n,i){var o=r(n),s=new t(e);return o instanceof t?o._then(function(t){s._setBoundTo(t),s._resolveCallback(i)},s._reject,s._progress,s,null):(s._setBoundTo(n),s._resolveCallback(i)),s}}},{}],4:[function(t,e){"use strict";function r(){try{Promise===i&&(Promise=n)}catch(t){}return i}var n;"undefined"!=typeof Promise&&(n=Promise);var i=t("./promise.js")();i.noConflict=r,e.exports=i},{"./promise.js":23}],5:[function(t,e){"use strict";var r=Object.create;if(r){var n=r(null),i=r(null);n[" size"]=i[" size"]=0}e.exports=function(e){function r(t,r){var n;if(null!=t&&(n=t[r]),"function"!=typeof n){var i="Object "+a.classString(t)+" has no method '"+a.toString(r)+"'";throw new e.TypeError(i)}return n}function n(t){var e=this.pop(),n=r(t,e);return n.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}{var s,a=t("./util.js"),u=a.canEvaluate;a.isIdentifier}e.prototype.call=function(t){for(var e=arguments.length,r=new Array(e-1),i=1;e>i;++i)r[i-1]=arguments[i];return r.push(t),this._then(n,void 0,void 0,r,void 0)},e.prototype.get=function(t){var e,r="number"==typeof t;if(r)e=o;else if(u){var n=s(t);e=null!==n?n:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util.js":38}],6:[function(t,e){"use strict";e.exports=function(e){var r=t("./errors.js"),n=t("./async.js"),i=r.CancellationError;e.prototype._cancel=function(t){if(!this.isCancellable())return this;for(var e,r=this;void 0!==(e=r._cancellationParent)&&e.isCancellable();)r=e;this._unsetCancellable(),r._target()._rejectCallback(t,!1,!0)},e.prototype.cancel=function(t){return this.isCancellable()?(void 0===t&&(t=new i),n.invokeLater(this._cancel,this,t),this):this},e.prototype.cancellable=function(){return this._cancellable()?this:(n.enableTrampoline(),this._setCancellable(),this._cancellationParent=void 0,this)},e.prototype.uncancellable=function(){var t=this.then();return t._unsetCancellable(),t},e.prototype.fork=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);return n._setCancellable(),n._cancellationParent=void 0,n}}},{"./async.js":2,"./errors.js":13}],7:[function(t,e){"use strict";e.exports=function(){function e(t){this._parent=t;var r=this._length=1+(void 0===t?0:t._length);j(this,e),r>32&&this.uncycle()}function r(t,e){for(var r=0;r=0;--a)if(n[a]===o){s=a;break}for(var a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}function o(t){for(var e=[],r=0;r0&&(e=e.slice(r)),e}function a(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t.toString();var r=/\[object [a-zA-Z0-9$_]+\]/;if(r.test(e))try{var n=JSON.stringify(t);e=n}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+u(e)+">, no stack trace)"}function u(t){var e=41;return t.lengtht)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;t=this._length=n;for(var n=t-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(var n=0;t>n;++n){var s=e[n].stack,a=r[s];if(void 0!==a&&a!==n){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var u=n>0?e[n-1]:this;t-1>a?(u._parent=e[a+1],u._parent.uncycle(),u._length=u._parent._length+1):(u._parent=void 0,u._length=1);for(var c=u._length+1,l=n-2;l>=0;--l)e[l]._length=c,c++;return}}}},e.prototype.parent=function(){return this._parent},e.prototype.hasParent=function(){return void 0!==this._parent},e.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var s=e.parseStackAndMessage(t),a=s.message,u=[s.stack],c=this;void 0!==c;)u.push(o(c.stack.split("\n"))),c=c._parent;i(u),n(u),p.notEnumerableProp(t,"stack",r(a,u)),p.notEnumerableProp(t,"__stackCleaned__",!0)}},e.parseStackAndMessage=function(t){var e=t.stack,r=t.toString();return e="string"==typeof e&&e.length>0?s(t):[" (No stack trace)"],{message:r,stack:o(e)}},e.formatAndLogError=function(t,e){if("undefined"!=typeof console){var r;if("object"==typeof t||"function"==typeof t){var n=t.stack;r=e+d(n,t)}else r=e+String(t);"function"==typeof l?l(r):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}},e.unhandledRejection=function(t){e.formatAndLogError(t,"^--- With additional stack trace: ")},e.isSupported=function(){return"function"==typeof j},e.fireRejectionEvent=function(t,r,n,i){var o=!1;try{"function"==typeof r&&(o=!0,"rejectionHandled"===t?r(i):r(n,i))}catch(s){h.throwLater(s)}var a=!1;try{a=b(t,n,i)}catch(s){a=!0,h.throwLater(s)}var u=!1;if(m)try{u=m(t.toLowerCase(),{reason:n,promise:i})}catch(s){u=!0,h.throwLater(s)}a||o||u||"unhandledRejection"!==t||e.formatAndLogError(n,"Unhandled rejection ")};var y=function(){return!1},g=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;e.setBounds=function(t,r){if(e.isSupported()){for(var n,i,o=t.stack.split("\n"),s=r.stack.split("\n"),a=-1,u=-1,l=0;la||0>u||!n||!i||n!==i||a>=u||(y=function(t){if(f.test(t))return!0;var e=c(t);return e&&e.fileName===n&&a<=e.line&&e.line<=u?!0:!1})}};var m,j=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():a(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit=Error.stackTraceLimit+6,_=t,d=e;var r=Error.captureStackTrace;return y=function(t){return f.test(t)},function(t,e){Error.stackTraceLimit=Error.stackTraceLimit+6,r(t,e),Error.stackTraceLimit=Error.stackTraceLimit-6}}var n=new Error;if("string"==typeof n.stack&&n.stack.split("\n")[0].indexOf("stackDetection@")>=0)return _=/@/,d=e,v=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in n||!i?(d=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?a(e):e.toString()},null):(_=t,d=e,function(t){Error.stackTraceLimit=Error.stackTraceLimit+6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit=Error.stackTraceLimit-6})}([]),b=function(){if(p.isNode)return function(t,e,r){return"rejectionHandled"===t?process.emit(t,r):process.emit(t,e,r)};var t=!1,e=!0;try{var r=new self.CustomEvent("test");t=r instanceof CustomEvent}catch(n){}if(!t)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(n){e=!1}e&&(m=function(e,r){var n;return t?n=new self.CustomEvent(e,{detail:r,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(n=document.createEvent("CustomEvent"),n.initCustomEvent(e,!1,!0,r)),n?!self.dispatchEvent(n):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,r){var n=o[t],i=self[n];return i?("rejectionHandled"===t?i.call(self,r):i.call(self,e,r),!0):!1}}();return"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(l=function(t){console.warn(t)},p.isNode&&process.stderr.isTTY?l=function(t){process.stderr.write(""+t+"\n")}:p.isNode||"string"!=typeof(new Error).stack||(l=function(t){console.warn("%c"+t,"color: red")})),e}},{"./async.js":2,"./util.js":38}],8:[function(t,e){"use strict";e.exports=function(e){function r(t,e,r){this._instances=t,this._callback=e,this._promise=r}function n(t,e){var r={},n=s(t).call(r,e);if(n===a)return n;var i=u(r);return i.length?(a.e=new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"),a):n}var i=t("./util.js"),o=t("./errors.js"),s=i.tryCatch,a=i.errorObj,u=t("./es5.js").keys,c=o.TypeError;return r.prototype.doFilter=function(t){for(var r=this._callback,i=this._promise,o=i._boundTo,u=0,c=this._instances.length;c>u;++u){var l=this._instances[u],h=l===Error||null!=l&&l.prototype instanceof Error;if(h&&t instanceof l){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}if("function"==typeof l&&!h){var f=n(l,t);if(f===a){t=a.e;break}if(f){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}}}return e.e=t,e},r}},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(t,e){"use strict";e.exports=function(t,e,r){function n(){this._trace=new e(o())}function i(){return r()?new n:void 0}function o(){var t=s.length-1;return t>=0?s[t]:void 0}var s=[];return n.prototype._pushContext=function(){r()&&void 0!==this._trace&&s.push(this._trace)},n.prototype._popContext=function(){r()&&void 0!==this._trace&&s.pop()},t.prototype._peekContext=o,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,i}},{}],10:[function(t,e){"use strict";e.exports=function(e,r){var n,i,o=t("./async.js"),s=t("./errors.js").Warning,a=t("./util.js"),u=a.canAttachTrace,c=!1||a.isNode&&(!!process.env.BLUEBIRD_DEBUG||"development"===process.env.NODE_ENV);return c&&o.disableTrampolineIfNecessary(),e.prototype._ensurePossibleRejectionHandled=function(){this._setRejectionIsUnhandled(),o.invokeLater(this._notifyUnhandledRejection,this,void 0)},e.prototype._notifyUnhandledRejectionIsHandled=function(){r.fireRejectionEvent("rejectionHandled",n,void 0,this)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._getCarriedStackTrace()||this._settledValue;this._setUnhandledRejectionIsNotified(),r.fireRejectionEvent("unhandledRejection",i,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=524288|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-524289&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(524288&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=2097152|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-2097153&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(2097152&this._bitField)>0},e.prototype._setCarriedStackTrace=function(t){this._bitField=1048576|this._bitField,this._fulfillmentHandler0=t},e.prototype._isCarryingStackTrace=function(){return(1048576&this._bitField)>0},e.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0},e.prototype._captureStackTrace=function(){return c&&(this._trace=new r(this._peekContext())),this},e.prototype._attachExtraTrace=function(t,e){if(c&&u(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var i=r.parseStackAndMessage(t);a.notEnumerableProp(t,"stack",i.message+"\n"+i.stack.join("\n")),a.notEnumerableProp(t,"__stackCleaned__",!0)}}},e.prototype._warn=function(t){var e=new s(t),n=this._peekContext();if(n)n.attachExtraTrace(e);else{var i=r.parseStackAndMessage(e);e.stack=i.message+"\n"+i.stack.join("\n")}r.formatAndLogError(e,"")},e.onPossiblyUnhandledRejection=function(t){i="function"==typeof t?t:void 0},e.onUnhandledRejectionHandled=function(t){n="function"==typeof t?t:void 0},e.longStackTraces=function(){if(o.haveItemsQueued()&&c===!1)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/DT1qyG\n");c=r.isSupported(),c&&o.disableTrampolineIfNecessary()},e.hasLongStackTraces=function(){return c&&r.isSupported()},r.isSupported()||(e.longStackTraces=function(){},c=!1),function(){return c}}},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(t,e){"use strict";var r=t("./util.js"),n=r.isPrimitive,i=r.wrapsPrimitiveReceiver;e.exports=function(t){var e=function(){return this},r=function(){throw this},o=function(){},s=function(){throw void 0},a=function(t,e){return 1===e?function(){throw t}:2===e?function(){return t}:void 0};t.prototype["return"]=t.prototype.thenReturn=function(t){return void 0===t?this.then(o):i&&n(t)?this._then(a(t,2),void 0,void 0,void 0,void 0):this._then(e,void 0,void 0,t,void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return void 0===t?this.then(s):i&&n(t)?this._then(a(t,1),void 0,void 0,void 0,void 0):this._then(r,void 0,void 0,t,void 0)}}},{"./util.js":38}],12:[function(t,e){"use strict";e.exports=function(t,e){var r=t.reduce;t.prototype.each=function(t){return r(this,t,null,e)},t.each=function(t,n){return r(t,n,null,e)}}},{}],13:[function(t,e){"use strict";function r(t,e){function r(n){return this instanceof r?(l(this,"message","string"==typeof n?n:e),l(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new r(n)}return c(r,Error),r}function n(t){return this instanceof n?(l(this,"name","OperationalError"),l(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(l(this,"message",t.message),l(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new n(t)}var i,o,s=t("./es5.js"),a=s.freeze,u=t("./util.js"),c=u.inherits,l=u.notEnumerableProp,h=r("Warning","warning"),p=r("CancellationError","cancellation error"),f=r("TimeoutError","timeout error"),_=r("AggregateError","aggregate error");try{i=TypeError,o=RangeError}catch(d){i=r("TypeError","type error"),o=r("RangeError","range error")}for(var v="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y0&&"function"==typeof arguments[e]){t=arguments[e];var n}for(var i=arguments.length,o=new Array(i),s=0;i>s;++s)o[s]=arguments[s];t&&o.pop();var n=new r(o).promise();return void 0!==t?n.spread(t):n}}},{"./util.js":38}],19:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,e,r,n){this.constructor$(t),this._promise._captureStackTrace(),this._callback=e,this._preservedValues=n===o?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=r>=1?[]:_,c.invoke(a,this,void 0)}function a(){this._init$(void 0,-2)}function u(t,e,r,n){var i="object"==typeof r&&null!==r?r.concurrency:0;return i="number"==typeof i&&isFinite(i)&&i>=1?i:0,new s(t,e,i,n)}var c=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj,f={},_=[];l.inherits(s,r),s.prototype._init=function(){},s.prototype._promiseFulfilled=function(t,r){var n=this._values,o=this.length(),s=this._preservedValues,a=this._limit;if(n[r]===f){if(n[r]=t,a>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return}else{if(a>=1&&this._inFlight>=a)return n[r]=t,void this._queue.push(r);null!==s&&(s[r]=t);var u=this._callback,c=this._promise._boundTo;this._promise._pushContext();var l=h(u).call(c,t,r,o);if(this._promise._popContext(),l===p)return this._reject(l.e);var _=i(l,this._promise);if(_ instanceof e){if(_=_._target(),_._isPending())return a>=1&&this._inFlight++,n[r]=f,_._proxyPromiseArray(this,r);if(!_._isFulfilled())return this._reject(_._reason());l=_._value()}n[r]=l}var d=++this._totalResolved;d>=o&&(null!==s?this._filter(n,s):this._resolve(n))},s.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(n[i++]=e[o]);n.length=i,this._resolve(n)},s.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return"function"!=typeof t?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(this,t,e,null).promise()},e.map=function(t,e,r,i){return"function"!=typeof e?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(t,e,r,i).promise()}}},{"./async.js":2,"./util.js":38}],20:[function(t,e){"use strict";e.exports=function(e,r,n,i){var o=t("./util.js"),s=o.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");return function(){var n=new e(r);n._captureStackTrace(),n._pushContext();var i=s(t).apply(this,arguments);return n._popContext(),n._resolveFromSyncValue(i),n}},e.attempt=e["try"]=function(t,n,a){if("function"!=typeof t)return i("fn must be a function\n\n See http://goo.gl/916lJJ\n");var u=new e(r);u._captureStackTrace(),u._pushContext();var c=o.isArray(n)?s(t).apply(a,n):s(t).call(a,n);return u._popContext(),u._resolveFromSyncValue(c),u},e.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1,!0):this._resolveCallback(t,!0)}}},{"./util.js":38}],21:[function(t,e){"use strict";e.exports=function(e){function r(t,e){var r=this;if(!o.isArray(t))return n.call(r,t,e);var i=a(e).apply(r._boundTo,[null].concat(t));i===u&&s.throwLater(i.e)}function n(t,e){var r=this,n=r._boundTo,i=void 0===t?a(e).call(n,null):a(e).call(n,null,t);i===u&&s.throwLater(i.e)}function i(t,e){var r=this;if(!t){var n=r._target(),i=n._getCarriedStackTrace();i.cause=t,t=i}var o=a(e).call(r._boundTo,t);o===u&&s.throwLater(o.e)}var o=t("./util.js"),s=t("./async.js"),a=o.tryCatch,u=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=n;void 0!==e&&Object(e).spread&&(o=r),this._then(o,i,void 0,this,t)}return this}}},{"./async.js":2,"./util.js":38}],22:[function(t,e){"use strict";e.exports=function(e,r){var n=t("./util.js"),i=t("./async.js"),o=n.tryCatch,s=n.errorObj;e.prototype.progressed=function(t){return this._then(void 0,void 0,t,void 0,void 0)},e.prototype._progress=function(t){this._isFollowingOrFulfilledOrRejected()||this._target()._progressUnchecked(t)},e.prototype._progressHandlerAt=function(t){return 0===t?this._progressHandler0:this[(t<<2)+t-5+2]},e.prototype._doProgressWith=function(t){var r=t.value,i=t.handler,a=t.promise,u=t.receiver,c=o(i).call(u,r);if(c===s){if(null!=c.e&&"StopProgressPropagation"!==c.e.name){var l=n.canAttachTrace(c.e)?c.e:new Error(n.toString(c.e));a._attachExtraTrace(l),a._progress(c.e)}}else c instanceof e?c._then(a._progress,null,null,a,void 0):a._progress(c)},e.prototype._progressUnchecked=function(t){for(var n=this._length(),o=this._progress,s=0;n>s;s++){var a=this._progressHandlerAt(s),u=this._promiseAt(s);if(u instanceof e)"function"==typeof a?i.invoke(this._doProgressWith,this,{handler:a,promise:u,receiver:this._receiverAt(s),value:t}):i.invoke(o,u,t);else{var c=this._receiverAt(s);"function"==typeof a?a.call(c,t,u):c instanceof r&&!c._isResolved()&&c._promiseProgressed(t,u)}}}}},{"./async.js":2,"./util.js":38}],23:[function(t,e){"use strict";e.exports=function(){function e(t){if("function"!=typeof t)throw new c("the promise constructor requires a resolver function\n\n See http://goo.gl/EC22Yn\n");if(this.constructor!==e)throw new c("the promise constructor cannot be invoked directly\n\n See http://goo.gl/KsIlge\n");this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._progressHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._settledValue=void 0,t!==l&&this._resolveFromResolver(t)}function r(t){var r=new e(l);r._fulfillmentHandler0=t,r._rejectionHandler0=t,r._progressHandler0=t,r._promise0=t,r._receiver0=t,r._settledValue=t}var n=function(){return new c("circular promise resolution chain\n\n See http://goo.gl/LhFpo0\n")},i=function(){return new e.PromiseInspection(this._target())},o=function(t){return e.reject(new c(t))},s=t("./util.js"),a=t("./async.js"),u=t("./errors.js"),c=e.TypeError=u.TypeError;e.RangeError=u.RangeError,e.CancellationError=u.CancellationError,e.TimeoutError=u.TimeoutError,e.OperationalError=u.OperationalError,e.RejectionError=u.OperationalError,e.AggregateError=u.AggregateError;var l=function(){},h={},p={e:null},f=t("./thenables.js")(e,l),_=t("./promise_array.js")(e,l,f,o),d=t("./captured_trace.js")(),v=t("./debuggability.js")(e,d),y=t("./context.js")(e,d,v),g=t("./catch_filter.js")(p),m=t("./promise_resolver.js"),j=m._nodebackForPromise,b=s.errorObj,w=s.tryCatch;return e.prototype.toString=function(){return"[object Promise]"},e.prototype.caught=e.prototype["catch"]=function(t){var r=arguments.length;if(r>1){var n,i=new Array(r-1),o=0;for(n=0;r-1>n;++n){var s=arguments[n];if("function"!=typeof s)return e.reject(new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"));i[o++]=s}i.length=o,t=arguments[n];var a=new g(i,t,this);return this._then(void 0,a.doFilter,void 0,a,void 0)}return this._then(void 0,t,void 0,void 0,void 0)},e.prototype.reflect=function(){return this._then(i,i,void 0,this,void 0)},e.prototype.then=function(t,e,r){if(v()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+s.classString(t);arguments.length>1&&(n+=", "+s.classString(e)),this._warn(n)}return this._then(t,e,r,void 0,void 0)},e.prototype.done=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);n._setIsFinal()},e.prototype.spread=function(t,e){return this.all()._then(t,e,void 0,h,void 0)},e.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable() +},e.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},e.prototype.all=function(){return new _(this).promise()},e.prototype.error=function(t){return this.caught(s.originatesFromRejection,t)},e.is=function(t){return t instanceof e},e.fromNode=function(t){var r=new e(l),n=w(t)(j(r));return n===b&&r._rejectCallback(n.e,!0,!0),r},e.all=function(t){return new _(t).promise()},e.defer=e.pending=function(){var t=new e(l);return new m(t)},e.cast=function(t){var r=f(t);if(!(r instanceof e)){var n=r;r=new e(l),r._fulfillUnchecked(n)}return r},e.resolve=e.fulfilled=e.cast,e.reject=e.rejected=function(t){var r=new e(l);return r._captureStackTrace(),r._rejectCallback(t,!0),r},e.setScheduler=function(t){if("function"!=typeof t)throw new c("fn must be a function\n\n See http://goo.gl/916lJJ\n");var e=a._schedule;return a._schedule=t,e},e.prototype._then=function(t,r,n,i,o){var s=void 0!==o,u=s?o:new e(l);s||(u._propagateFrom(this,5),u._captureStackTrace());var c=this._target();c!==this&&(void 0===i&&(i=this._boundTo),s||u._setIsMigrated());var h=c._addCallbacks(t,r,n,u,i);return c._isResolved()&&!c._isSettlePromisesQueued()&&a.invoke(c._settlePromiseAtPostResolution,c,h),u},e.prototype._settlePromiseAtPostResolution=function(t){this._isRejectionUnhandled()&&this._unsetRejectionIsUnhandled(),this._settlePromiseAt(t)},e.prototype._length=function(){return 131071&this._bitField},e.prototype._isFollowingOrFulfilledOrRejected=function(){return(939524096&this._bitField)>0},e.prototype._isFollowing=function(){return 536870912===(536870912&this._bitField)},e.prototype._setLength=function(t){this._bitField=-131072&this._bitField|131071&t},e.prototype._setFulfilled=function(){this._bitField=268435456|this._bitField},e.prototype._setRejected=function(){this._bitField=134217728|this._bitField},e.prototype._setFollowing=function(){this._bitField=536870912|this._bitField},e.prototype._setIsFinal=function(){this._bitField=33554432|this._bitField},e.prototype._isFinal=function(){return(33554432&this._bitField)>0},e.prototype._cancellable=function(){return(67108864&this._bitField)>0},e.prototype._setCancellable=function(){this._bitField=67108864|this._bitField},e.prototype._unsetCancellable=function(){this._bitField=-67108865&this._bitField},e.prototype._setIsMigrated=function(){this._bitField=4194304|this._bitField},e.prototype._unsetIsMigrated=function(){this._bitField=-4194305&this._bitField},e.prototype._isMigrated=function(){return(4194304&this._bitField)>0},e.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[5*t-5+4];return void 0===e&&this._isBound()?this._boundTo:e},e.prototype._promiseAt=function(t){return 0===t?this._promise0:this[5*t-5+3]},e.prototype._fulfillmentHandlerAt=function(t){return 0===t?this._fulfillmentHandler0:this[5*t-5+0]},e.prototype._rejectionHandlerAt=function(t){return 0===t?this._rejectionHandler0:this[5*t-5+1]},e.prototype._migrateCallbacks=function(t,r){var n=t._fulfillmentHandlerAt(r),i=t._rejectionHandlerAt(r),o=t._progressHandlerAt(r),s=t._promiseAt(r),a=t._receiverAt(r);s instanceof e&&s._setIsMigrated(),this._addCallbacks(n,i,o,s,a)},e.prototype._addCallbacks=function(t,e,r,n,i){var o=this._length();if(o>=131066&&(o=0,this._setLength(0)),0===o)this._promise0=n,void 0!==i&&(this._receiver0=i),"function"!=typeof t||this._isCarryingStackTrace()||(this._fulfillmentHandler0=t),"function"==typeof e&&(this._rejectionHandler0=e),"function"==typeof r&&(this._progressHandler0=r);else{var s=5*o-5;this[s+3]=n,this[s+4]=i,"function"==typeof t&&(this[s+0]=t),"function"==typeof e&&(this[s+1]=e),"function"==typeof r&&(this[s+2]=r)}return this._setLength(o+1),o},e.prototype._setProxyHandlers=function(t,e){var r=this._length();if(r>=131066&&(r=0,this._setLength(0)),0===r)this._promise0=e,this._receiver0=t;else{var n=5*r-5;this[n+3]=e,this[n+4]=t}this._setLength(r+1)},e.prototype._proxyPromiseArray=function(t,e){this._setProxyHandlers(t,e)},e.prototype._resolveCallback=function(t,r){if(!this._isFollowingOrFulfilledOrRejected()){if(t===this)return this._rejectCallback(n(),!1,!0);var i=f(t,this);if(!(i instanceof e))return this._fulfill(t);var o=1|(r?4:0);this._propagateFrom(i,o);var s=i._target();if(s._isPending()){for(var a=this._length(),u=0;a>u;++u)s._migrateCallbacks(this,u);this._setFollowing(),this._setLength(0),this._setFollowee(s)}else s._isFulfilled()?this._fulfillUnchecked(s._value()):this._rejectUnchecked(s._reason(),s._getCarriedStackTrace())}},e.prototype._rejectCallback=function(t,e,r){r||s.markAsOriginatingFromRejection(t);var n=s.ensureErrorObject(t),i=n===t;this._attachExtraTrace(n,e?i:!1),this._reject(t,i?void 0:n)},e.prototype._resolveFromResolver=function(t){var e=this;this._captureStackTrace(),this._pushContext();var r=!0,n=w(t)(function(t){null!==e&&(e._resolveCallback(t),e=null)},function(t){null!==e&&(e._rejectCallback(t,r),e=null)});r=!1,this._popContext(),void 0!==n&&n===b&&null!==e&&(e._rejectCallback(n.e,!0,!0),e=null)},e.prototype._settlePromiseFromHandler=function(t,e,r,i){if(!i._isRejected()){i._pushContext();var o;if(o=e!==h||this._isRejected()?w(t).call(e,r):w(t).apply(this._boundTo,r),i._popContext(),o===b||o===i||o===p){var s=o===i?n():o.e;i._rejectCallback(s,!1,!0)}else i._resolveCallback(o)}},e.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},e.prototype._followee=function(){return this._rejectionHandler0},e.prototype._setFollowee=function(t){this._rejectionHandler0=t},e.prototype._cleanValues=function(){this._cancellable()&&(this._cancellationParent=void 0)},e.prototype._propagateFrom=function(t,e){(1&e)>0&&t._cancellable()&&(this._setCancellable(),this._cancellationParent=t),(4&e)>0&&t._isBound()&&this._setBoundTo(t._boundTo)},e.prototype._fulfill=function(t){this._isFollowingOrFulfilledOrRejected()||this._fulfillUnchecked(t)},e.prototype._reject=function(t,e){this._isFollowingOrFulfilledOrRejected()||this._rejectUnchecked(t,e)},e.prototype._settlePromiseAt=function(t){var r=this._promiseAt(t),n=r instanceof e;if(n&&r._isMigrated())return r._unsetIsMigrated(),a.invoke(this._settlePromiseAt,this,t);var i=this._isFulfilled()?this._fulfillmentHandlerAt(t):this._rejectionHandlerAt(t),o=this._isCarryingStackTrace()?this._getCarriedStackTrace():void 0,s=this._settledValue,u=this._receiverAt(t);this._clearCallbackDataAtIndex(t),"function"==typeof i?n?this._settlePromiseFromHandler(i,u,s,r):i.call(u,s,r):u instanceof _?u._isResolved()||(this._isFulfilled()?u._promiseFulfilled(s,r):u._promiseRejected(s,r)):n&&(this._isFulfilled()?r._fulfill(s):r._reject(s,o)),t>=4&&4===(31&t)&&a.invokeLater(this._setLength,this,0)},e.prototype._clearCallbackDataAtIndex=function(t){if(0===t)this._isCarryingStackTrace()||(this._fulfillmentHandler0=void 0),this._rejectionHandler0=this._progressHandler0=this._receiver0=this._promise0=void 0;else{var e=5*t-5;this[e+3]=this[e+4]=this[e+0]=this[e+1]=this[e+2]=void 0}},e.prototype._isSettlePromisesQueued=function(){return-1073741824===(-1073741824&this._bitField)},e.prototype._setSettlePromisesQueued=function(){this._bitField=-1073741824|this._bitField},e.prototype._unsetSettlePromisesQueued=function(){this._bitField=1073741823&this._bitField},e.prototype._queueSettlePromises=function(){a.settlePromises(this),this._setSettlePromisesQueued()},e.prototype._fulfillUnchecked=function(t){if(t===this){var e=n();return this._attachExtraTrace(e),this._rejectUnchecked(e,void 0)}this._setFulfilled(),this._settledValue=t,this._cleanValues(),this._length()>0&&this._queueSettlePromises()},e.prototype._rejectUncheckedCheckError=function(t){var e=s.ensureErrorObject(t);this._rejectUnchecked(t,e===t?void 0:e)},e.prototype._rejectUnchecked=function(t,e){if(t===this){var r=n();return this._attachExtraTrace(r),this._rejectUnchecked(r)}return this._setRejected(),this._settledValue=t,this._cleanValues(),this._isFinal()?void a.throwLater(function(t){throw"stack"in t&&a.invokeFirst(d.unhandledRejection,void 0,t),t},void 0===e?t:e):(void 0!==e&&e!==t&&this._setCarriedStackTrace(e),void(this._length()>0?this._queueSettlePromises():this._ensurePossibleRejectionHandled()))},e.prototype._settlePromises=function(){this._unsetSettlePromisesQueued();for(var t=this._length(),e=0;t>e;e++)this._settlePromiseAt(e)},e._makeSelfResolutionError=n,t("./progress.js")(e,_),t("./method.js")(e,l,f,o),t("./bind.js")(e,l,f),t("./finally.js")(e,p,f),t("./direct_resolve.js")(e),t("./synchronous_inspection.js")(e),t("./join.js")(e,_,f,l),e.Promise=e,t("./map.js")(e,_,o,f,l),t("./cancel.js")(e),t("./using.js")(e,o,f,y),t("./generators.js")(e,o,l,f),t("./nodeify.js")(e),t("./call_get.js")(e),t("./props.js")(e,_,f,o),t("./race.js")(e,l,f,o),t("./reduce.js")(e,_,o,f,l),t("./settle.js")(e,_),t("./some.js")(e,_,o),t("./promisify.js")(e,l),t("./any.js")(e),t("./each.js")(e,l),t("./timers.js")(e,l),t("./filter.js")(e,l),s.toFastProperties(e),s.toFastProperties(e.prototype),r({a:1}),r({b:2}),r({c:3}),r(1),r(function(){}),r(void 0),r(!1),r(new e(l)),d.setBounds(a.firstLineError,s.lastLineError),e}},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){switch(t){case-2:return[];case-3:return{}}}function s(t){var n,i=this._promise=new e(r);t instanceof e&&(n=t,i._propagateFrom(n,5)),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var a=t("./util.js"),u=a.isArray;return s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function c(t,r){var s=n(this._values,this._promise);if(s instanceof e){if(s=s._target(),this._values=s,!s._isFulfilled())return s._isPending()?void s._then(c,this._reject,void 0,this,r):void this._reject(s._reason());if(s=s._value(),!u(s)){var a=new e.TypeError("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");return void this.__hardReject__(a)}}else if(!u(s))return void this._promise._reject(i("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")._reason());if(0===s.length)return void(-5===r?this._resolveEmptyArray():this._resolve(o(r)));var l=this.getActualLength(s.length);this._length=l,this._values=this.shouldCopyValues()?new Array(l):this._values;for(var h=this._promise,p=0;l>p;++p){var f=this._isResolved(),_=n(s[p],h);_ instanceof e?(_=_._target(),f?_._unsetRejectionIsUnhandled():_._isPending()?_._proxyPromiseArray(this,p):_._isFulfilled()?this._promiseFulfilled(_._value(),p):this._promiseRejected(_._reason(),p)):f||this._promiseFulfilled(_,p)}},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype.__hardReject__=s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1,!0)},s.prototype._promiseProgressed=function(t,e){this._promise._progress({index:e,value:t})},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},s.prototype._promiseRejected=function(t){this._totalResolved++,this._reject(t)},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}},{"./util.js":38}],25:[function(t,e){"use strict";function r(t){return t instanceof Error&&p.getPrototypeOf(t)===Error.prototype}function n(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=p.keys(t),i=0;i2){for(var o=arguments.length,s=new Array(o-1),u=1;o>u;++u)s[u-1]=arguments[u];t._fulfill(s)}else t._fulfill(r);t=null}}}var o,s=t("./util.js"),a=s.maybeWrapAsError,u=t("./errors.js"),c=u.TimeoutError,l=u.OperationalError,h=s.haveGetters,p=t("./es5.js"),f=/^(?:name|message|stack|cause)$/;if(o=h?function(t){this.promise=t}:function(t){this.promise=t,this.asCallback=i(t),this.callback=this.asCallback},h){var _={get:function(){return i(this.promise)}};p.defineProperty(o.prototype,"asCallback",_),p.defineProperty(o.prototype,"callback",_)}o._nodebackForPromise=i,o.prototype.toString=function(){return"[object PromiseResolver]"},o.prototype.resolve=o.prototype.fulfill=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._resolveCallback(t)},o.prototype.reject=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._rejectCallback(t)},o.prototype.progress=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._progress(t)},o.prototype.cancel=function(t){this.promise.cancel(t)},o.prototype.timeout=function(){this.reject(new c("timeout"))},o.prototype.isResolved=function(){return this.promise.isResolved()},o.prototype.toJSON=function(){return this.promise.toJSON()},e.exports=o},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(t,e){"use strict";e.exports=function(e,r){function n(t){return!b.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(e){return!1}}function o(t,e,r){var n=f.getDataPropertyOrDefault(t,e+r,j);return n?i(n):!1}function s(t,e,r){for(var n=0;ns;s+=2){var c=o[s],l=o[s+1],h=c+e;t[h]=n===E?E(c,p,c,l,e):n(l,function(){return E(c,p,c,l,e)})}return f.toFastProperties(t),t}function l(t,e){return E(t,e,void 0,t)}var h,p={},f=t("./util.js"),_=t("./promise_resolver.js")._nodebackForPromise,d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,g=t("./errors").TypeError,m="Async",j={__isPromisified__:!0},b=/^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/,w=function(t,e){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&!f.isClass(e)},k=function(t){return t.replace(/([$])/,"\\$")},E=y?h:u;e.promisify=function(t,e){if("function"!=typeof t)throw new g("fn must be a function\n\n See http://goo.gl/916lJJ\n");if(i(t))return t;var r=l(t,arguments.length<2?p:e);return f.copyDescriptors(t,r,n),r},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new g("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/9ITlV0\n");e=Object(e);var r=e.suffix;"string"!=typeof r&&(r=m);var n=e.filter;"function"!=typeof n&&(n=w);var i=e.promisifier;if("function"!=typeof i&&(i=E),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/8FZo5V\n");for(var o=f.inheritedDataKeys(t),s=0;si;++i){var o=e[i];n[i]=t[o],n[i+r]=o}this.constructor$(n)}function s(t){var r,s=n(t);return u(s)?(r=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&r._propagateFrom(s,4),r):i("cannot await properties of a non-object\n\n See http://goo.gl/OsFKC8\n")}var a=t("./util.js"),u=a.isObject,c=t("./es5.js");a.inherits(o,r),o.prototype._init=function(){this._init$(void 0,-3)},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;if(r>=this._length){for(var n={},i=this.length(),o=0,s=this.length();s>o;++o)n[this._values[o+i]]=this._values[o];this._resolve(n)}},o.prototype._promiseProgressed=function(t,e){this._promise._progress({key:this._values[e+this.length()],value:t})},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5.js":14,"./util.js":38}],28:[function(t,e){"use strict";function r(t,e,r,n,i){for(var o=0;i>o;++o)r[o+n]=t[o+e],t[o+e]=void 0}function n(t){this._capacity=t,this._length=0,this._front=0}n.prototype._willBeOverCapacity=function(t){return this._capacityp;++p){var _=t[p];(void 0!==_||p in t)&&e.cast(_)._then(l,h,void 0,c,null)}return c}var s=t("./util.js").isArray,a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util.js":38}],30:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,r,n,s){this.constructor$(t),this._promise._captureStackTrace(),this._preservedValues=s===o?[]:null,this._zerothIsAccum=void 0===n,this._gotAccum=!1,this._reducingIndex=this._zerothIsAccum?1:0,this._valuesPhase=void 0;var u=i(n,this._promise),l=!1,h=u instanceof e;h&&(u=u._target(),u._isPending()?u._proxyPromiseArray(this,-1):u._isFulfilled()?(n=u._value(),this._gotAccum=!0):(this._reject(u._reason()),l=!0)),h||this._zerothIsAccum||(this._gotAccum=!0),this._callback=r,this._accum=n,l||c.invoke(a,this,void 0)}function a(){this._init$(void 0,-5)}function u(t,e,r,i){if("function"!=typeof e)return n("fn must be a function\n\n See http://goo.gl/916lJJ\n");var o=new s(t,e,r,i);return o.promise()}var c=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj;l.inherits(s,r),s.prototype._init=function(){},s.prototype._resolveEmptyArray=function(){(this._gotAccum||this._zerothIsAccum)&&this._resolve(null!==this._preservedValues?[]:this._accum)},s.prototype._promiseFulfilled=function(t,r){var n=this._values;n[r]=t;var o,s=this.length(),a=this._preservedValues,u=null!==a,c=this._gotAccum,l=this._valuesPhase;if(!l)for(l=this._valuesPhase=new Array(s),o=0;s>o;++o)l[o]=0;if(o=l[r],0===r&&this._zerothIsAccum?(this._accum=t,this._gotAccum=c=!0,l[r]=0===o?1:2):-1===r?(this._accum=t,this._gotAccum=c=!0):0===o?l[r]=1:(l[r]=2,this._accum=t),c){for(var f,_=this._callback,d=this._promise._boundTo,v=this._reducingIndex;s>v;++v)if(o=l[v],2!==o){if(1!==o)return;if(t=n[v],this._promise._pushContext(),u?(a.push(t),f=h(_).call(d,t,v,s)):f=h(_).call(d,this._accum,t,v,s),this._promise._popContext(),f===p)return this._reject(f.e);var y=i(f,this._promise);if(y instanceof e){if(y=y._target(),y._isPending())return l[v]=4,y._proxyPromiseArray(this,v);if(!y._isFulfilled())return this._reject(y._reason());f=y._value()}this._reducingIndex=v+1,this._accum=f}else this._reducingIndex=v+1;this._resolve(u?a:this._accum)}},e.prototype.reduce=function(t,e){return u(this,t,e,null)},e.reduce=function(t,e,r,n){return u(t,e,r,n)}}},{"./async.js":2,"./util.js":38}],31:[function(t,e){"use strict";var r,n=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")};if(t("./util.js").isNode){var i=process.versions.node.split(".").map(Number);r=0===i[0]&&i[1]>10||i[0]>0?function(t){global.setImmediate(t)}:process.nextTick,r||(r="undefined"!=typeof setImmediate?setImmediate:"undefined"!=typeof setTimeout?setTimeout:n)}else"undefined"!=typeof MutationObserver?(r=function(t){var e=document.createElement("div"),r=new MutationObserver(t);return r.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},r.isStatic=!0):r="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:n;e.exports=r},{"./util.js":38}],32:[function(t,e){"use strict";e.exports=function(e,r){function n(t){this.constructor$(t)}var i=e.PromiseInspection,o=t("./util.js");o.inherits(n,r),n.prototype._promiseResolved=function(t,e){this._values[t]=e;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},n.prototype._promiseFulfilled=function(t,e){var r=new i;r._bitField=268435456,r._settledValue=t,this._promiseResolved(e,r)},n.prototype._promiseRejected=function(t,e){var r=new i;r._bitField=134217728,r._settledValue=t,this._promiseResolved(e,r)},e.settle=function(t){return new n(t).promise()},e.prototype.settle=function(){return new n(this).promise()}}},{"./util.js":38}],33:[function(t,e){"use strict";e.exports=function(e,r,n){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return n("expecting a positive integer\n\n See http://goo.gl/1wAmHx\n");var r=new i(t),o=r.promise();return r.setHowMany(e),r.init(),o}var s=t("./util.js"),a=t("./errors.js").RangeError,u=t("./errors.js").AggregateError,c=s.isArray;s.inherits(i,r),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=c(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),this._resolve(1===this.howMany()&&this._unwrap?this._values[0]:this._values))},i.prototype._promiseRejected=function(t){if(this._addRejected(t),this.howMany()>this._canPossiblyFulfill()){for(var e=new u,r=this.length();r0},e.prototype.isRejected=t.prototype._isRejected=function(){return(134217728&this._bitField)>0},e.prototype.isPending=t.prototype._isPending=function(){return 0===(402653184&this._bitField)},e.prototype.isResolved=t.prototype._isResolved=function(){return(402653184&this._bitField)>0},t.prototype.isPending=function(){return this._target()._isPending()},t.prototype.isRejected=function(){return this._target()._isRejected()},t.prototype.isFulfilled=function(){return this._target()._isFulfilled()},t.prototype.isResolved=function(){return this._target()._isResolved()},t.prototype._value=function(){return this._settledValue},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue},t.prototype.value=function(){var t=this._target();if(!t.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n");return t._settledValue},t.prototype.reason=function(){var t=this._target();if(!t.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n");return t._unsetRejectionIsUnhandled(),t._settledValue},t.PromiseInspection=e}},{}],35:[function(t,e){"use strict";e.exports=function(e,r){function n(t,n){if(c(t)){if(t instanceof e)return t;if(o(t)){var l=new e(r);return t._then(l._fulfillUnchecked,l._rejectUncheckedCheckError,l._progressUnchecked,l,null),l}var h=a.tryCatch(i)(t);if(h===u){n&&n._pushContext();var l=e.reject(h.e);return n&&n._popContext(),l}if("function"==typeof h)return s(t,h,n)}return t}function i(t){return t.then}function o(t){return l.call(t,"_promise0")}function s(t,n,i){function o(r){l&&(t===r?l._rejectCallback(e._makeSelfResolutionError(),!1,!0):l._resolveCallback(r),l=null)}function s(t){l&&(l._rejectCallback(t,p,!0),l=null)}function c(t){l&&"function"==typeof l._progress&&l._progress(t)}var l=new e(r),h=l;i&&i._pushContext(),l._captureStackTrace(),i&&i._popContext();var p=!0,f=a.tryCatch(n).call(t,o,s,c);return p=!1,l&&f===u&&(l._rejectCallback(f.e,!0,!0),l=null),h}var a=t("./util.js"),u=a.errorObj,c=a.isObject,l={}.hasOwnProperty;return n}},{"./util.js":38}],36:[function(t,e){"use strict";e.exports=function(e,r){function n(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util.js"),s=e.TimeoutError,a=function(t,e){if(t.isPending()){"string"!=typeof e&&(e="operation timed out");var r=new s(e);o.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._cancel(r)}},u=function(t){return c(+this).thenReturn(t)},c=e.delay=function(t,n){if(void 0===n){n=t,t=void 0;var i=new e(r);return setTimeout(function(){i._fulfill()},n),i}return n=+n,e.resolve(t)._then(u,null,null,n,void 0)};e.prototype.delay=function(t){return c(this,t)},e.prototype.timeout=function(t,e){t=+t;var r=this.then().cancellable();r._cancellationParent=this;var o=setTimeout(function(){a(r,e)},t);return r._then(n,i,void 0,o,void 0)}}},{"./util.js":38}],37:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){for(var r=t.length,n=0;r>n;++n){var i=t[n];if(i.isRejected())return e.reject(i.error());t[n]=i._settledValue}return t}function s(t){setTimeout(function(){throw t},0)}function a(t){var e=n(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function u(t,r){function i(){if(o>=u)return c.resolve();var l=a(t[o++]);if(l instanceof e&&l._isDisposable()){try{l=n(l._getDisposer().tryDispose(r),t.promise)}catch(h){return s(h)}if(l instanceof e)return l._then(i,s,null,null,null)}i()}var o=0,u=t.length,c=e.defer();return i(),c.promise}function c(t){var e=new v;return e._settledValue=t,e._bitField=268435456,u(this,e).thenReturn(t)}function l(t){var e=new v;return e._settledValue=t,e._bitField=134217728,u(this,e).thenThrow(t)}function h(t,e,r){this._data=t,this._promise=e,this._context=r}function p(t,e,r){this.constructor$(t,e,r)}function f(t){return h.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}var _=t("./errors.js").TypeError,d=t("./util.js").inherits,v=e.PromiseInspection;h.prototype.data=function(){return this._data},h.prototype.promise=function(){return this._promise},h.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},h.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=null!==e?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},h.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},d(p,h),p.prototype.doDispose=function(t,e){var r=this.data();return r.call(t,t,e)},e.using=function(){var t=arguments.length;if(2>t)return r("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return r("fn must be a function\n\n See http://goo.gl/916lJJ\n");t--;for(var s=new Array(t),a=0;t>a;++a){var u=arguments[a];if(h.isDisposer(u)){var p=u;u=u.promise(),u._setDisposable(p)}else{var _=n(u);_ instanceof e&&(u=_._then(f,null,null,{resources:s,index:a},void 0))}s[a]=u}var d=e.settle(s).then(o).then(function(t){d._pushContext();var e;try{e=i.apply(void 0,t)}finally{d._popContext()}return e})._then(c,l,void 0,s,void 0);return s.promise=d,d},e.prototype._setDisposable=function(t){this._bitField=262144|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(262144&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-262145&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new _}}},{"./errors.js":13,"./util.js":38}],38:[function(t,e,r){"use strict"; +function n(){try{return T.apply(this,arguments)}catch(t){return F.e=t,F}}function i(t){return T=t,n}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return!o(t)}function a(t){return o(t)?new Error(v(t)):t}function u(t,e){var r,n=t.length,i=new Array(n+1);for(r=0;n>r;++r)i[r]=t[r];return i[r]=e,i}function c(t,e,r){if(!w.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var n=Object.getOwnPropertyDescriptor(t,e);return null!=n?null==n.get&&null==n.set?n.value:r:void 0}function l(t,e,r){if(o(t))return t;var n={value:r,configurable:!0,enumerable:!1,writable:!0};return w.defineProperty(t,e,n),t}function h(t){throw t}function p(t){try{if("function"==typeof t){var e=w.names(t.prototype);return w.isES5?e.length>1:e.length>0&&!(1===e.length&&"constructor"===e[0])}return!1}catch(r){return!1}}function f(t){function e(){}e.prototype=t;for(var r=8;r--;)new e;return t}function _(t){return R.test(t)}function d(t,e,r){for(var n=new Array(t),i=0;t>i;++i)n[i]=e+i+r;return n}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){try{l(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function m(t){return t instanceof Error&&w.propertyIsWritable(t,"stack")}function j(t){return{}.toString.call(t)}function b(t,e,r){for(var n=w.names(t),i=0;it||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,r,i,a,u,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],s(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];r.apply(this,a)}else if(o(r)){for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];for(c=r.slice(),i=c.length,u=0;i>u;u++)c[u].apply(this,a)}return!0},r.prototype.addListener=function(t,e){var i;if(!n(e))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,n(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned){var i;i=s(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,i&&i>0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())}return this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),i||(i=!0,e.apply(this,arguments))}if(!n(e))throw TypeError("listener must be a function");var i=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,i,s,a;if(!n(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],s=r.length,i=-1,r===e||n(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(a=s;a-->0;)if(r[a]===e||r[a].listener&&r[a].listener===e){i=a;break}if(0>i)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],n(r))this.removeListener(t,r);else for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?n(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.listenerCount=function(t,e){var r;return r=t._events&&t._events[e]?n(t._events[e])?1:t._events[e].length:0}},{}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js new file mode 100644 index 0000000..05a6228 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js @@ -0,0 +1,21 @@ +"use strict"; +module.exports = function(Promise) { +var SomePromiseArray = Promise._SomePromiseArray; +function any(promises) { + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(1); + ret.setUnwrap(); + ret.init(); + return promise; +} + +Promise.any = function (promises) { + return any(promises); +}; + +Promise.prototype.any = function () { + return any(this); +}; + +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js new file mode 100644 index 0000000..a98955c --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js @@ -0,0 +1,55 @@ +"use strict"; +module.exports = (function(){ +var AssertionError = (function() { + function AssertionError(a) { + this.constructor$(a); + this.message = a; + this.name = "AssertionError"; + } + AssertionError.prototype = new Error(); + AssertionError.prototype.constructor = AssertionError; + AssertionError.prototype.constructor$ = Error; + return AssertionError; +})(); + +function getParams(args) { + var params = []; + for (var i = 0; i < args.length; ++i) params.push("arg" + i); + return params; +} + +function nativeAssert(callName, args, expect) { + try { + var params = getParams(args); + var constructorArgs = params; + constructorArgs.push("return " + + callName + "("+ params.join(",") + ");"); + var fn = Function.apply(null, constructorArgs); + return fn.apply(null, args); + } catch (e) { + if (!(e instanceof SyntaxError)) { + throw e; + } else { + return expect; + } + } +} + +return function assert(boolExpr, message) { + if (boolExpr === true) return; + + if (typeof boolExpr === "string" && + boolExpr.charAt(0) === "%") { + var nativeCallName = boolExpr; + var $_len = arguments.length;var args = new Array($_len - 2); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];} + if (nativeAssert(nativeCallName, args, message) === message) return; + message = (nativeCallName + " !== " + message); + } + + var ret = new AssertionError(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(ret, assert); + } + throw ret; +}; +})(); diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js new file mode 100644 index 0000000..3b5f828 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js @@ -0,0 +1,204 @@ +"use strict"; +var firstLineError; +try {throw new Error(); } catch (e) {firstLineError = e;} +var schedule = require("./schedule.js"); +var Queue = require("./queue.js"); +var util = require("./util.js"); + +function Async() { + this._isTickUsed = false; + this._lateQueue = new Queue(16); + this._normalQueue = new Queue(16); + this._trampolineEnabled = true; + var self = this; + this.drainQueues = function () { + self._drainQueues(); + }; + this._schedule = + schedule.isStatic ? schedule(this.drainQueues) : schedule; +} + +Async.prototype.disableTrampolineIfNecessary = function() { + if (util.hasDevTools) { + this._trampolineEnabled = false; + } +}; + +Async.prototype.enableTrampoline = function() { + if (!this._trampolineEnabled) { + this._trampolineEnabled = true; + this._schedule = function(fn) { + setTimeout(fn, 0); + }; + } +}; + +Async.prototype.haveItemsQueued = function () { + return this._normalQueue.length() > 0; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + } +}; + +Async.prototype._getDomain = function() {}; + +if (!false) { +if (util.isNode) { + var EventsModule = require("events"); + + var domainGetter = function() { + var domain = process.domain; + if (domain === null) return undefined; + return domain; + }; + + if (EventsModule.usingDomains) { + Async.prototype._getDomain = domainGetter; + } else { + var descriptor = + Object.getOwnPropertyDescriptor(EventsModule, "usingDomains"); + + if (descriptor) { + if (!descriptor.configurable) { + process.on("domainsActivated", function() { + Async.prototype._getDomain = domainGetter; + }); + } else { + var usingDomains = false; + Object.defineProperty(EventsModule, "usingDomains", { + configurable: false, + enumerable: true, + get: function() { + return usingDomains; + }, + set: function(value) { + if (usingDomains || !value) return; + usingDomains = true; + Async.prototype._getDomain = domainGetter; + util.toFastProperties(process); + process.emit("domainsActivated"); + } + }); + } + } + } +} +} + +function AsyncInvokeLater(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + var domain = this._getDomain(); + if (domain !== undefined) { + var fn = domain.bind(promise._settlePromises); + this._normalQueue.push(fn, promise, undefined); + } else { + this._normalQueue._pushOne(promise); + } + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 0); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + setTimeout(function() { + promise._settlePromises(); + }, 0); + } + }; +} + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = new Async(); +module.exports.firstLineError = firstLineError; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js new file mode 100644 index 0000000..d6f6da2 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js @@ -0,0 +1,73 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + this._setBoundTo(thisArg); + if (this._isPending()) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, ret._progress, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, ret._progress, ret, context); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 131072; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~131072); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.bind = function (thisArg, value) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + + if (maybePromise instanceof Promise) { + maybePromise._then(function(thisArg) { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + }, ret._reject, ret._progress, ret, null); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + } + return ret; +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js new file mode 100644 index 0000000..ed6226e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js @@ -0,0 +1,11 @@ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = require("./promise.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js new file mode 100644 index 0000000..62c166d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js @@ -0,0 +1,123 @@ +"use strict"; +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} + +module.exports = function(Promise) { +var util = require("./util.js"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!false) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; + } + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; + } + } + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + if (!false) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } + } + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; + +function namedGetter(obj) { + return obj[this]; +} +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js new file mode 100644 index 0000000..9eb40b6 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js @@ -0,0 +1,48 @@ +"use strict"; +module.exports = function(Promise) { +var errors = require("./errors.js"); +var async = require("./async.js"); +var CancellationError = errors.CancellationError; + +Promise.prototype._cancel = function (reason) { + if (!this.isCancellable()) return this; + var parent; + var promiseToReject = this; + while ((parent = promiseToReject._cancellationParent) !== undefined && + parent.isCancellable()) { + promiseToReject = parent; + } + this._unsetCancellable(); + promiseToReject._target()._rejectCallback(reason, false, true); +}; + +Promise.prototype.cancel = function (reason) { + if (!this.isCancellable()) return this; + if (reason === undefined) reason = new CancellationError(); + async.invokeLater(this._cancel, this, reason); + return this; +}; + +Promise.prototype.cancellable = function () { + if (this._cancellable()) return this; + async.enableTrampoline(); + this._setCancellable(); + this._cancellationParent = undefined; + return this; +}; + +Promise.prototype.uncancellable = function () { + var ret = this.then(); + ret._unsetCancellable(); + return ret; +}; + +Promise.prototype.fork = function (didFulfill, didReject, didProgress) { + var ret = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + + ret._setCancellable(); + ret._cancellationParent = undefined; + return ret; +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js new file mode 100644 index 0000000..6fda9e8 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js @@ -0,0 +1,492 @@ +"use strict"; +module.exports = function() { +var async = require("./async.js"); +var util = require("./util.js"); +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var warn; + +function CapturedTrace(parent) { + this._parent = parent; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.parent = function() { + return this._parent; +}; + +CapturedTrace.prototype.hasParent = function() { + return this._parent !== undefined; +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = CapturedTrace.parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = stackFramePattern.test(line) || + " (No stack trace)" === line; + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +CapturedTrace.parseStackAndMessage = function(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +}; + +CapturedTrace.formatAndLogError = function(error, title) { + if (typeof console !== "undefined") { + var message; + if (typeof error === "object" || typeof error === "function") { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof warn === "function") { + warn(message); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +}; + +CapturedTrace.unhandledRejection = function (reason) { + CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: "); +}; + +CapturedTrace.isSupported = function () { + return typeof captureStackTrace === "function"; +}; + +CapturedTrace.fireRejectionEvent = +function(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); + } + } + + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + } +}; + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj.toString(); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} +CapturedTrace.setBounds = function(firstLineError, lastLineError) { + if (!CapturedTrace.isSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow) { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); + } + }; + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; + } + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); + } + return true; + }; + } +})(); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + warn = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + warn = function(message) { + process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + warn = function(message) { + console.warn("%c" + message, "color: red"); + }; + } +} + +return CapturedTrace; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js new file mode 100644 index 0000000..040f057 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js @@ -0,0 +1,66 @@ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = require("./util.js"); +var errors = require("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = require("./es5.js").keys; +var TypeError = errors.TypeError; + +function CatchFilter(instances, callback, promise) { + this._instances = instances; + this._callback = callback; + this._promise = promise; +} + +function safePredicate(predicate, e) { + var safeObject = {}; + var retfilter = tryCatch(predicate).call(safeObject, e); + + if (retfilter === errorObj) return retfilter; + + var safeKeys = keys(safeObject); + if (safeKeys.length) { + errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); + return errorObj; + } + return retfilter; +} + +CatchFilter.prototype.doFilter = function (e) { + var cb = this._callback; + var promise = this._promise; + var boundTo = promise._boundTo; + for (var i = 0, len = this._instances.length; i < len; ++i) { + var item = this._instances[i]; + var itemIsErrorType = item === Error || + (item != null && item.prototype instanceof Error); + + if (itemIsErrorType && e instanceof item) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } else if (typeof item === "function" && !itemIsErrorType) { + var shouldHandle = safePredicate(item, e); + if (shouldHandle === errorObj) { + e = errorObj.e; + break; + } else if (shouldHandle) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } + } + } + NEXT_FILTER.e = e; + return NEXT_FILTER; +}; + +return CatchFilter; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js new file mode 100644 index 0000000..ccd7702 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js @@ -0,0 +1,38 @@ +"use strict"; +module.exports = function(Promise, CapturedTrace, isDebugging) { +var contextStack = []; +function Context() { + this._trace = new CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.pop(); + } +}; + +function createContext() { + if (isDebugging()) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} + +Promise.prototype._peekContext = peekContext; +Promise.prototype._pushContext = Context.prototype._pushContext; +Promise.prototype._popContext = Context.prototype._popContext; + +return createContext; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js new file mode 100644 index 0000000..5ac1767 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js @@ -0,0 +1,147 @@ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var async = require("./async.js"); +var Warning = require("./errors.js").Warning; +var util = require("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +if (debugging) { + async.disableTrampolineIfNecessary(); +} + +Promise.prototype._ensurePossibleRejectionHandled = function () { + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + CapturedTrace.fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._getCarriedStackTrace() || this._settledValue; + this._setUnhandledRejectionIsNotified(); + CapturedTrace.fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 524288; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~524288); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 524288) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 2097152; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~2097152); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 2097152) > 0; +}; + +Promise.prototype._setCarriedStackTrace = function (capturedTrace) { + this._bitField = this._bitField | 1048576; + this._fulfillmentHandler0 = capturedTrace; +}; + +Promise.prototype._isCarryingStackTrace = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._getCarriedStackTrace = function () { + return this._isCarryingStackTrace() + ? this._fulfillmentHandler0 + : undefined; +}; + +Promise.prototype._captureStackTrace = function () { + if (debugging) { + this._trace = new CapturedTrace(this._peekContext()); + } + return this; +}; + +Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { + if (debugging && canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = CapturedTrace.parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +}; + +Promise.prototype._warn = function(message) { + var warning = new Warning(message); + var ctx = this._peekContext(); + if (ctx) { + ctx.attachExtraTrace(warning); + } else { + var parsed = CapturedTrace.parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + CapturedTrace.formatAndLogError(warning, ""); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + unhandledRejectionHandled = typeof fn === "function" ? fn : undefined; +}; + +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && + debugging === false + ) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); + } + debugging = CapturedTrace.isSupported(); + if (debugging) { + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js new file mode 100644 index 0000000..47a9ce9 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js @@ -0,0 +1,62 @@ +"use strict"; +var util = require("./util.js"); +var isPrimitive = util.isPrimitive; +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; + +module.exports = function(Promise) { +var returner = function () { + return this; +}; +var thrower = function () { + throw this; +}; +var returnUndefined = function() {}; +var throwUndefined = function() { + throw undefined; +}; + +var wrapper = function (value, action) { + if (action === 1) { + return function () { + throw value; + }; + } else if (action === 2) { + return function () { + return value; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value === undefined) return this.then(returnUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js new file mode 100644 index 0000000..a37e22c --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js @@ -0,0 +1,12 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, null, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, null, INTERNAL); +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js new file mode 100644 index 0000000..c334bb1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js @@ -0,0 +1,111 @@ +"use strict"; +var es5 = require("./es5.js"); +var Objectfreeze = es5.freeze; +var util = require("./util.js"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} + +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; + + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + +} +inherits(OperationalError, Error); + +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js new file mode 100644 index 0000000..ea41d5a --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js @@ -0,0 +1,80 @@ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js new file mode 100644 index 0000000..ed57bf0 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js @@ -0,0 +1,12 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseMap = Promise.map; + +Promise.prototype.filter = function (fn, options) { + return PromiseMap(this, fn, options, INTERNAL); +}; + +Promise.filter = function (promises, fn, options) { + return PromiseMap(promises, fn, options, INTERNAL); +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js new file mode 100644 index 0000000..ed84a2a --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js @@ -0,0 +1,99 @@ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = require("./util.js"); +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, reasonOrValue, + promise.isFulfilled()); + } + } + + if (promise.isRejected()) { + NEXT_FILTER.e = reasonOrValue; + return NEXT_FILTER; + } else { + return reasonOrValue; + } +} + +function tapHandler(value) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo, value) + : handler(value); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, value, true); + } + } + return value; +} + +Promise.prototype._passThroughHandler = function (handler, isFinally) { + if (typeof handler !== "function") return this.then(); + + var promiseAndHandler = { + promise: this, + handler: handler + }; + + return this._then( + isFinally ? finallyHandler : tapHandler, + isFinally ? finallyHandler : undefined, undefined, + promiseAndHandler, undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThroughHandler(handler, true); +}; + +Promise.prototype.tap = function (handler) { + return this._passThroughHandler(handler, false); +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js new file mode 100644 index 0000000..4c0568d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js @@ -0,0 +1,136 @@ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = require("./errors.js"); +var TypeError = errors.TypeError; +var util = require("./util.js"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; +} + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._next(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + if (result === errorObj) { + return this._promise._rejectCallback(result.e, false, true); + } + + var value = result.value; + if (result.done === true) { + this._promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._throw( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise._then( + this._next, + this._throw, + undefined, + this, + null + ); + } +}; + +PromiseSpawn.prototype._throw = function (reason) { + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._next = function (value) { + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + spawn._generator = generator; + spawn._next(undefined); + return spawn.promise(); + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js new file mode 100644 index 0000000..cf33eb1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js @@ -0,0 +1,107 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = require("./util.js"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!false) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var caller = function(count) { + var values = []; + for (var i = 1; i <= count; ++i) values.push("holder.p" + i); + return new Function("holder", " \n\ + 'use strict'; \n\ + var callback = holder.fn; \n\ + return callback(values); \n\ + ".replace(/values/g, values.join(", "))); + }; + var thenCallbacks = []; + var callers = [undefined]; + for (var i = 1; i <= 5; ++i) { + thenCallbacks.push(thenCallback(i)); + callers.push(caller(i)); + } + + var Holder = function(total, fn) { + this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; + this.fn = fn; + this.total = total; + this.now = 0; + }; + + Holder.prototype.callers = callers; + Holder.prototype.checkFulfillment = function(promise) { + var now = this.now; + now++; + var total = this.total; + if (now >= total) { + var handler = this.callers[total]; + promise._pushContext(); + var ret = tryCatch(handler)(this); + promise._popContext(); + if (ret === errorObj) { + promise._rejectCallback(ret.e, false, true); + } else { + promise._resolveCallback(ret); + } + } else { + this.now = now; + } + }; + + var reject = function (reason) { + this._reject(reason); + }; +} +} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!false) { + if (last < 6 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var holder = new Holder(last, fn); + var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + } else if (maybePromise._isFulfilled()) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else { + ret._reject(maybePromise._reason()); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + return ret; + } + } + } + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js new file mode 100644 index 0000000..66a5b17 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js @@ -0,0 +1,131 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = require("./async.js"); +var util = require("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var PENDING = {}; +var EMPTY_ARRAY = []; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._callback = fn; + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + async.invoke(init, this, undefined); +} +util.inherits(MappingPromiseArray, PromiseArray); +function init() {this._init$(undefined, -2);} + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + if (values[index] === PENDING) { + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return; + } + if (preservedValues !== null) preservedValues[index] = value; + + var callback = this._callback; + var receiver = this._promise._boundTo; + this._promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + this._promise._popContext(); + if (ret === errorObj) return this._reject(ret.e); + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + if (limit >= 1) this._inFlight++; + values[index] = PENDING; + return maybePromise._proxyPromiseArray(this, index); + } else if (maybePromise._isFulfilled()) { + ret = maybePromise._value(); + } else { + return this._reject(maybePromise._reason()); + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + + } +}; + +MappingPromiseArray.prototype._drainQueue = function () { + var queue = this._queue; + var limit = this._limit; + var values = this._values; + while (queue.length > 0 && this._inFlight < limit) { + if (this._isResolved()) return; + var index = queue.pop(); + this._promiseFulfilled(values[index], index); + } +}; + +MappingPromiseArray.prototype._filter = function (booleans, values) { + var len = values.length; + var ret = new Array(len); + var j = 0; + for (var i = 0; i < len; ++i) { + if (booleans[i]) ret[j++] = values[i]; + } + ret.length = j; + this._resolve(ret); +}; + +MappingPromiseArray.prototype.preservedValues = function () { + return this._preservedValues; +}; + +function map(promises, fn, options, _filter) { + var limit = typeof options === "object" && options !== null + ? options.concurrency + : 0; + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter); +} + +Promise.prototype.map = function (fn, options) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + + return map(this, fn, options, null).promise(); +}; + +Promise.map = function (promises, fn, options, _filter) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + return map(promises, fn, options, _filter).promise(); +}; + + +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js new file mode 100644 index 0000000..3d3eeb1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js @@ -0,0 +1,44 @@ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = require("./util.js"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn, args, ctx) { + if (typeof fn !== "function") { + return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = util.isArray(args) + ? tryCatch(fn).apply(ctx, args) + : tryCatch(fn).call(ctx, args); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false, true); + } else { + this._resolveCallback(value, true); + } +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js new file mode 100644 index 0000000..f305b93 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise) { +var util = require("./util.js"); +var async = require("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundTo; + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var target = promise._target(); + var newReason = target._getCarriedStackTrace(); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundTo, reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = +Promise.prototype.nodeify = function (nodeback, options) { + if (typeof nodeback == "function") { + var adapter = successAdapter; + if (options !== undefined && Object(options).spread) { + adapter = spreadAdapter; + } + this._then( + adapter, + errorAdapter, + undefined, + this, + nodeback + ); + } + return this; +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js new file mode 100644 index 0000000..2e3e95e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js @@ -0,0 +1,76 @@ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = require("./util.js"); +var async = require("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +Promise.prototype.progressed = function (handler) { + return this._then(undefined, undefined, handler, undefined, undefined); +}; + +Promise.prototype._progress = function (progressValue) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._target()._progressUnchecked(progressValue); + +}; + +Promise.prototype._progressHandlerAt = function (index) { + return index === 0 + ? this._progressHandler0 + : this[(index << 2) + index - 5 + 2]; +}; + +Promise.prototype._doProgressWith = function (progression) { + var progressValue = progression.value; + var handler = progression.handler; + var promise = progression.promise; + var receiver = progression.receiver; + + var ret = tryCatch(handler).call(receiver, progressValue); + if (ret === errorObj) { + if (ret.e != null && + ret.e.name !== "StopProgressPropagation") { + var trace = util.canAttachTrace(ret.e) + ? ret.e : new Error(util.toString(ret.e)); + promise._attachExtraTrace(trace); + promise._progress(ret.e); + } + } else if (ret instanceof Promise) { + ret._then(promise._progress, null, null, promise, undefined); + } else { + promise._progress(ret); + } +}; + + +Promise.prototype._progressUnchecked = function (progressValue) { + var len = this._length(); + var progress = this._progress; + for (var i = 0; i < len; i++) { + var handler = this._progressHandlerAt(i); + var promise = this._promiseAt(i); + if (!(promise instanceof Promise)) { + var receiver = this._receiverAt(i); + if (typeof handler === "function") { + handler.call(receiver, progressValue, promise); + } else if (receiver instanceof PromiseArray && + !receiver._isResolved()) { + receiver._promiseProgressed(progressValue, promise); + } + continue; + } + + if (typeof handler === "function") { + async.invoke(this._doProgressWith, this, { + handler: handler, + promise: promise, + receiver: this._receiverAt(i), + value: progressValue + }); + } else { + async.invoke(progress, promise, progressValue); + } + } +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js new file mode 100644 index 0000000..f80d247 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js @@ -0,0 +1,700 @@ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); +}; +var reflect = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +var util = require("./util.js"); +var async = require("./async.js"); +var errors = require("./errors.js"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {e: null}; +var tryConvertToPromise = require("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + require("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = require("./captured_trace.js")(); +var isDebugging = require("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + require("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = require("./promise_resolver.js"); +var nodebackForPromise = PromiseResolver._nodebackForPromise; +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function Promise(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); + } + if (this.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._progressHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._settledValue = undefined; + if (resolver !== INTERNAL) this._resolveFromResolver(resolver); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (typeof item === "function") { + catchInstances[j++] = item; + } else { + return Promise.reject( + new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); + } + } + catchInstances.length = j; + fn = arguments[i]; + var catchFilter = new CatchFilter(catchInstances, fn, this); + return this._then(undefined, catchFilter.doFilter, undefined, + catchFilter, undefined); + } + return this._then(undefined, fn, undefined, undefined, undefined); +}; + +Promise.prototype.reflect = function () { + return this._then(reflect, reflect, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject, didProgress) { + if (isDebugging() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, didProgress, + undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject, didProgress) { + var promise = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (didFulfill, didReject) { + return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); +}; + +Promise.prototype.isCancellable = function () { + return !this.isResolved() && + this._cancellable(); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = function(fn) { + var ret = new Promise(INTERNAL); + var result = tryCatch(fn)(nodebackForPromise(ret)); + if (result === errorObj) { + ret._rejectCallback(result.e, true, true); + } + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.defer = Promise.pending = function () { + var promise = new Promise(INTERNAL); + return new PromiseResolver(promise); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + var val = ret; + ret = new Promise(INTERNAL); + ret._fulfillUnchecked(val); + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + didProgress, + receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var ret = haveInternalData ? internalData : new Promise(INTERNAL); + + if (!haveInternalData) { + ret._propagateFrom(this, 4 | 1); + ret._captureStackTrace(); + } + + var target = this._target(); + if (target !== this) { + if (receiver === undefined) receiver = this._boundTo; + if (!haveInternalData) ret._setIsMigrated(); + } + + var callbackIndex = + target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); + + if (target._isResolved() && !target._isSettlePromisesQueued()) { + async.invoke( + target._settlePromiseAtPostResolution, target, callbackIndex); + } + + return ret; +}; + +Promise.prototype._settlePromiseAtPostResolution = function (index) { + if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); + this._settlePromiseAt(index); +}; + +Promise.prototype._length = function () { + return this._bitField & 131071; +}; + +Promise.prototype._isFollowingOrFulfilledOrRejected = function () { + return (this._bitField & 939524096) > 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 536870912) === 536870912; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -131072) | + (len & 131071); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 536870912; +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 33554432; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 33554432) > 0; +}; + +Promise.prototype._cancellable = function () { + return (this._bitField & 67108864) > 0; +}; + +Promise.prototype._setCancellable = function () { + this._bitField = this._bitField | 67108864; +}; + +Promise.prototype._unsetCancellable = function () { + this._bitField = this._bitField & (~67108864); +}; + +Promise.prototype._setIsMigrated = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._unsetIsMigrated = function () { + this._bitField = this._bitField & (~4194304); +}; + +Promise.prototype._isMigrated = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 + ? this._receiver0 + : this[ + index * 5 - 5 + 4]; + if (ret === undefined && this._isBound()) { + return this._boundTo; + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return index === 0 + ? this._promise0 + : this[index * 5 - 5 + 3]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return index === 0 + ? this._fulfillmentHandler0 + : this[index * 5 - 5 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return index === 0 + ? this._rejectionHandler0 + : this[index * 5 - 5 + 1]; +}; + +Promise.prototype._migrateCallbacks = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var progress = follower._progressHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (promise instanceof Promise) promise._setIsMigrated(); + this._addCallbacks(fulfill, reject, progress, promise, receiver); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + progress, + promise, + receiver +) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + if (receiver !== undefined) this._receiver0 = receiver; + if (typeof fulfill === "function" && !this._isCarryingStackTrace()) + this._fulfillmentHandler0 = fulfill; + if (typeof reject === "function") this._rejectionHandler0 = reject; + if (typeof progress === "function") this._progressHandler0 = progress; + } else { + var base = index * 5 - 5; + this[base + 3] = promise; + this[base + 4] = receiver; + if (typeof fulfill === "function") + this[base + 0] = fulfill; + if (typeof reject === "function") + this[base + 1] = reject; + if (typeof progress === "function") + this[base + 2] = progress; + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + if (index === 0) { + this._promise0 = promiseSlotValue; + this._receiver0 = receiver; + } else { + var base = index * 5 - 5; + this[base + 3] = promiseSlotValue; + this[base + 4] = receiver; + } + this._setLength(index + 1); +}; + +Promise.prototype._proxyPromiseArray = function (promiseArray, index) { + this._setProxyHandlers(promiseArray, index); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (this._isFollowingOrFulfilledOrRejected()) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false, true); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + var propagationFlags = 1 | (shouldBind ? 4 : 0); + this._propagateFrom(maybePromise, propagationFlags); + var promise = maybePromise._target(); + if (promise._isPending()) { + var len = this._length(); + for (var i = 0; i < len; ++i) { + promise._migrateCallbacks(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (promise._isFulfilled()) { + this._fulfillUnchecked(promise._value()); + } else { + this._rejectUnchecked(promise._reason(), + promise._getCarriedStackTrace()); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { + if (!shouldNotMarkOriginatingFromRejection) { + util.markAsOriginatingFromRejection(reason); + } + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, hasStack ? undefined : trace); +}; + +Promise.prototype._resolveFromResolver = function (resolver) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = tryCatch(resolver)(function(value) { + if (promise === null) return; + promise._resolveCallback(value); + promise = null; + }, function (reason) { + if (promise === null) return; + promise._rejectCallback(reason, synchronous); + promise = null; + }); + synchronous = false; + this._popContext(); + + if (r !== undefined && r === errorObj && promise !== null) { + promise._rejectCallback(r.e, true, true); + promise = null; + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + if (promise._isRejected()) return; + promise._pushContext(); + var x; + if (receiver === APPLY && !this._isRejected()) { + x = tryCatch(handler).apply(this._boundTo, value); + } else { + x = tryCatch(handler).call(receiver, value); + } + promise._popContext(); + + if (x === errorObj || x === promise || x === NEXT_FILTER) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false, true); + } else { + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._cleanValues = function () { + if (this._cancellable()) { + this._cancellationParent = undefined; + } +}; + +Promise.prototype._propagateFrom = function (parent, flags) { + if ((flags & 1) > 0 && parent._cancellable()) { + this._setCancellable(); + this._cancellationParent = parent; + } + if ((flags & 4) > 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +}; + +Promise.prototype._fulfill = function (value) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._fulfillUnchecked(value); +}; + +Promise.prototype._reject = function (reason, carriedStackTrace) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._rejectUnchecked(reason, carriedStackTrace); +}; + +Promise.prototype._settlePromiseAt = function (index) { + var promise = this._promiseAt(index); + var isPromise = promise instanceof Promise; + + if (isPromise && promise._isMigrated()) { + promise._unsetIsMigrated(); + return async.invoke(this._settlePromiseAt, this, index); + } + var handler = this._isFulfilled() + ? this._fulfillmentHandlerAt(index) + : this._rejectionHandlerAt(index); + + var carriedStackTrace = + this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; + var value = this._settledValue; + var receiver = this._receiverAt(index); + + + this._clearCallbackDataAtIndex(index); + + if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof PromiseArray) { + if (!receiver._isResolved()) { + if (this._isFulfilled()) { + receiver._promiseFulfilled(value, promise); + } + else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (this._isFulfilled()) { + promise._fulfill(value); + } else { + promise._reject(value, carriedStackTrace); + } + } + + if (index >= 4 && (index & 31) === 4) + async.invokeLater(this._setLength, this, 0); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + if (index === 0) { + if (!this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = undefined; + } + this._rejectionHandler0 = + this._progressHandler0 = + this._receiver0 = + this._promise0 = undefined; + } else { + var base = index * 5 - 5; + this[base + 3] = + this[base + 4] = + this[base + 0] = + this[base + 1] = + this[base + 2] = undefined; + } +}; + +Promise.prototype._isSettlePromisesQueued = function () { + return (this._bitField & + -1073741824) === -1073741824; +}; + +Promise.prototype._setSettlePromisesQueued = function () { + this._bitField = this._bitField | -1073741824; +}; + +Promise.prototype._unsetSettlePromisesQueued = function () { + this._bitField = this._bitField & (~-1073741824); +}; + +Promise.prototype._queueSettlePromises = function() { + async.settlePromises(this); + this._setSettlePromisesQueued(); +}; + +Promise.prototype._fulfillUnchecked = function (value) { + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err, undefined); + } + this._setFulfilled(); + this._settledValue = value; + this._cleanValues(); + + if (this._length() > 0) { + this._queueSettlePromises(); + } +}; + +Promise.prototype._rejectUncheckedCheckError = function (reason) { + var trace = util.ensureErrorObject(reason); + this._rejectUnchecked(reason, trace === reason ? undefined : trace); +}; + +Promise.prototype._rejectUnchecked = function (reason, trace) { + if (reason === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err); + } + this._setRejected(); + this._settledValue = reason; + this._cleanValues(); + + if (this._isFinal()) { + async.throwLater(function(e) { + if ("stack" in e) { + async.invokeFirst( + CapturedTrace.unhandledRejection, undefined, e); + } + throw e; + }, trace === undefined ? reason : trace); + return; + } + + if (trace !== undefined && trace !== reason) { + this._setCarriedStackTrace(trace); + } + + if (this._length() > 0) { + this._queueSettlePromises(); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._settlePromises = function () { + this._unsetSettlePromisesQueued(); + var len = this._length(); + for (var i = 0; i < len; i++) { + this._settlePromiseAt(i); + } +}; + +Promise._makeSelfResolutionError = makeSelfResolutionError; +require("./progress.js")(Promise, PromiseArray); +require("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +require("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +require("./direct_resolve.js")(Promise); +require("./synchronous_inspection.js")(Promise); +require("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./cancel.js')(Promise); +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +require('./nodeify.js')(Promise); +require('./call_get.js')(Promise); +require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./settle.js')(Promise, PromiseArray); +require('./some.js')(Promise, PromiseArray, apiRejection); +require('./promisify.js')(Promise, INTERNAL); +require('./any.js')(Promise); +require('./each.js')(Promise, INTERNAL); +require('./timers.js')(Promise, INTERNAL); +require('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._progressHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + p._settledValue = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + CapturedTrace.setBounds(async.firstLineError, util.lastLineError); + return Promise; + +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js new file mode 100644 index 0000000..6dac866 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js @@ -0,0 +1,142 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = require("./util.js"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + var parent; + if (values instanceof Promise) { + parent = values; + promise._propagateFrom(parent, 1 | 4); + } + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + this._values = values; + if (values._isFulfilled()) { + values = values._value(); + if (!isArray(values)) { + var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + this.__hardReject__(err); + return; + } + } else if (values._isPending()) { + values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + return; + } else { + this._reject(values._reason()); + return; + } + } else if (!isArray(values)) { + this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var promise = this._promise; + for (var i = 0; i < len; ++i) { + var isResolved = this._isResolved(); + var maybePromise = tryConvertToPromise(values[i], promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (isResolved) { + maybePromise._unsetRejectionIsUnhandled(); + } else if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, i); + } else if (maybePromise._isFulfilled()) { + this._promiseFulfilled(maybePromise._value(), i); + } else { + this._promiseRejected(maybePromise._reason(), i); + } + } else if (!isResolved) { + this._promiseFulfilled(maybePromise, i); + } + } +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype.__hardReject__ = +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false, true); +}; + +PromiseArray.prototype._promiseProgressed = function (progressValue, index) { + this._promise._progress({ + index: index, + value: progressValue + }); +}; + + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +PromiseArray.prototype._promiseRejected = function (reason, index) { + this._totalResolved++; + this._reject(reason); +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js new file mode 100644 index 0000000..b180a32 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js @@ -0,0 +1,123 @@ +"use strict"; +var util = require("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = require("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = require("./es5.js"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise) { + return function(err, value) { + if (promise === null) return; + + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (arguments.length > 2) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + promise._fulfill(args); + } else { + promise._fulfill(value); + } + + promise = null; + }; +} + + +var PromiseResolver; +if (!haveGetters) { + PromiseResolver = function (promise) { + this.promise = promise; + this.asCallback = nodebackForPromise(promise); + this.callback = this.asCallback; + }; +} +else { + PromiseResolver = function (promise) { + this.promise = promise; + }; +} +if (haveGetters) { + var prop = { + get: function() { + return nodebackForPromise(this.promise); + } + }; + es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); + es5.defineProperty(PromiseResolver.prototype, "callback", prop); +} + +PromiseResolver._nodebackForPromise = nodebackForPromise; + +PromiseResolver.prototype.toString = function () { + return "[object PromiseResolver]"; +}; + +PromiseResolver.prototype.resolve = +PromiseResolver.prototype.fulfill = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._resolveCallback(value); +}; + +PromiseResolver.prototype.reject = function (reason) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._rejectCallback(reason); +}; + +PromiseResolver.prototype.progress = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._progress(value); +}; + +PromiseResolver.prototype.cancel = function (err) { + this.promise.cancel(err); +}; + +PromiseResolver.prototype.timeout = function () { + this.reject(new TimeoutError("timeout")); +}; + +PromiseResolver.prototype.isResolved = function () { + return this.promise.isResolved(); +}; + +PromiseResolver.prototype.toJSON = function () { + return this.promise.toJSON(); +}; + +module.exports = PromiseResolver; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js new file mode 100644 index 0000000..0355344 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js @@ -0,0 +1,291 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = require("./util.js"); +var nodebackForPromise = require("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = require("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyPropsPattern = + /^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/; +var defaultFilter = function(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} + +function isPromisified(fn) { + try { + return fn.__isPromisified__ === true; + } + catch (e) { + return false; + } +} + +function hasPromisified(obj, key, suffix) { + var val = util.getDataPropertyOrDefault(obj, key + suffix, + defaultPromisified); + return val ? isPromisified(val) : false; +} +function checkValid(ret, suffix, suffixRegexp) { + for (var i = 0; i < ret.length; i += 2) { + var key = ret[i]; + if (suffixRegexp.test(key)) { + var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); + for (var j = 0; j < ret.length; j += 2) { + if (ret[j] === keyWithoutAsyncSuffix) { + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a" + .replace("%s", suffix)); + } + } + } + } +} + +function promisifiableMethods(obj, suffix, suffixRegexp, filter) { + var keys = util.inheritedDataKeys(obj); + var ret = []; + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var value = obj[key]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} + +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!false) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { + var ret = [likelyArgumentCount]; + var min = Math.max(0, likelyArgumentCount - 1 - 3); + for(var i = likelyArgumentCount - 1; i >= min; --i) { + ret.push(i); + } + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { + ret.push(i); + } + return ret; +}; + +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; + +var parameterCount = function(fn) { + if (typeof fn.length === "number") { + return Math.max(Math.min(fn.length, 1023 + 1), 0); + } + return 0; +}; + +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn) { + var newParameterCount = Math.max(0, parameterCount(fn) - 1); + var argumentOrder = switchCaseArgumentOrder(newParameterCount); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; + + function generateCallForArgumentCount(count) { + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; + } + return ret.replace("{{args}}", args).replace(", ", comma); + } + + function generateArgumentSwitchCase() { + var ret = ""; + for (var i = 0; i < argumentOrder.length; ++i) { + ret += "case " + argumentOrder[i] +":" + + generateCallForArgumentCount(argumentOrder[i]); + } + + ret += " \n\ + default: \n\ + var args = new Array(len + 1); \n\ + var i = 0; \n\ + for (var i = 0; i < len; ++i) { \n\ + args[i] = arguments[i]; \n\ + } \n\ + args[i] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); + return ret; + } + + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "INTERNAL","'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + return promise; \n\ + }; \n\ + ret.__isPromisified__ = true; \n\ + return ret; \n\ + " + .replace("Parameters", parameterDeclaration(newParameterCount)) + .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode))( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + INTERNAL + ); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } + function promisified() { + var _receiver = receiver; + if (receiver === THIS) _receiver = this; + var promise = new Promise(INTERNAL); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; + var fn = nodebackForPromise(promise); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + return promise; + } + promisified.__isPromisified__ = true; + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier) { + var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); + var methods = + promisifiableMethods(obj, suffix, suffixRegexp, filter); + + for (var i = 0, len = methods.length; i < len; i+= 2) { + var key = methods[i]; + var fn = methods[i+1]; + var promisifiedKey = key + suffix; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver) { + return makeNodePromisified(callback, receiver, undefined, callback); +} + +Promise.promisify = function (fn, receiver) { + if (typeof fn !== "function") { + throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + if (isPromisified(fn)) { + return fn; + } + var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + util.copyDescriptors(fn, ret, propsFilter); + return ret; +}; + +Promise.promisifyAll = function (target, options) { + if (typeof target !== "function" && typeof target !== "object") { + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a"); + } + options = Object(options); + var suffix = options.suffix; + if (typeof suffix !== "string") suffix = defaultSuffix; + var filter = options.filter; + if (typeof filter !== "function") filter = defaultFilter; + var promisifier = options.promisifier; + if (typeof promisifier !== "function") promisifier = makeNodePromisified; + + if (!util.isIdentifier(suffix)) { + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); + } + + var keys = util.inheritedDataKeys(target); + for (var i = 0; i < keys.length; ++i) { + var value = target[keys[i]]; + if (keys[i] !== "constructor" && + util.isClass(value)) { + promisifyAll(value.prototype, suffix, filter, promisifier); + promisifyAll(value, suffix, filter, promisifier); + } + } + + return promisifyAll(target, suffix, filter, promisifier); +}; +}; + diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js new file mode 100644 index 0000000..d6f9e64 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js @@ -0,0 +1,79 @@ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = require("./util.js"); +var isObject = util.isObject; +var es5 = require("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; +}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val = {}; + var keyOffset = this.length(); + for (var i = 0, len = this.length(); i < len; ++i) { + val[this._values[i + keyOffset]] = this._values[i]; + } + this._resolve(val); + } +}; + +PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { + this._promise._progress({ + key: this._values[index + this.length()], + value: value + }); +}; + +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; + +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); + + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } + + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 4); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js new file mode 100644 index 0000000..84d57d5 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js @@ -0,0 +1,90 @@ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js new file mode 100644 index 0000000..30e7bb0 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js @@ -0,0 +1,47 @@ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = require("./util.js").isArray; + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else if (!isArray(promises)) { + return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 4 | 1); + } + var fulfill = ret._fulfill; + var reject = ret._reject; + for (var i = 0, len = promises.length; i < len; ++i) { + var val = promises[i]; + + if (val === undefined && !(i in promises)) { + continue; + } + + Promise.cast(val)._then(fulfill, reject, undefined, ret, null); + } + return ret; +} + +Promise.race = function (promises) { + return race(promises, undefined); +}; + +Promise.prototype.race = function () { + return race(this, undefined); +}; + +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js new file mode 100644 index 0000000..3192220 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js @@ -0,0 +1,146 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = require("./async.js"); +var util = require("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +function ReductionPromiseArray(promises, fn, accum, _each) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._preservedValues = _each === INTERNAL ? [] : null; + this._zerothIsAccum = (accum === undefined); + this._gotAccum = false; + this._reducingIndex = (this._zerothIsAccum ? 1 : 0); + this._valuesPhase = undefined; + var maybePromise = tryConvertToPromise(accum, this._promise); + var rejected = false; + var isPromise = maybePromise instanceof Promise; + if (isPromise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, -1); + } else if (maybePromise._isFulfilled()) { + accum = maybePromise._value(); + this._gotAccum = true; + } else { + this._reject(maybePromise._reason()); + rejected = true; + } + } + if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; + this._callback = fn; + this._accum = accum; + if (!rejected) async.invoke(init, this, undefined); +} +function init() { + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._init = function () {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); + } +}; + +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + values[index] = value; + var length = this.length(); + var preservedValues = this._preservedValues; + var isEach = preservedValues !== null; + var gotAccum = this._gotAccum; + var valuesPhase = this._valuesPhase; + var valuesPhaseIndex; + if (!valuesPhase) { + valuesPhase = this._valuesPhase = new Array(length); + for (valuesPhaseIndex=0; valuesPhaseIndex 10) || (version[0] > 0) + ? function(fn) { global.setImmediate(fn); } : process.nextTick; + + if (!schedule) { + if (typeof setImmediate !== "undefined") { + schedule = setImmediate; + } else if (typeof setTimeout !== "undefined") { + schedule = setTimeout; + } else { + schedule = noAsyncScheduler; + } + } +} else if (typeof MutationObserver !== "undefined") { + schedule = function(fn) { + var div = document.createElement("div"); + var observer = new MutationObserver(fn); + observer.observe(div, {attributes: true}); + return function() { div.classList.toggle("foo"); }; + }; + schedule.isStatic = true; +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js new file mode 100644 index 0000000..f9299c2 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js @@ -0,0 +1,40 @@ +"use strict"; +module.exports = + function(Promise, PromiseArray) { +var PromiseInspection = Promise.PromiseInspection; +var util = require("./util.js"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 268435456; + ret._settledValue = value; + this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 134217728; + ret._settledValue = reason; + this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return new SettledPromiseArray(this).promise(); +}; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js new file mode 100644 index 0000000..f3968cf --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js @@ -0,0 +1,125 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = require("./util.js"); +var RangeError = require("./errors.js").RangeError; +var AggregateError = require("./errors.js").AggregateError; +var isArray = util.isArray; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + this._addFulfilled(value); + if (this._fulfilled() === this.howMany()) { + this._values.length = this.howMany(); + if (this.howMany() === 1 && this._unwrap) { + this._resolve(this._values[0]); + } else { + this._resolve(this._values); + } + } + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + e.push(this._values[i]); + } + this._reject(e); + } +}; + +SomePromiseArray.prototype._fulfilled = function () { + return this._totalResolved; +}; + +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); +}; + +SomePromiseArray.prototype._addRejected = function (reason) { + this._values.push(reason); +}; + +SomePromiseArray.prototype._addFulfilled = function (value) { + this._values[this._totalResolved++] = value; +}; + +SomePromiseArray.prototype._canPossiblyFulfill = function () { + return this.length() - this._rejected(); +}; + +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); +}; + +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; + +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} + +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; + +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; + +Promise._SomePromiseArray = SomePromiseArray; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js new file mode 100644 index 0000000..7aac149 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js @@ -0,0 +1,94 @@ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValue = promise._settledValue; + } + else { + this._bitField = 0; + this._settledValue = undefined; + } +} + +PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.isFulfilled = +Promise.prototype._isFulfilled = function () { + return (this._bitField & 268435456) > 0; +}; + +PromiseInspection.prototype.isRejected = +Promise.prototype._isRejected = function () { + return (this._bitField & 134217728) > 0; +}; + +PromiseInspection.prototype.isPending = +Promise.prototype._isPending = function () { + return (this._bitField & 402653184) === 0; +}; + +PromiseInspection.prototype.isResolved = +Promise.prototype._isResolved = function () { + return (this._bitField & 402653184) > 0; +}; + +Promise.prototype.isPending = function() { + return this._target()._isPending(); +}; + +Promise.prototype.isRejected = function() { + return this._target()._isRejected(); +}; + +Promise.prototype.isFulfilled = function() { + return this._target()._isFulfilled(); +}; + +Promise.prototype.isResolved = function() { + return this._target()._isResolved(); +}; + +Promise.prototype._value = function() { + return this._settledValue; +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue; +}; + +Promise.prototype.value = function() { + var target = this._target(); + if (!target.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return target._settledValue; +}; + +Promise.prototype.reason = function() { + var target = this._target(); + if (!target.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + target._unsetRejectionIsUnhandled(); + return target._settledValue; +}; + + +Promise.PromiseInspection = PromiseInspection; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js new file mode 100644 index 0000000..c858f86 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js @@ -0,0 +1,89 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util.js"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) { + return obj; + } + else if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfillUnchecked, + ret._rejectUncheckedCheckError, + ret._progressUnchecked, + ret, + null + ); + return ret; + } + var then = util.tryCatch(getThen)(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + return doThenable(obj, then, context); + } + } + return obj; +} + +function getThen(obj) { + return obj.then; +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, + resolveFromThenable, + rejectFromThenable, + progressFromThenable); + synchronous = false; + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolveFromThenable(value) { + if (!promise) return; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + promise._resolveCallback(value); + } + promise = null; + } + + function rejectFromThenable(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + + function progressFromThenable(value) { + if (!promise) return; + if (typeof promise._progress === "function") { + promise._progress(value); + } + } + return ret; +} + +return tryConvertToPromise; +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js new file mode 100644 index 0000000..ecf1b57 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + if (typeof message !== "string") { + message = "operation timed out"; + } + var err = new TimeoutError(message); + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._cancel(err); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (value, ms) { + if (ms === undefined) { + ms = value; + value = undefined; + var ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, ms); + return ret; + } + ms = +ms; + return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); +}; + +Promise.prototype.delay = function (ms) { + return delay(this, ms); +}; + +function successClear(value) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + return value; +} + +function failureClear(reason) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret = this.then().cancellable(); + ret._cancellationParent = this; + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js new file mode 100644 index 0000000..4038711 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js @@ -0,0 +1,202 @@ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = require("./errors.js").TypeError; + var inherits = require("./util.js").inherits; + var PromiseInspection = Promise.PromiseInspection; + + function inspectionMapper(inspections) { + var len = inspections.length; + for (var i = 0; i < len; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + return Promise.reject(inspection.error()); + } + inspections[i] = inspection._settledValue; + } + return inspections; + } + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + if (maybePromise !== thenable && + typeof thenable._isDisposable === "function" && + typeof thenable._getDisposer === "function" && + thenable._isDisposable()) { + maybePromise._setDisposable(thenable._getDisposer()); + } + return maybePromise; + } + function dispose(resources, inspection) { + var i = 0; + var len = resources.length; + var ret = Promise.defer(); + function iterator() { + if (i >= len) return ret.resolve(); + var maybePromise = castPreservingDisposable(resources[i++]); + if (maybePromise instanceof Promise && + maybePromise._isDisposable()) { + try { + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); + } catch (e) { + return thrower(e); + } + if (maybePromise instanceof Promise) { + return maybePromise._then(iterator, thrower, + null, null, null); + } + } + iterator(); + } + iterator(); + return ret.promise; + } + + function disposerSuccess(value) { + var inspection = new PromiseInspection(); + inspection._settledValue = value; + inspection._bitField = 268435456; + return dispose(this, inspection).thenReturn(value); + } + + function disposerFail(reason) { + var inspection = new PromiseInspection(); + inspection._settledValue = reason; + inspection._bitField = 134217728; + return dispose(this, inspection).thenThrow(reason); + } + + function Disposer(data, promise, context) { + this._data = data; + this._promise = promise; + this._context = context; + } + + Disposer.prototype.data = function () { + return this._data; + }; + + Disposer.prototype.promise = function () { + return this._promise; + }; + + Disposer.prototype.resource = function () { + if (this.promise().isFulfilled()) { + return this.promise().value(); + } + return null; + }; + + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== null + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; + + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); + }; + + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); + + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); + }; + + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); + } + return value; + } + + Promise.using = function () { + var len = arguments.length; + if (len < 2) return apiRejection( + "you must pass at least 2 arguments to Promise.using"); + var fn = arguments[len - 1]; + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } + } + resources[i] = resource; + } + + var promise = Promise.settle(resources) + .then(inspectionMapper) + .then(function(vals) { + promise._pushContext(); + var ret; + try { + ret = fn.apply(undefined, vals); + } finally { + promise._popContext(); + } + return ret; + }) + ._then( + disposerSuccess, disposerFail, undefined, resources, undefined); + resources.promise = promise; + return promise; + }; + + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 262144; + this._disposer = disposer; + }; + + Promise.prototype._isDisposable = function () { + return (this._bitField & 262144) > 0; + }; + + Promise.prototype._getDisposer = function () { + return this._disposer; + }; + + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~262144); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); + }; + +}; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js new file mode 100644 index 0000000..fbee5de --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js @@ -0,0 +1,280 @@ +"use strict"; +var es5 = require("./es5.js"); +var canEvaluate = typeof navigator == "undefined"; +var haveGetters = (function(){ + try { + var o = {}; + es5.defineProperty(o, "f", { + get: function () { + return 3; + } + }); + return o.f === 3; + } + catch (e) { + return false; + } + +})(); + +var errorObj = {e: {}}; +var tryCatchTarget; +function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } + } + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return !isPrimitive(value); +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); +} + +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; +} + +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} + +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; +} + + +var wrapsPrimitiveReceiver = (function() { + return this !== "string"; +}).call("string"); + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + if (es5.isES5) { + var oProto = Object.prototype; + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && obj !== oProto) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function f() {} + f.prototype = obj; + var l = 8; + while (l--) new f(); + return obj; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + haveGetters: haveGetters, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" +}; +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json new file mode 100644 index 0000000..0926364 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json @@ -0,0 +1,96 @@ +{ + "name": "bluebird", + "description": "Full featured Promises/A+ implementation with exceptionally good performance", + "version": "2.9.26", + "keywords": [ + "promise", + "performance", + "promises", + "promises-a", + "promises-aplus", + "async", + "await", + "deferred", + "deferreds", + "future", + "flow control", + "dsl", + "fluent interface" + ], + "scripts": { + "lint": "node scripts/jshint.js", + "test": "node tools/test.js", + "istanbul": "istanbul", + "prepublish": "node tools/build.js --no-debug --main --zalgo --browser --minify" + }, + "homepage": "https://github.com/petkaantonov/bluebird", + "repository": { + "type": "git", + "url": "git://github.com/petkaantonov/bluebird.git" + }, + "bugs": { + "url": "http://github.com/petkaantonov/bluebird/issues" + }, + "license": "MIT", + "author": { + "name": "Petka Antonov", + "email": "petka_antonov@hotmail.com", + "url": "http://github.com/petkaantonov/" + }, + "devDependencies": { + "acorn": "~0.6.0", + "baconjs": "^0.7.43", + "bluebird": "^2.9.2", + "body-parser": "^1.10.2", + "browserify": "^8.1.1", + "cli-table": "~0.3.1", + "co": "^4.2.0", + "cross-spawn": "^0.2.3", + "glob": "^4.3.2", + "grunt-saucelabs": "~8.4.1", + "highland": "^2.3.0", + "istanbul": "^0.3.5", + "jshint": "^2.6.0", + "jshint-stylish": "~0.2.0", + "mkdirp": "~0.5.0", + "mocha": "~2.1", + "open": "~0.0.5", + "optimist": "~0.6.1", + "rimraf": "~2.2.6", + "rx": "^2.3.25", + "serve-static": "^1.7.1", + "sinon": "~1.7.3", + "uglify-js": "~2.4.16" + }, + "main": "./js/main/bluebird.js", + "browser": "./js/browser/bluebird.js", + "files": [ + "js/browser", + "js/main", + "js/zalgo", + "LICENSE", + "zalgo.js" + ], + "gitHead": "c6604d44f219af9da683f6e28d818008fa374af2", + "_id": "bluebird@2.9.26", + "_shasum": "362772ea4d09f556a4b9f3b64c2fd136e87e3a55", + "_from": "bluebird@2.9.26", + "_npmVersion": "2.7.1", + "_nodeVersion": "1.6.2", + "_npmUser": { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + }, + "maintainers": [ + { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + } + ], + "dist": { + "shasum": "362772ea4d09f556a4b9f3b64c2fd136e87e3a55", + "tarball": "http://registry.npmjs.org/bluebird/-/bluebird-2.9.26.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.9.26.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/.jshintrc b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md new file mode 100644 index 0000000..854c971 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md @@ -0,0 +1,195 @@ + +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 +================== + + * 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/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile new file mode 100644 index 0000000..5cf4a59 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile @@ -0,0 +1,36 @@ + +# 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 dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +distclean: clean + @rm -rf node_modules + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean distclean diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md new file mode 100644 index 0000000..b4f45e3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md @@ -0,0 +1,188 @@ +# 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'); +``` + +### 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 + - 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/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/bower.json b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/bower.json new file mode 100644 index 0000000..6af573f --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/bower.json @@ -0,0 +1,28 @@ +{ + "name": "visionmedia-debug", + "main": "dist/debug.js", + "version": "2.2.0", + "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/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/browser.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/browser.js new file mode 100644 index 0000000..7c76452 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/browser.js @@ -0,0 +1,168 @@ + +/** + * 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; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : 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) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.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/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/component.json b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/component.json new file mode 100644 index 0000000..ca10637 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.2.0", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js new file mode 100644 index 0000000..7571a86 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * 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/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/node.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/node.js new file mode 100644 index 0000000..1d392a8 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/node.js @@ -0,0 +1,209 @@ + +/** + * 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/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json new file mode 100644 index 0000000..d22f5cf --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json @@ -0,0 +1,72 @@ +{ + "name": "debug", + "version": "2.2.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "license": "MIT", + "dependencies": { + "ms": "0.7.1" + }, + "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": "b38458422b5aa8aa6d286b10dfe427e8a67e2b35", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@2.2.0", + "scripts": {}, + "_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "_from": "debug@2.2.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "tarball": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.npmignore b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.travis.yml b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.travis.yml new file mode 100644 index 0000000..895dbd3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/History.md b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/History.md new file mode 100644 index 0000000..33abe6d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/History.md @@ -0,0 +1,30 @@ + +0.0.5 / 2013-02-05 +================== + + * optimization: remove use of arguments [jkroso](https://github.com/jkroso) + * add scripts to component.json [jkroso](https://github.com/jkroso) + * tests; remove time for travis + +0.0.4 / 2013-01-07 +================== + + * added component.json #1 [jkroso](https://github.com/jkroso) + * reversed array loop #1 [jkroso](https://github.com/jkroso) + * remove fn params + +0.0.3 / 2012-09-29 +================== + + * faster with negative start args + +0.0.2 / 2012-09-29 +================== + + * support full [].slice semantics + +0.0.1 / 2012-09-29 +=================== + + * initial release + diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/LICENSE b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/LICENSE @@ -0,0 +1,22 @@ +(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/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/Makefile b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/Makefile new file mode 100644 index 0000000..2ad4e47 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/Makefile @@ -0,0 +1,5 @@ + +test: + @./node_modules/.bin/mocha $(T) $(TESTS) + +.PHONY: test diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/README.md b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/README.md new file mode 100644 index 0000000..6605c39 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/README.md @@ -0,0 +1,62 @@ +#sliced +========== + +A faster alternative to `[].slice.call(arguments)`. + +[![Build Status](https://secure.travis-ci.org/aheckmann/sliced.png)](http://travis-ci.org/aheckmann/sliced) + +Example output from [benchmark.js](https://github.com/bestiejs/benchmark.js) + + Array.prototype.slice.call x 1,320,205 ops/sec ±2.35% (92 runs sampled) + [].slice.call x 1,314,605 ops/sec ±1.60% (95 runs sampled) + cached slice.call x 10,468,380 ops/sec ±1.45% (95 runs sampled) + sliced x 16,608,237 ops/sec ±1.40% (92 runs sampled) + fastest is sliced + + Array.prototype.slice.call(arguments, 1) x 1,383,584 ops/sec ±1.73% (97 runs sampled) + [].slice.call(arguments, 1) x 1,494,735 ops/sec ±1.33% (95 runs sampled) + cached slice.call(arguments, 1) x 10,085,270 ops/sec ±1.51% (97 runs sampled) + sliced(arguments, 1) x 16,620,480 ops/sec ±1.29% (95 runs sampled) + fastest is sliced(arguments, 1) + + Array.prototype.slice.call(arguments, -1) x 1,303,262 ops/sec ±1.62% (94 runs sampled) + [].slice.call(arguments, -1) x 1,325,615 ops/sec ±1.36% (97 runs sampled) + cached slice.call(arguments, -1) x 9,673,603 ops/sec ±1.70% (96 runs sampled) + sliced(arguments, -1) x 16,384,575 ops/sec ±1.06% (91 runs sampled) + fastest is sliced(arguments, -1) + + Array.prototype.slice.call(arguments, -2, -10) x 1,404,390 ops/sec ±1.61% (95 runs sampled) + [].slice.call(arguments, -2, -10) x 1,514,367 ops/sec ±1.21% (96 runs sampled) + cached slice.call(arguments, -2, -10) x 9,836,017 ops/sec ±1.21% (95 runs sampled) + sliced(arguments, -2, -10) x 18,544,882 ops/sec ±1.30% (91 runs sampled) + fastest is sliced(arguments, -2, -10) + + Array.prototype.slice.call(arguments, -2, -1) x 1,458,604 ops/sec ±1.41% (97 runs sampled) + [].slice.call(arguments, -2, -1) x 1,536,547 ops/sec ±1.63% (99 runs sampled) + cached slice.call(arguments, -2, -1) x 10,060,633 ops/sec ±1.37% (96 runs sampled) + sliced(arguments, -2, -1) x 18,608,712 ops/sec ±1.08% (93 runs sampled) + fastest is sliced(arguments, -2, -1) + +_Benchmark [source](https://github.com/aheckmann/sliced/blob/master/bench.js)._ + +##Usage + +`sliced` accepts the same arguments as `Array#slice` so you can easily swap it out. + +```js +function zing () { + var slow = [].slice.call(arguments, 1, 8); + var args = slice(arguments, 1, 8); + + var slow = Array.prototype.slice.call(arguments); + var args = slice(arguments); + // etc +} +``` + +## install + + npm install sliced + + +[LICENSE](https://github.com/aheckmann/sliced/blob/master/LICENSE) diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/bench.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/bench.js new file mode 100644 index 0000000..f201d16 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/bench.js @@ -0,0 +1,95 @@ + +var sliced = require('./') +var Bench = require('benchmark'); +var s = new Bench.Suite; +var slice = [].slice; + +s.add('Array.prototype.slice.call', function () { + Array.prototype.slice.call(arguments); +}).add('[].slice.call', function () { + [].slice.call(arguments); +}).add('cached slice.call', function () { + slice.call(arguments) +}).add('sliced', function () { + sliced(arguments) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, 1)', function () { + Array.prototype.slice.call(arguments, 1); +}).add('[].slice.call(arguments, 1)', function () { + [].slice.call(arguments, 1); +}).add('cached slice.call(arguments, 1)', function () { + slice.call(arguments, 1) +}).add('sliced(arguments, 1)', function () { + sliced(arguments, 1) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, -1)', function () { + Array.prototype.slice.call(arguments, -1); +}).add('[].slice.call(arguments, -1)', function () { + [].slice.call(arguments, -1); +}).add('cached slice.call(arguments, -1)', function () { + slice.call(arguments, -1) +}).add('sliced(arguments, -1)', function () { + sliced(arguments, -1) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, -2, -10)', function () { + Array.prototype.slice.call(arguments, -2, -10); +}).add('[].slice.call(arguments, -2, -10)', function () { + [].slice.call(arguments, -2, -10); +}).add('cached slice.call(arguments, -2, -10)', function () { + slice.call(arguments, -2, -10) +}).add('sliced(arguments, -2, -10)', function () { + sliced(arguments, -2, -10) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, -2, -1)', function () { + Array.prototype.slice.call(arguments, -2, -1); +}).add('[].slice.call(arguments, -2, -1)', function () { + [].slice.call(arguments, -2, -1); +}).add('cached slice.call(arguments, -2, -1)', function () { + slice.call(arguments, -2, -1) +}).add('sliced(arguments, -2, -1)', function () { + sliced(arguments, -2, -1) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +/** + * Output: + * + * Array.prototype.slice.call x 1,289,592 ops/sec ±2.88% (87 runs sampled) + * [].slice.call x 1,345,451 ops/sec ±1.68% (97 runs sampled) + * cached slice.call x 10,719,886 ops/sec ±1.04% (99 runs sampled) + * sliced x 15,809,545 ops/sec ±1.46% (93 runs sampled) + * fastest is sliced + * + */ diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/component.json b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/component.json new file mode 100644 index 0000000..57e9e0c --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/component.json @@ -0,0 +1,14 @@ +{ + "name": "sliced", + "version": "0.0.5", + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "repo" : "aheckmann/sliced", + "keywords": [ + "arguments", + "slice", + "array" + ], + "scripts": ["lib/sliced.js", "index.js"], + "author": "Aaron Heckmann ", + "license": "MIT" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/index.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/index.js new file mode 100644 index 0000000..3b90ae7 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/index.js @@ -0,0 +1 @@ +module.exports = exports = require('./lib/sliced'); diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/lib/sliced.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/lib/sliced.js new file mode 100644 index 0000000..d88c85b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/lib/sliced.js @@ -0,0 +1,33 @@ + +/** + * An Array.prototype.slice.call(arguments) alternative + * + * @param {Object} args something with a length + * @param {Number} slice + * @param {Number} sliceEnd + * @api public + */ + +module.exports = function (args, slice, sliceEnd) { + var ret = []; + var len = args.length; + + if (0 === len) return ret; + + var start = slice < 0 + ? Math.max(0, slice + len) + : slice || 0; + + if (sliceEnd !== undefined) { + len = sliceEnd < 0 + ? sliceEnd + len + : sliceEnd + } + + while (len-- > start) { + ret[len - start] = args[len]; + } + + return ret; +} + diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/package.json b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/package.json new file mode 100644 index 0000000..4db2cd4 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/package.json @@ -0,0 +1,52 @@ +{ + "name": "sliced", + "version": "0.0.5", + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/sliced.git" + }, + "keywords": [ + "arguments", + "slice", + "array" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.5.0", + "benchmark": "~1.0.0" + }, + "_id": "sliced@0.0.5", + "dist": { + "shasum": "5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", + "tarball": "http://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz" + }, + "_npmVersion": "1.1.59", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "directories": {}, + "_shasum": "5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", + "_resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", + "_from": "sliced@0.0.5", + "bugs": { + "url": "https://github.com/aheckmann/sliced/issues" + }, + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/aheckmann/sliced#readme" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/test/index.js b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/test/index.js new file mode 100644 index 0000000..33d36a1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/node_modules/sliced/test/index.js @@ -0,0 +1,80 @@ + +var sliced = require('../') +var assert = require('assert') + +describe('sliced', function(){ + it('exports a function', function(){ + assert.equal('function', typeof sliced); + }) + describe('with 1 arg', function(){ + it('returns an array of the arg', function(){ + var o = [3, "4", {}]; + var r = sliced(o); + assert.equal(3, r.length); + assert.equal(o[0], r[0]); + assert.equal(o[1], r[1]); + assert.equal(o[1], r[1]); + }) + }) + describe('with 2 args', function(){ + it('returns an array of the arg starting at the 2nd arg', function(){ + var o = [3, "4", 5, null]; + var r = sliced(o, 2); + assert.equal(2, r.length); + assert.equal(o[2], r[0]); + assert.equal(o[3], r[1]); + }) + }) + describe('with 3 args', function(){ + it('returns an array of the arg from the 2nd to the 3rd arg', function(){ + var o = [3, "4", 5, null]; + var r = sliced(o, 1, 2); + assert.equal(1, r.length); + assert.equal(o[1], r[0]); + }) + }) + describe('with negative start and no end', function(){ + it('begins at an offset from the end and includes all following elements', function(){ + var o = [3, "4", 5, null]; + var r = sliced(o, -2); + assert.equal(2, r.length); + assert.equal(o[2], r[0]); + assert.equal(o[3], r[1]); + + var r = sliced(o, -12); + assert.equal(4, r.length); + assert.equal(o[0], r[0]); + assert.equal(o[1], r[1]); + }) + }) + describe('with negative start and positive end', function(){ + it('begins at an offset from the end and includes `end` elements', function(){ + var o = [3, "4", {x:1}, null]; + + var r = sliced(o, -2, 1); + assert.equal(0, r.length); + + var r = sliced(o, -2, 2); + assert.equal(0, r.length); + + var r = sliced(o, -2, 3); + assert.equal(1, r.length); + assert.equal(o[2], r[0]); + }) + }) + describe('with negative start and negative end', function(){ + it('begins at `start` offset from the end and includes all elements up to `end` offset from the end', function(){ + var o = [3, "4", {x:1}, null]; + var r = sliced(o, -3, -1); + assert.equal(2, r.length); + assert.equal(o[1], r[0]); + assert.equal(o[2], r[1]); + + var r = sliced(o, -3, -3); + assert.equal(0, r.length); + + var r = sliced(o, -3, -4); + assert.equal(0, r.length); + }) + }) +}) diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/package.json b/5-2/service/node_modules/mongoose/node_modules/mquery/package.json new file mode 100644 index 0000000..b05ee08 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/package.json @@ -0,0 +1,68 @@ +{ + "name": "mquery", + "version": "1.6.3", + "description": "Expressive query building for MongoDB", + "main": "lib/mquery.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mquery.git" + }, + "dependencies": { + "bluebird": "2.9.26", + "debug": "2.2.0", + "regexp-clone": "0.0.1", + "sliced": "0.0.5" + }, + "devDependencies": { + "mongodb": "1.4.38", + "mocha": "1.9.x", + "istanbul": "0.3.2" + }, + "bugs": { + "url": "https://github.com/aheckmann/mquery/issues/new" + }, + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "keywords": [ + "mongodb", + "query", + "builder" + ], + "homepage": "https://github.com/aheckmann/mquery/", + "gitHead": "cd0c3284df2089eed5f0a331802e15c6ff0e7fab", + "_id": "mquery@1.6.3", + "_shasum": "7c02bfb7e49c8012cece1556c5e65fef61f3c8e5", + "_from": "mquery@1.6.3", + "_npmVersion": "2.9.1", + "_nodeVersion": "0.12.3", + "_npmUser": { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + "dist": { + "shasum": "7c02bfb7e49c8012cece1556c5e65fef61f3c8e5", + "tarball": "http://registry.npmjs.org/mquery/-/mquery-1.6.3.tgz" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "ebensing", + "email": "ebensing38@gmail.com" + }, + { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/mquery/-/mquery-1.6.3.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/test/collection/browser.js b/5-2/service/node_modules/mongoose/node_modules/mquery/test/collection/browser.js new file mode 100644 index 0000000..e69de29 diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js b/5-2/service/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js new file mode 100644 index 0000000..e69de29 diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/test/collection/node.js b/5-2/service/node_modules/mongoose/node_modules/mquery/test/collection/node.js new file mode 100644 index 0000000..43f446e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/test/collection/node.js @@ -0,0 +1,29 @@ + +var assert = require('assert') +var slice = require('sliced') +var mongo = require('mongodb') +var utils = require('../../').utils; + +var uri = process.env.MQUERY_URI || 'mongodb://localhost/mquery'; +var db; + +exports.getCollection = function (cb) { + mongo.Db.connect(uri, function (err, db_) { + assert.ifError(err); + db = db_; + + var collection = db.collection('stuff'); + collection.opts.safe = true; + + // clean test db before starting + db.dropDatabase(function () { + cb(null, collection); + }); + }) +} + +exports.dropCollection = function (cb) { + db.dropDatabase(function () { + db.close(cb); + }) +} diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/test/env.js b/5-2/service/node_modules/mongoose/node_modules/mquery/test/env.js new file mode 100644 index 0000000..9b9b80b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/test/env.js @@ -0,0 +1,20 @@ + +var assert = require('assert') +var env = require('../').env; + +console.log('environment: %s', env.type); + +var col; +switch (env.type) { + case 'node': + col = require('./collection/node'); + break; + case 'mongo': + col = require('./collection/mongo'); + case 'browser': + col = require('./collection/browser'); + default: + throw new Error('missing collection implementation for environment: ' + env.type); +} + +module.exports = exports = col; diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/test/index.js b/5-2/service/node_modules/mongoose/node_modules/mquery/test/index.js new file mode 100644 index 0000000..747c947 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/test/index.js @@ -0,0 +1,2875 @@ +var mquery = require('../'); +var assert = require('assert'); + +describe('mquery', function(){ + var col; + + before(function(done){ + // get the env specific collection interface + require('./env').getCollection(function (err, collection) { + assert.ifError(err); + col = collection; + done(); + }); + }) + + after(function(done){ + require('./env').dropCollection(done); + }) + + describe('mquery', function(){ + it('is a function', function(){ + assert.equal('function', typeof mquery); + }) + it('creates instances with the `new` keyword', function(){ + assert.ok(mquery() instanceof mquery); + }) + describe('defaults', function(){ + it('are set', function(){ + var m = mquery(); + assert.strictEqual(undefined, m.op); + assert.deepEqual({}, m.options); + }) + }) + describe('criteria', function(){ + it('if collection-like is used as collection', function(){ + var m = mquery(col); + assert.equal(col, m._collection.collection); + }) + it('non-collection-like is used as criteria', function(){ + var m = mquery({ works: true }); + assert.ok(!m._collection); + assert.deepEqual({ works: true }, m._conditions); + }) + }) + describe('options', function(){ + it('are merged when passed', function(){ + var m = mquery(col, { safe: true }); + assert.deepEqual({ safe: true }, m.options); + var m = mquery({ name: 'mquery' }, { safe: true }); + assert.deepEqual({ safe: true }, m.options); + }) + }) + }) + + describe('toConstructor', function(){ + it('creates subclasses of mquery', function(){ + var opts = { safe: { w: 'majority' }, readPreference: 'p' }; + var match = { name: 'test', count: { $gt: 101 }}; + var select = { name: 1, count: 0 } + var update = { $set: { x: true }}; + var path = 'street'; + + var q = mquery().setOptions(opts); + q.where(match); + q.select(select); + q.update(update); + q.where(path); + q.find(); + + var M = q.toConstructor(); + var m = M(); + + assert.ok(m instanceof mquery); + assert.deepEqual(opts, m.options); + assert.deepEqual(match, m._conditions); + assert.deepEqual(select, m._fields); + assert.deepEqual(update, m._update); + assert.equal(path, m._path); + assert.equal('find', m.op); + }) + }) + + describe('setOptions', function(){ + it('calls associated methods', function(){ + var m = mquery(); + assert.equal(m._collection, null); + m.setOptions({ collection: col }); + assert.equal(m._collection.collection, col); + }) + it('directly sets option when no method exists', function(){ + var m = mquery(); + assert.equal(m.options.woot, null); + m.setOptions({ woot: 'yay' }); + assert.equal(m.options.woot, 'yay'); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.setOptions(); + assert.equal(m, n); + var n = m.setOptions({ x: 1 }); + assert.equal(m, n); + }) + }) + + describe('collection', function(){ + it('sets the _collection', function(){ + var m = mquery(); + m.collection(col); + assert.equal(m._collection.collection, col); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.collection(col); + assert.equal(m, n); + }) + }) + + describe('$where', function(){ + it('sets the $where condition', function(){ + var m = mquery(); + function go () {} + m.$where(go); + assert.ok(go === m._conditions.$where); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.$where('x'); + assert.equal(m, n); + }) + }) + + describe('where', function(){ + it('without arguments', function(){ + var m = mquery(); + m.where(); + assert.deepEqual({}, m._conditions); + }) + it('with non-string/object argument', function(){ + var m = mquery(); + + assert.throws(function(){ + m.where([]); + }, /path must be a string or object/); + }) + describe('with one argument', function(){ + it('that is an object', function(){ + var m = mquery(); + m.where({ name: 'flawed' }); + assert.strictEqual(m._conditions.name, 'flawed'); + }) + it('that is a query', function(){ + var m = mquery({ name: 'first' }); + var n = mquery({ name: 'changed' }); + m.where(n); + assert.strictEqual(m._conditions.name, 'changed'); + }) + it('that is a string', function(){ + var m = mquery(); + m.where('name'); + assert.equal('name', m._path); + assert.strictEqual(m._conditions.name, undefined); + }) + }) + it('with two arguments', function(){ + var m = mquery(); + m.where('name', 'The Great Pumpkin'); + assert.equal('name', m._path); + assert.strictEqual(m._conditions.name, 'The Great Pumpkin'); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.where('x', 'y'); + assert.equal(m, n); + var n = m.where() + assert.equal(m, n); + }) + }) + + describe('equals', function(){ + it('must be called after where()', function(){ + var m = mquery(); + assert.throws(function () { + m.equals(); + }, /must be used after where/) + }) + it('sets value of path set with where()', function(){ + var m = mquery(); + m.where('age').equals(1000); + assert.deepEqual({ age: 1000 }, m._conditions); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.where('x').equals(3); + assert.equal(m, n); + }) + }) + + describe('or', function(){ + it('pushes onto the internal $or condition', function(){ + var m = mquery(); + m.or({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$or) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.or(arg); + assert.deepEqual(arg, m._conditions.$or) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.or(arg); + m.or({ y: 1 }) + m.or([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$or) + }) + it('is chainable', function(){ + var m = mquery(); + m.or({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $or: [{ o: 'k' }] }, m._conditions) + }) + }) + + describe('nor', function(){ + it('pushes onto the internal $nor condition', function(){ + var m = mquery(); + m.nor({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$nor) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.nor(arg); + assert.deepEqual(arg, m._conditions.$nor) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.nor(arg); + m.nor({ y: 1 }) + m.nor([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$nor) + }) + it('is chainable', function(){ + var m = mquery(); + m.nor({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $nor: [{ o: 'k' }] }, m._conditions) + }) + }) + + describe('and', function(){ + it('pushes onto the internal $and condition', function(){ + var m = mquery(); + m.and({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$and) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.and(arg); + assert.deepEqual(arg, m._conditions.$and) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.and(arg); + m.and({ y: 1 }) + m.and([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$and) + }) + it('is chainable', function(){ + var m = mquery(); + m.and({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $and: [{ o: 'k' }] }, m._conditions) + }) + }) + + function generalCondition (type) { + return function () { + it('accepts 2 args', function(){ + var m = mquery()[type]('count', 3); + var check = {}; + check['$' + type] = 3; + assert.deepEqual(m._conditions.count, check); + }) + it('uses previously set `where` path if 1 arg passed', function(){ + var m = mquery().where('count')[type](3); + var check = {}; + check['$' + type] = 3; + assert.deepEqual(m._conditions.count, check); + }) + it('throws if 1 arg was passed but no previous `where` was used', function(){ + assert.throws(function(){ + mquery()[type](3); + }, /must be used after where/); + }) + it('is chainable', function(){ + var m = mquery().where('count')[type](3).where('x', 8); + var check = {x: 8, count: {}}; + check.count['$' + type] = 3; + assert.deepEqual(m._conditions, check); + }) + it('overwrites previous value', function(){ + var m = mquery().where('count')[type](3)[type](8); + var check = {}; + check['$' + type] = 8; + assert.deepEqual(m._conditions.count, check); + }) + } + } + + 'gt gte lt lte ne in nin regex size maxDistance'.split(' ').forEach(function (type) { + describe(type, generalCondition(type)) + }) + + describe('mod', function () { + describe('with 1 argument', function(){ + it('requires a previous where()', function(){ + assert.throws(function () { + mquery().mod([30, 10]) + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('madmen').mod([10,20]); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + }) + + describe('with 2 arguments and second is non-Array', function(){ + it('requires a previous where()', function(){ + assert.throws(function () { + mquery().mod('x', 10) + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('madmen').mod(10, 20); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + }) + + it('with 2 arguments and second is an array', function(){ + var m = mquery().mod('madmen', [10,20]); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + + it('with 3 arguments', function(){ + var m = mquery().mod('madmen', 10, 20); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + + it('is chainable', function(){ + var m = mquery().mod('madmen', 10, 20).where('x', 8); + var check = { madmen: { $mod: [10,20] }, x: 8}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('exists', function(){ + it('with 0 args', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().exists() + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('name').exists(); + var check = { name: { $exists: true }}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('with 1 arg', function(){ + describe('that is boolean', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().exists() + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().exists('name', false); + var check = { name: { $exists: false }}; + assert.deepEqual(m._conditions, check); + }) + }) + describe('that is not boolean', function(){ + it('sets the value to `true`', function(){ + var m = mquery().where('name').exists('yummy'); + var check = { yummy: { $exists: true }}; + assert.deepEqual(m._conditions, check); + }) + }) + }) + + describe('with 2 args', function(){ + it('works', function(){ + var m = mquery().exists('yummy', false); + var check = { yummy: { $exists: false }}; + assert.deepEqual(m._conditions, check); + }) + }) + + it('is chainable', function(){ + var m = mquery().where('name').exists().find({ x: 1 }); + var check = { name: { $exists: true }, x: 1}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('elemMatch', function(){ + describe('with null/undefined first argument', function(){ + assert.throws(function () { + mquery().elemMatch(); + }, /Invalid argument/); + assert.throws(function () { + mquery().elemMatch(null); + }, /Invalid argument/); + assert.doesNotThrow(function () { + mquery().elemMatch('', {}); + }); + }) + + describe('with 1 argument', function(){ + it('throws if not a function or object', function(){ + assert.throws(function () { + mquery().elemMatch([]); + }, /Invalid argument/); + }) + + describe('that is an object', function(){ + it('throws if no previous `where` was used', function(){ + assert.throws(function () { + mquery().elemMatch({}); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('comment').elemMatch({ author: 'joe', votes: {$gte: 3 }}); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + describe('that is a function', function(){ + it('throws if no previous `where` was used', function(){ + assert.throws(function () { + mquery().elemMatch(function(){}); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('comment').elemMatch(function (query) { + query.where({ author: 'joe', votes: {$gte: 3 }}) + }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + }) + + describe('with 2 arguments', function(){ + describe('and the 2nd is an object', function(){ + it('works', function(){ + var m = mquery().elemMatch('comment', { author: 'joe', votes: {$gte: 3 }}); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + describe('and the 2nd is a function', function(){ + it('works', function(){ + var m = mquery().elemMatch('comment', function (query) { + query.where({ author: 'joe', votes: {$gte: 3 }}) + }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + it('and the 2nd is not a function or object', function(){ + assert.throws(function () { + mquery().elemMatch('comment', []); + }, /Invalid argument/); + }) + }) + }) + + describe('within', function(){ + it('is chainable', function(){ + var m = mquery(); + assert.equal(m.where('a').within(), m); + }) + describe('when called with arguments', function(){ + it('must follow where()', function(){ + assert.throws(function () { + mquery().within([]); + }, /must be used after where/); + }) + + describe('of length 1', function(){ + it('throws if not a recognized shape', function(){ + assert.throws(function () { + mquery().where('loc').within({}); + }, /Invalid argument/) + assert.throws(function () { + mquery().where('loc').within(null); + }, /Invalid argument/) + }) + it('delegates to circle when center exists', function(){ + var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); + assert.deepEqual({ $geoWithin: {$center:[[10,10], 3]}}, m._conditions.loc); + }) + it('delegates to box when exists', function(){ + var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); + assert.deepEqual({ $geoWithin: {$box:[[10,10], [11,14]]}}, m._conditions.loc); + }) + it('delegates to polygon when exists', function(){ + var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $geoWithin: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); + }) + it('delegates to geometry when exists', function(){ + var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $geoWithin: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); + }) + }) + + describe('of length 2', function(){ + it('delegates to box()', function(){ + var m = mquery().where('loc').within([1,2],[2,5]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[2,5]]}}); + }) + }) + + describe('of length > 2', function(){ + it('delegates to polygon()', function(){ + var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); + }) + }) + }) + }) + + describe('geoWithin', function(){ + before(function(){ + mquery.use$geoWithin = false; + }) + after(function(){ + mquery.use$geoWithin = true; + }) + describe('when called with arguments', function(){ + describe('of length 1', function(){ + it('delegates to circle when center exists', function(){ + var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); + assert.deepEqual({ $within: {$center:[[10,10], 3]}}, m._conditions.loc); + }) + it('delegates to box when exists', function(){ + var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); + assert.deepEqual({ $within: {$box:[[10,10], [11,14]]}}, m._conditions.loc); + }) + it('delegates to polygon when exists', function(){ + var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $within: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); + }) + it('delegates to geometry when exists', function(){ + var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $within: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); + }) + }) + + describe('of length 2', function(){ + it('delegates to box()', function(){ + var m = mquery().where('loc').within([1,2],[2,5]); + assert.deepEqual(m._conditions.loc, { $within: { $box: [[1,2],[2,5]]}}); + }) + }) + + describe('of length > 2', function(){ + it('delegates to polygon()', function(){ + var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); + assert.deepEqual(m._conditions.loc, { $within: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); + }) + }) + }) + }) + + describe('box', function(){ + describe('with 1 argument', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().box('sometihng'); + }, /Invalid argument/); + }) + }) + describe('with > 3 arguments', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().box(1,2,3,4); + }, /Invalid argument/); + }) + }) + + describe('with 2 arguments', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().box([],[]); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('loc').box([1,2],[3,4]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); + }) + }) + + describe('with 3 arguments', function(){ + it('works', function(){ + var m = mquery().box('loc', [1,2],[3,4]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); + }) + }) + }) + + describe('polygon', function(){ + describe('when first argument is not a string', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().polygon({}); + }, /must be used after where/); + + assert.doesNotThrow(function () { + mquery().where('loc').polygon([1,2], [2,3], [3,6]); + }); + }) + + it('assigns arguments to within polygon condition', function(){ + var m = mquery().where('loc').polygon([1,2], [2,3], [3,6]); + assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); + }) + }) + + describe('when first arg is a string', function(){ + it('assigns remaining arguments to within polygon condition', function(){ + var m = mquery().polygon('loc', [1,2], [2,3], [3,6]); + assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); + }) + }) + }) + + describe('circle', function(){ + describe('with one arg', function(){ + it('must follow where()', function(){ + assert.throws(function () { + mquery().circle('x'); + }, /must be used after where/); + assert.doesNotThrow(function () { + mquery().where('loc').circle({center:[0,0], radius: 3 }); + }); + }) + it('works', function(){ + var m = mquery().where('loc').circle({center:[0,0], radius: 3 }); + assert.deepEqual(m._conditions, { loc: { $geoWithin: {$center: [[0,0],3] }}}); + }) + }) + describe('with 3 args', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().where('loc').circle(1,2,3); + }, /Invalid argument/); + }) + }) + describe('requires radius and center', function(){ + assert.throws(function () { + mquery().circle('loc', { center: 1 }); + }, /center and radius are required/); + assert.throws(function () { + mquery().circle('loc', { radius: 1 }); + }, /center and radius are required/); + assert.doesNotThrow(function () { + mquery().circle('loc', { center: [1,2], radius: 1 }); + }); + }) + }) + + describe('geometry', function(){ + // within + intersects + var point = { type: 'Point', coordinates: [[0,0],[1,1]] }; + + it('must be called after within or intersects', function(done){ + assert.throws(function () { + mquery().where('a').geometry(point); + }, /must come after/); + + assert.doesNotThrow(function () { + mquery().where('a').within().geometry(point); + }); + + assert.doesNotThrow(function () { + mquery().where('a').intersects().geometry(point); + }); + + done(); + }) + + describe('when called with one argument', function(){ + describe('after within()', function(){ + it('and arg quacks like geoJSON', function(done){ + var m = mquery().where('a').within().geometry(point); + assert.deepEqual({ a: { $geoWithin: { $geometry: point }}}, m._conditions); + done(); + }) + }) + + describe('after intersects()', function(){ + it('and arg quacks like geoJSON', function(done){ + var m = mquery().where('a').intersects().geometry(point); + assert.deepEqual({ a: { $geoIntersects: { $geometry: point }}}, m._conditions); + done(); + }) + }) + + it('and arg does not quack like geoJSON', function(done){ + assert.throws(function () { + mquery().where('b').within().geometry({type:1, coordinates:2}); + }, /Invalid argument/); + done(); + }) + }) + + describe('when called with zero arguments', function(){ + it('throws', function(done){ + assert.throws(function () { + mquery().where('a').within().geometry(); + }, /Invalid argument/); + + done(); + }) + }) + + describe('when called with more than one arguments', function(){ + it('throws', function(done){ + assert.throws(function () { + mquery().where('a').within().geometry({type:'a',coordinates:[]}, 2); + }, /Invalid argument/); + done(); + }) + }) + }) + + describe('intersects', function(){ + it('must be used after where()', function(done){ + var m = mquery(); + assert.throws(function () { + m.intersects(); + }, /must be used after where/) + done(); + }) + + it('sets geo comparison to "$intersects"', function(done){ + var n = mquery().where('a').intersects(); + assert.equal('$geoIntersects', n._geoComparison); + done(); + }) + + it('is chainable', function(){ + var m = mquery(); + assert.equal(m.where('a').intersects(), m); + }) + + it('calls geometry if argument quacks like geojson', function(done){ + var m = mquery(); + var o = { type: 'LineString', coordinates: [[0,1],[3,40]] }; + var ran = false; + + m.geometry = function (arg) { + ran = true; + assert.deepEqual(o, arg); + } + + m.where('a').intersects(o); + assert.ok(ran); + + done(); + }) + + it('throws if argument is not geometry-like', function(done){ + var m = mquery().where('a'); + + assert.throws(function () { + m.intersects(null); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(undefined); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(false); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects({}); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects([]); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(function(){}); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(NaN); + }, /Invalid argument/); + + done(); + }) + }) + + describe('near', function(){ + // near nearSphere + describe('with 0 args', function(){ + it('is compatible with geometry()', function(done){ + var q = mquery().where('x').near().geometry({ type: 'Point', coordinates: [180, 11] }); + assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [180,11]}}}, q._conditions.x); + done(); + }) + }) + + describe('with 1 arg', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().near(1); + }, /must be used after where/) + }) + it('does not throw if used after where()', function(){ + assert.doesNotThrow(function () { + mquery().where('loc').near({center:[1,1]}); + }) + }) + }) + describe('with > 2 args', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().near(1,2,3); + }, /Invalid argument/) + }) + }) + + it('creates $geometry args for GeoJSON', function(){ + var m = mquery().where('loc').near({ center: { type: 'Point', coordinates: [10,10] }}); + assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [10,10]}}}, m._conditions.loc); + }) + + it('expects `center`', function(){ + assert.throws(function () { + mquery().near('loc', { maxDistance: 3 }); + }, /center is required/) + assert.doesNotThrow(function () { + mquery().near('loc', { center: [3,4] }); + }) + }) + + it('accepts spherical conditions', function(){ + var m = mquery().where('loc').near({ center: [1,2], spherical: true }); + assert.deepEqual(m._conditions, { loc: { $nearSphere: [1,2]}}); + }) + + it('is non-spherical by default', function(){ + var m = mquery().where('loc').near({ center: [1,2] }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2]}}); + }) + + it('supports maxDistance', function(){ + var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}}); + }) + + it('is chainable', function(){ + var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }).find({ x: 1 }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}, x: 1}); + }) + + describe('supports passing GeoJSON, gh-13', function(){ + it('with center', function(){ + var m = mquery().where('loc').near({ + center: { type: 'Point', coordinates: [1,1] } + , maxDistance: 2 + }); + + var expect = { + loc: { + $near: { + $geometry: { + type: 'Point' + , coordinates : [1,1] + } + , $maxDistance : 2 + } + } + } + + assert.deepEqual(m._conditions, expect); + }) + }) + }) + + // fields + + describe('select', function(){ + describe('with 0 args', function(){ + it('is chainable', function(){ + var m = mquery() + assert.equal(m, m.select()); + }) + }) + + it('accepts an object', function(){ + var o = { x: 1, y: 1 } + var m = mquery().select(o); + assert.deepEqual(m._fields, o); + }) + + it('accepts a string', function(){ + var o = 'x -y'; + var m = mquery().select(o); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + }) + + it('does not accept an array', function(done){ + assert.throws(function () { + var o = ['x', '-y']; + var m = mquery().select(o); + }, /Invalid select/); + done(); + }) + + it('merges previous arguments', function(){ + var o = { x: 1, y: 0, a: 1 } + var m = mquery().select(o); + m.select('z -u w').select({ x: 0 }) + assert.deepEqual(m._fields, { + x: 0 + , y: 0 + , z: 1 + , u: 0 + , w: 1 + , a: 1 + }); + }) + + it('rejects non-string, object, arrays', function(){ + assert.throws(function () { + mquery().select(function(){}); + }, /Invalid select\(\) argument/); + }) + + it('accepts aguments objects', function(){ + var m = mquery(); + function t () { + m.select(arguments); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + } + t('x', '-y'); + }) + + noDistinct('select'); + no('count', 'select'); + }) + + describe('selected', function() { + it('returns true when fields have been selected', function(done) { + var m = mquery().select({ name: 1 }); + assert.ok(m.selected()); + + var m = mquery().select('name'); + assert.ok(m.selected()); + + done(); + }); + + it('returns false when no fields have been selected', function(done) { + var m = mquery(); + assert.strictEqual(false, m.selected()); + done(); + }); + }); + + describe('selectedInclusively', function() { + describe('returns false', function(){ + it('when no fields have been selected', function(done) { + assert.strictEqual(false, mquery().selectedInclusively()); + assert.equal(false, mquery().select({}).selectedInclusively()); + done(); + }); + it('when any fields have been excluded', function(done) { + assert.strictEqual(false, mquery().select('-name').selectedInclusively()); + assert.strictEqual(false, mquery().select({ name: 0 }).selectedInclusively()); + assert.strictEqual(false, mquery().select('name bio -_id').selectedInclusively()); + assert.strictEqual(false, mquery().select({ name: 1, _id: 0 }).selectedInclusively()); + done(); + }); + it('when using $meta', function(done) { + assert.strictEqual(false, mquery().select({ name: { $meta: 'textScore' } }).selectedInclusively()); + done(); + }); + }); + + describe('returns true', function() { + it('when fields have been included', function(done) { + assert.equal(true, mquery().select('name').selectedInclusively()); + assert.equal(true, mquery().select({ name:1 }).selectedInclusively()); + done(); + }); + }); + }); + + describe('selectedExclusively', function() { + describe('returns false', function(){ + it('when no fields have been selected', function(done) { + assert.equal(false, mquery().selectedExclusively()); + assert.equal(false, mquery().select({}).selectedExclusively()); + done(); + }); + it('when fields have only been included', function(done) { + assert.equal(false, mquery().select('name').selectedExclusively()); + assert.equal(false, mquery().select({ name: 1 }).selectedExclusively()); + done(); + }); + }); + + describe('returns true', function() { + it('when any field has been excluded', function(done) { + assert.equal(true, mquery().select('-name').selectedExclusively()); + assert.equal(true, mquery().select({ name:0 }).selectedExclusively()); + assert.equal(true, mquery().select('-_id').selectedExclusively()); + assert.strictEqual(true, mquery().select('name bio -_id').selectedExclusively()); + assert.strictEqual(true, mquery().select({ name: 1, _id: 0 }).selectedExclusively()); + done(); + }); + }); + }); + + describe('slice', function(){ + describe('with 0 args', function(){ + it('is chainable', function(){ + var m = mquery() + assert.equal(m, m.slice()); + }) + it('is a noop', function(){ + var m = mquery().slice(); + assert.deepEqual(m._fields, undefined); + }) + }) + + describe('with 1 arg', function(){ + it('throws if not called after where()', function(){ + assert.throws(function () { + mquery().slice(1); + }, /must be used after where/); + assert.doesNotThrow(function () { + mquery().where('a').slice(1); + }); + }) + it('that is a number', function(){ + var query = mquery(); + query.where('collection').slice(5); + assert.deepEqual(query._fields, {collection: {$slice: 5}}); + }) + it('that is an array', function(){ + var query = mquery(); + query.where('collection').slice([5,10]); + assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); + }) + it('that is an object', function() { + var query = mquery(); + query.slice({ collection: [5, 10] }); + assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); + }) + }) + + describe('with 2 args', function(){ + describe('and first is a number', function(){ + it('throws if not called after where', function(){ + assert.throws(function () { + mquery().slice(2,3); + }, /must be used after where/); + }) + it('does not throw if used after where', function(){ + var query = mquery(); + query.where('collection').slice(2,3); + assert.deepEqual(query._fields, {collection: {$slice: [2,3]}}); + }) + }) + it('and first is not a number', function(){ + var query = mquery().slice('collection', [-5, 2]); + assert.deepEqual(query._fields, {collection: {$slice: [-5,2]}}); + }) + }) + + describe('with 3 args', function(){ + it('works', function(){ + var query = mquery(); + query.slice('collection', 14, 10); + assert.deepEqual(query._fields, {collection: {$slice: [14, 10]}}); + }) + }) + + noDistinct('slice'); + no('count', 'slice'); + }) + + // options + + describe('sort', function(){ + describe('with 0 args', function(){ + it('chains', function(){ + var m = mquery(); + assert.equal(m, m.sort()); + }) + it('has no affect', function(){ + var m = mquery(); + assert.equal(m.options.sort, undefined); + }) + }) + + it('works', function(){ + var query = mquery(); + query.sort('a -c b'); + assert.deepEqual(query.options.sort, { a : 1, b: 1, c : -1}); + + query = mquery(); + query.sort({'a': 1, 'c': -1, 'b': 'asc', e: 'descending', f: 'ascending'}); + assert.deepEqual(query.options.sort, {'a': 1, 'c': -1, 'b': 1, 'e': -1, 'f': 1}); + + query = mquery(); + var e= undefined; + try { + query.sort(['a', 1]); + } catch (err) { + e= err; + } + assert.ok(e, 'uh oh. no error was thrown'); + assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); + + e= undefined; + try { + query.sort('a', 1, 'c', -1, 'b', 1); + } catch (err) { + e= err; + } + assert.ok(e, 'uh oh. no error was thrown'); + assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); + }) + + it('handles $meta sort options', function(){ + var query = mquery(); + query.sort({ score: { $meta : "textScore" } }); + assert.deepEqual(query.options.sort, { score : { $meta : "textScore" } }); + }) + + no('count', 'sort'); + }) + + function simpleOption (type, options) { + describe(type, function(){ + it('sets the ' + type + ' option', function(){ + var m = mquery()[type](2); + var optionName = options.name || type; + assert.equal(2, m.options[optionName]); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m[type](3), m); + }) + + if (!options.distinct) noDistinct(type); + if (!options.count) no('count', type); + }) + } + + var negated = { + limit: {distinct: false, count: true} + , skip: {distinct: false, count: true} + , maxScan: {distinct: false, count: false} + , batchSize: {distinct: false, count: false} + , maxTime: {distinct: true, count: true, name: 'maxTimeMS' } + , comment: {distinct: false, count: false} + }; + Object.keys(negated).forEach(function (key) { + simpleOption(key, negated[key]); + }) + + describe('snapshot', function(){ + it('works', function(){ + var query = mquery(); + query.snapshot(); + assert.equal(true, query.options.snapshot); + + var query = mquery() + query.snapshot(true); + assert.equal(true, query.options.snapshot); + + var query = mquery() + query.snapshot(false); + assert.equal(false, query.options.snapshot); + }) + noDistinct('snapshot'); + no('count', 'snapshot'); + }) + + describe('hint', function(){ + it('accepts an object', function(){ + var query2 = mquery(); + query2.hint({'a': 1, 'b': -1}); + assert.deepEqual(query2.options.hint, {'a': 1, 'b': -1}); + }) + + it('rejects everything else', function(){ + assert.throws(function(){ + mquery().hint('c'); + }, /Invalid hint./); + assert.throws(function(){ + mquery().hint(['c']); + }, /Invalid hint./); + assert.throws(function(){ + mquery().hint(1); + }, /Invalid hint./); + }) + + describe('does not have side affects', function(){ + it('on invalid arg', function(){ + var m = mquery(); + try { + m.hint(1); + } catch (err) { + // ignore + } + assert.equal(undefined, m.options.hint); + }) + it('on missing arg', function(){ + var m = mquery().hint(); + assert.equal(undefined, m.options.hint); + }) + }) + + noDistinct('hint'); + }) + + describe('slaveOk', function(){ + it('works', function(){ + var query = mquery(); + query.slaveOk(); + assert.equal(true, query.options.slaveOk); + + var query = mquery() + query.slaveOk(true); + assert.equal(true, query.options.slaveOk); + + var query = mquery() + query.slaveOk(false); + assert.equal(false, query.options.slaveOk); + }) + }) + + describe('read', function(){ + it('sets associated readPreference option', function(){ + var m = mquery(); + m.read('p'); + assert.equal('primary', m.options.readPreference); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m, m.read('sp')); + }) + }) + + describe('tailable', function(){ + it('works', function(){ + var query = mquery(); + query.tailable(); + assert.equal(true, query.options.tailable); + + var query = mquery() + query.tailable(true); + assert.equal(true, query.options.tailable); + + var query = mquery() + query.tailable(false); + assert.equal(false, query.options.tailable); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m, m.tailable()); + }) + noDistinct('tailable'); + no('count', 'tailable'); + }) + + // query utilities + + describe('merge', function(){ + describe('with falsy arg', function(){ + it('returns itself', function(){ + var m = mquery(); + assert.equal(m, m.merge()); + assert.equal(m, m.merge(null)); + assert.equal(m, m.merge(0)); + }) + }) + describe('with an argument', function(){ + describe('that is not a query or plain object', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().merge([]); + }, /Invalid argument/); + assert.throws(function () { + mquery().merge('merge'); + }, /Invalid argument/); + assert.doesNotThrow(function () { + mquery().merge({}); + }, /Invalid argument/); + }) + }) + + describe('that is a query', function(){ + it('merges conditions, field selection, and options', function(){ + var m = mquery({ x: 'hi' }, { select: 'x y', another: true }) + var n = mquery().merge(m); + assert.deepEqual(n._conditions, m._conditions); + assert.deepEqual(n._fields, m._fields); + assert.deepEqual(n.options, m.options); + }) + it('clones update arguments', function(done){ + var original = { $set: { iTerm: true }} + var m = mquery().update(original); + var n = mquery().merge(m); + m.update({ $set: { x: 2 }}) + assert.notDeepEqual(m._update, n._update); + done(); + }) + it('is chainable', function(){ + var m = mquery({ x: 'hi' }); + var n = mquery(); + assert.equal(n, n.merge(m)); + }) + }) + + describe('that is an object', function(){ + it('merges', function(){ + var m = { x: 'hi' }; + var n = mquery().merge(m); + assert.deepEqual(n._conditions, { x: 'hi' }); + }) + it('clones update arguments', function(done){ + var original = { $set: { iTerm: true }} + var m = mquery().update(original); + var n = mquery().merge(original); + m.update({ $set: { x: 2 }}) + assert.notDeepEqual(m._update, n._update); + done(); + }) + it('is chainable', function(){ + var m = { x: 'hi' }; + var n = mquery(); + assert.equal(n, n.merge(m)); + }) + }) + }) + }) + + // queries + + describe('find', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.find() + }) + assert.doesNotThrow(function () { + m.find({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery().find({ x: 1 }).find().find({ y: 2 }); + assert.deepEqual(m._conditions, {x:1,y:2}); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.tailable(); + m.select('_id'); + var a = mquery().find(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).find({ name: 'mquery' }, function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery({ name: 'mquery' }); + mquery(col).find(m, function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery' }).collection(col).find(function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }); + }) + }) + }) + + describe('findOne', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.findOne() + }) + assert.doesNotThrow(function () { + m.findOne({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery(); + var n = m.findOne({ x: 1 }).findOne().findOne({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(m._conditions, {x:1,y:2}); + assert.equal('findOne', m.op); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.read('nearest'); + m.select('_id'); + var a = mquery().findOne(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery findone' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery findone' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).findOne({ name: 'mquery findone' }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery(col).where({ name: 'mquery findone' }); + mquery(col).findOne(m, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery findone' }).collection(col).findOne(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }); + }) + }) + }) + + describe('count', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.count() + }) + assert.doesNotThrow(function () { + m.count({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery(); + var n = m.count({ x: 1 }).count().count({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(m._conditions, {x:1,y:2}); + assert.equal('count', m.op); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.read('nearest'); + m.select('_id'); + var a = mquery().count(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery count' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery count' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).count({ name: 'mquery count' }, function (err, count) { + assert.ifError(err); + assert.ok(count); + assert.ok(1 === count); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery({ name: 'mquery count' }); + mquery(col).count(m, function (err, count) { + assert.ifError(err); + assert.ok(count); + assert.ok(1 === count); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery count' }).collection(col).count(function (err, count) { + assert.ifError(err); + assert.ok(1 === count); + done(); + }); + }) + }) + + describe('validates its option', function(){ + it('sort', function(done){ + assert.throws(function(){ + var m = mquery().sort('x').count(); + }, /sort cannot be used with count/); + done(); + }) + + it('select', function(done){ + assert.throws(function(){ + var m = mquery().select('x').count(); + }, /field selection and slice cannot be used with count/); + done(); + }) + + it('slice', function(done){ + assert.throws(function(){ + var m = mquery().where('x').slice(-3).count(); + }, /field selection and slice cannot be used with count/); + done(); + }) + + it('limit', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().limit(3).count(); + }) + done(); + }) + + it('skip', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().skip(3).count(); + }) + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 }).count(); + }, /batchSize cannot be used with count/); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery').count(); + }, /comment cannot be used with count/); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300).count(); + }, /maxScan cannot be used with count/); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot().count(); + }, /snapshot cannot be used with count/); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable().count(); + }, /tailable cannot be used with count/); + done(); + }) + }) + }) + + describe('distinct', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.distinct() + }) + assert.doesNotThrow(function () { + m.distinct('name') + }) + assert.doesNotThrow(function () { + m.distinct({ name: 'mquery distinct' }) + }) + assert.doesNotThrow(function () { + m.distinct({ name: 'mquery distinct' }, 'name') + }) + }) + }) + + it('is chainable', function(){ + var m = mquery({x:1}).distinct('name'); + var n = m.distinct({y:2}); + assert.equal(m, n); + assert.deepEqual(n._conditions, {x:1, y:2}); + assert.equal('name', n._distinct); + assert.equal('distinct', n.op); + }); + + it('overwrites field', function(){ + var m = mquery({ name: 'mquery' }).distinct('name'); + m.distinct('rename'); + assert.equal(m._distinct, 'rename'); + m.distinct({x:1}, 'renamed'); + assert.equal(m._distinct, 'renamed'); + }) + + it('merges other queries', function(){ + var m = mquery().distinct({ name: 'mquery' }, 'age') + m.read('nearest'); + var a = mquery().distinct(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + assert.deepEqual(a._distinct, m._distinct); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery distinct', age: 1 }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery distinct' }, done); + }) + + it('when distinct arg is passed with a callback', function(done){ + mquery(col).distinct('distinct', function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + describe('when criteria is passed with a callback', function(){ + it('if distinct arg was declared', function(done){ + mquery(col).distinct('age').distinct({ name: 'mquery distinct' }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + it('but not if distinct arg was not declared', function(){ + assert.throws(function(){ + mquery(col).distinct({ name: 'mquery distinct' }, function(){}) + }, /No value for `distinct`/) + }) + }) + describe('when Query is passed with a callback', function(){ + var m = mquery({ name: 'mquery distinct' }); + it('if distinct arg was declared', function(done){ + mquery(col).distinct('age').distinct(m, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + it('but not if distinct arg was not declared', function(){ + assert.throws(function(){ + mquery(col).distinct(m, function(){}) + }, /No value for `distinct`/) + }) + }) + describe('when just a callback is passed', function(done){ + it('if distinct arg was declared', function(done){ + var m = mquery({ name: 'mquery distinct' }); + m.collection(col); + m.distinct('age'); + m.distinct(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }); + }) + it('but not if no distinct arg was declared', function(){ + var m = mquery(); + m.collection(col); + assert.throws(function () { + m.distinct(function(){}); + }, /No value for `distinct`/); + }) + }) + }) + + describe('validates its option', function(){ + it('sort', function(done){ + assert.throws(function(){ + var m = mquery().sort('x').distinct(); + }, /sort cannot be used with distinct/); + done(); + }) + + it('select', function(done){ + assert.throws(function(){ + var m = mquery().select('x').distinct(); + }, /field selection and slice cannot be used with distinct/); + done(); + }) + + it('slice', function(done){ + assert.throws(function(){ + var m = mquery().where('x').slice(-3).distinct(); + }, /field selection and slice cannot be used with distinct/); + done(); + }) + + it('limit', function(done){ + assert.throws(function(){ + var m = mquery().limit(3).distinct(); + }, /limit cannot be used with distinct/); + done(); + }) + + it('skip', function(done){ + assert.throws(function(){ + var m = mquery().skip(3).distinct(); + }, /skip cannot be used with distinct/); + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 }).distinct(); + }, /batchSize cannot be used with distinct/); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery').distinct(); + }, /comment cannot be used with distinct/); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300).distinct(); + }, /maxScan cannot be used with distinct/); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot().distinct(); + }, /snapshot cannot be used with distinct/); + done(); + }) + + it('hint', function(done){ + assert.throws(function(){ + var m = mquery().hint({ x: 1 }).distinct(); + }, /hint cannot be used with distinct/); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable().distinct(); + }, /tailable cannot be used with distinct/); + done(); + }) + }) + }) + + describe('update', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.update({ name: 'old' }, { name: 'updated' }, { multi: true }) + }) + assert.doesNotThrow(function () { + m.update({ name: 'old' }, { name: 'updated' }) + }) + assert.doesNotThrow(function () { + m.update({ name: 'updated' }) + }) + assert.doesNotThrow(function () { + m.update() + }) + }) + }) + + it('is chainable', function(){ + var m = mquery({x:1}).update({ y: 2 }); + var n = m.where({y:2}); + assert.equal(m, n); + assert.deepEqual(n._conditions, {x:1, y:2}); + assert.deepEqual({ y: 2 }, n._update); + assert.equal('update', n.op); + }); + + it('merges update doc arg', function(){ + var a = [1,2]; + var m = mquery().where({ name: 'mquery' }).update({ x: 'stuff', a: a }); + m.update({ z: 'stuff' }); + assert.deepEqual(m._update, { z: 'stuff', x: 'stuff', a: a }); + assert.deepEqual(m._conditions, { name: 'mquery' }); + assert.ok(!m.options.overwrite); + m.update({}, { z: 'renamed' }, { overwrite: true }); + assert.ok(m.options.overwrite === true); + assert.deepEqual(m._conditions, { name: 'mquery' }); + assert.deepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); + a.push(3); + assert.notDeepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); + }) + + it('merges other options', function(){ + var m = mquery(); + m.setOptions({ overwrite: true }); + m.update({ age: 77 }, { name: 'pagemill' }, { multi: true }) + assert.deepEqual({ age: 77 }, m._conditions); + assert.deepEqual({ name: 'pagemill' }, m._update); + assert.deepEqual({ overwrite: true, multi: true }, m.options); + }) + + describe('executes', function(){ + var id; + before(function (done) { + col.insert({ name: 'mquery update', age: 1 }, { safe: true }, function (err, docs) { + var elem = docs[0]; + id = elem._id; + done(); + }); + }); + + after(function(done){ + col.remove({ _id: id }, done); + }) + + describe('when conds + doc + opts + callback passed', function(){ + it('works', function(done){ + var m = mquery(col).where({ _id: id }) + m.update({}, { name: 'Sparky' }, { safe: true }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'Sparky'); + done(); + }) + }) + }) + }) + + describe('when conds + doc + callback passed', function(){ + it('works', function (done) { + var m = mquery(col).update({ _id: id }, { name: 'fairgrounds' }, function (err, num, doc) { + assert.ifError(err); + assert.ok(1, num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'fairgrounds'); + done(); + }) + }) + }) + }) + + describe('when doc + callback passed', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }).update({ name: 'changed' }, function (err, num, doc) { + assert.ifError(err); + assert.ok(1, num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'changed'); + done(); + }) + }) + }) + }) + + describe('when just callback passed', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true }); + m.update({ name: 'Frankenweenie' }); + m.update(function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'Frankenweenie'); + done(); + }) + }) + }) + }) + + describe('without a callback', function(){ + it('when forced by exec()', function(done){ + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, multi: true }); + m.update({ name: 'forced' }); + + var update = m._collection.update; + m._collection.update = function (conds, doc, opts, cb) { + m._collection.update = update; + + assert.ok(!opts.safe); + assert.ok(true === opts.multi); + assert.equal('forced', doc.$set.name); + done(); + } + + m.exec() + }) + }) + + describe('except when update doc is empty and missing overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true }); + m.update({ }, function (err, num) { + assert.ifError(err); + assert.ok(0 === num); + setTimeout(function(){ + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(3, mquery.utils.keys(doc).length); + assert.equal(id, doc._id.toString()); + assert.equal('Frankenweenie', doc.name); + done(); + }) + }, 300); + }) + }) + }); + + describe('when update doc is set with overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, overwrite: true }); + m.update({ all: 'yep', two: 2 }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(3, mquery.utils.keys(doc).length); + assert.equal('yep', doc.all); + assert.equal(2, doc.two); + assert.equal(id, doc._id.toString()); + done(); + }) + }) + }) + }) + + describe('when update doc is empty with overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, overwrite: true }); + m.update({ }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(1, mquery.utils.keys(doc).length); + assert.equal(id, doc._id.toString()); + done(); + }) + }) + }) + }) + + describe('when boolean (true) - exec()', function(){ + it('works', function(done){ + var m = mquery(col).where({ _id: id }); + m.update({ name: 'bool' }).update(true); + setTimeout(function () { + m.findOne(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('bool', doc.name); + done(); + }) + }, 300) + }) + }) + }) + }) + + describe('remove', function(){ + describe('with 0 args', function(){ + var name = 'remove: no args test' + before(function(done){ + col.insert({ name: name }, { safe: true }, done) + }) + after(function(done){ + col.remove({ name: name }, { safe: true }, done) + }) + + it('does not execute', function(done){ + var remove = col.remove; + col.remove = function () { + col.remove = remove; + done(new Error('remove executed!')); + } + + var m = mquery(col).where({ name: name }).remove() + setTimeout(function () { + col.remove = remove; + done(); + }, 10); + }) + + it('chains', function(){ + var m = mquery(); + assert.equal(m, m.remove()); + }) + }) + + describe('with 1 argument', function(){ + var name = 'remove: 1 arg test' + before(function(done){ + col.insert({ name: name }, { safe: true }, done) + }) + after(function(done){ + col.remove({ name: name }, { safe: true }, done) + }) + + describe('that is a', function(){ + it('plain object', function(){ + var m = mquery(col).remove({ name: 'Whiskers' }); + m.remove({ color: '#fff' }) + assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); + }) + + it('query', function(){ + var q = mquery({ color: '#fff' }); + var m = mquery(col).remove({ name: 'Whiskers' }); + m.remove(q) + assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); + }) + + it('function', function(done){ + mquery(col, { safe: true }).where({name: name}).remove(function (err) { + assert.ifError(err); + mquery(col).findOne({ name: name }, function (err, doc) { + assert.ifError(err); + assert.equal(null, doc); + done(); + }) + }); + }) + + it('boolean (true) - execute', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + mquery(col).findOne({ name: name }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + mquery(col).remove(true); + setTimeout(function () { + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(0, docs.length); + done(); + }) + }, 300) + }) + }) + }) + }) + }) + + describe('with 2 arguments', function(){ + var name = 'remove: 2 arg test' + beforeEach(function(done){ + col.remove({}, { safe: true }, function (err) { + assert.ifError(err); + col.insert([{ name: 'shelly' }, { name: name }], { safe: true }, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + }) + }) + + describe('plain object + callback', function(){ + it('works', function(done){ + mquery(col).remove({ name: name }, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(1, docs.length); + assert.equal('shelly', docs[0].name); + done(); + }) + }); + }) + }) + + describe('mquery + callback', function(){ + it('works', function(done){ + var m = mquery({ name: name }); + mquery(col).remove(m, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(1, docs.length); + assert.equal('shelly', docs[0].name); + done(); + }) + }); + }) + }) + }) + }) + + function validateFindAndModifyOptions (method) { + describe('validates its option', function(){ + it('sort', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().sort('x')[method](); + }) + done(); + }) + + it('select', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().select('x')[method](); + }) + done(); + }) + + it('limit', function(done){ + assert.throws(function(){ + var m = mquery().limit(3)[method](); + }, new RegExp('limit cannot be used with ' + method)); + done(); + }) + + it('skip', function(done){ + assert.throws(function(){ + var m = mquery().skip(3)[method](); + }, new RegExp('skip cannot be used with ' + method)); + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 })[method](); + }, new RegExp('batchSize cannot be used with ' + method)); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300)[method](); + }, new RegExp('maxScan cannot be used with ' + method)); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot()[method](); + }, new RegExp('snapshot cannot be used with ' + method)); + done(); + }) + + it('hint', function(done){ + assert.throws(function(){ + var m = mquery().hint({ x: 1 })[method](); + }, new RegExp('hint cannot be used with ' + method)); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable()[method](); + }, new RegExp('tailable cannot be used with ' + method)); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery')[method](); + }, new RegExp('comment cannot be used with ' + method)); + done(); + }) + }) + } + + describe('findOneAndUpdate', function(){ + var name = 'findOneAndUpdate + fn' + + validateFindAndModifyOptions('findOneAndUpdate'); + + describe('with 0 args', function(){ + it('makes no changes', function(){ + var m = mquery(); + var n = m.findOneAndUpdate(); + assert.deepEqual(m, n); + }) + }) + describe('with 1 arg', function(){ + describe('that is an object', function(){ + it('updates the doc', function(){ + var m = mquery(); + var n = m.findOneAndUpdate({ $set: { name: '1 arg' }}); + assert.deepEqual(n._update, { $set: { name: '1 arg' }}); + }) + }) + describe('that is a query', function(){ + it('updates the doc', function(){ + var m = mquery({ name: name }).update({ x: 1 }); + var n = mquery().findOneAndUpdate(m); + assert.deepEqual(n._update, { x: 1 }); + }) + }) + it('that is a function', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery({ name: name }).collection(col); + name = '1 arg'; + var n = m.update({ $set: { name: name }}); + n.findOneAndUpdate(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + describe('with 2 args', function(){ + it('conditions + update', function(){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { age: 100 }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ age: 100 }, m._update); + }) + it('query + update', function(){ + var n = mquery({ name: name }); + var m = mquery(col); + m.findOneAndUpdate(n, { age: 100 }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ age: 100 }, m._update); + }) + it('update + callback', function(done){ + var m = mquery(col).where({ name: name }); + m.findOneAndUpdate({ $inc: { age: 10 }}, function (err, doc) { + assert.ifError(err); + assert.equal(10, doc.age); + done(); + }); + }) + }) + describe('with 3 args', function(){ + it('conditions + update + options', function(){ + var m = mquery(); + var n = m.findOneAndUpdate({ name: name }, { works: true }, { new: false }); + assert.deepEqual({ name: name}, n._conditions); + assert.deepEqual({ works: true }, n._update); + assert.deepEqual({ new: false }, n.options); + }) + it('conditions + update + callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { works: true }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + assert.ok(true === doc.works); + done(); + }); + }) + }) + describe('with 4 args', function(){ + it('conditions + update + options + callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { works: false }, { new: false }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + assert.ok(true === doc.works); + done(); + }); + }) + }) + }) + + describe('findOneAndRemove', function(){ + var name = 'findOneAndRemove' + + validateFindAndModifyOptions('findOneAndRemove'); + + describe('with 0 args', function(){ + it('makes no changes', function(){ + var m = mquery(); + var n = m.findOneAndRemove(); + assert.deepEqual(m, n); + }) + }) + describe('with 1 arg', function(){ + describe('that is an object', function(){ + it('updates the doc', function(){ + var m = mquery(); + var n = m.findOneAndRemove({ name: '1 arg' }); + assert.deepEqual(n._conditions, { name: '1 arg' }); + }) + }) + describe('that is a query', function(){ + it('updates the doc', function(){ + var m = mquery({ name: name }); + var n = m.findOneAndRemove(m); + assert.deepEqual(n._conditions, { name: name }); + }) + }) + it('that is a function', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery({ name: name }).collection(col); + m.findOneAndRemove(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + describe('with 2 args', function(){ + it('conditions + options', function(){ + var m = mquery(col); + m.findOneAndRemove({ name: name }, { new: false }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ new: false }, m.options); + }) + it('query + options', function(){ + var n = mquery({ name: name }); + var m = mquery(col); + m.findOneAndRemove(n, { sort: { x: 1 }}); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ sort: { 'x': 1 }}, m.options); + }) + it('conditions + callback', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery(col); + m.findOneAndRemove({ name: name }, function (err, doc) { + assert.ifError(err); + assert.equal(name, doc.name); + done(); + }); + }); + }) + it('query + callback', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var n = mquery({ name: name }) + var m = mquery(col); + m.findOneAndRemove(n, function (err, doc) { + assert.ifError(err); + assert.equal(name, doc.name); + done(); + }); + }); + }) + }) + describe('with 3 args', function(){ + it('conditions + options + callback', function(done){ + name = 'findOneAndRemove + conds + options + cb'; + col.insert([{ name: name }, { name: 'a' }], { safe: true }, function (err) { + assert.ifError(err); + var m = mquery(col); + m.findOneAndRemove({ name: name }, { sort: { name: 1 }}, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + }) + + describe('exec', function(){ + beforeEach(function(done){ + col.insert([{ name: 'exec', age: 1 }, { name: 'exec', age: 2 }], done); + }) + + afterEach(function(done){ + mquery(col).remove(done); + }) + + it('requires an op', function(){ + assert.throws(function () { + mquery().exec() + }, /Missing query type/); + }) + + describe('find', function() { + it('works', function(done){ + var m = mquery(col).find({ name: 'exec' }); + m.exec(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + + it('works with readPreferences', function (done) { + var m = mquery(col).find({ name: 'exec' }); + try { + var rp = new require('mongodb').ReadPreference('primary'); + m.read(rp); + } catch (e) { + if (e.code === 'MODULE_NOT_FOUND') + e = null; + done(e); + return; + } + m.exec(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + }); + + it('findOne', function(done){ + var m = mquery(col).findOne({ age: 2 }); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal(2, doc.age); + done(); + }) + }) + + it('count', function(done){ + var m = mquery(col).count({ name: 'exec' }); + m.exec(function (err, count) { + assert.ifError(err); + assert.equal(2, count); + done(); + }) + }) + + it('distinct', function(done){ + var m = mquery({ name: 'exec' }); + m.collection(col); + m.distinct('age'); + m.exec(function (err, array) { + assert.ifError(err); + assert.ok(Array.isArray(array)); + assert.equal(2, array.length); + assert(~array.indexOf(1)); + assert(~array.indexOf(2)); + done(); + }); + }) + + describe('update', function(){ + var num; + + it('with a callback', function(done){ + var m = mquery(col); + m.where({ name: 'exec' }) + + m.count(function (err, _num) { + assert.ifError(err); + num = _num; + m.setOptions({ multi: true }) + m.update({ name: 'exec + update' }); + m.exec(function (err, res) { + assert.ifError(err); + assert.equal(num, res); + mquery(col).find({ name: 'exec + update' }, function (err, docs) { + assert.ifError(err); + assert.equal(num, docs.length); + done(); + }) + }) + }) + }) + + it('without a callback', function(done){ + var m = mquery(col) + m.where({ name: 'exec + update' }).setOptions({ multi: true }) + m.update({ name: 'exec' }); + + // unsafe write + m.exec(); + + setTimeout(function () { + mquery(col).find({ name: 'exec' }, function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }, 200) + }) + it('preserves key ordering', function(done) { + var m = mquery(col); + + var m2 = m.update({ _id : 'something' }, { '1' : 1, '2' : 2, '3' : 3}); + var doc = m2._updateForExec().$set; + var count = 0; + for (var i in doc) { + if (count == 0) { + assert.equal('1', i); + } else if (count == 1) { + assert.equal('2', i); + } else if (count ==2) { + assert.equal('3', i); + } + count++; + } + done(); + }); + }) + + describe('remove', function(){ + it('with a callback', function(done){ + var m = mquery(col).where({ age: 2 }).remove(); + m.exec(function (err, num) { + assert.ifError(err); + assert.equal(1, num); + done(); + }) + }) + + it('without a callback', function(done){ + var m = mquery(col).where({ age: 1 }).remove(); + m.exec(); + + setTimeout(function () { + mquery(col).where('name', 'exec').count(function(err, num) { + assert.equal(1, num); + done(); + }) + }, 200) + }) + }) + + describe('findOneAndUpdate', function(){ + it('with a callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: 'exec', age: 1 }, { $set: { name: 'findOneAndUpdate' }}); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal('findOneAndUpdate', doc.name); + done(); + }); + }) + }) + + describe('findOneAndRemove', function(){ + it('with a callback', function(done){ + var m = mquery(col); + m.findOneAndRemove({ name: 'exec', age: 2 }); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal('exec', doc.name); + assert.equal(2, doc.age); + mquery(col).count({ name: 'exec' }, function (err, num) { + assert.ifError(err); + assert.equal(1, num); + done(); + }); + }); + }) + }) + }) + + describe('setTraceFunction', function() { + beforeEach(function(done){ + col.insert([{ name: 'trace', age: 93 }], done); + }) + + it('calls trace function when executing query', function(done) { + var m = mquery(col); + + var resultTraceCalled; + + m.setTraceFunction(function (method, queryInfo) { + try { + assert.equal('findOne', method); + assert.equal('trace', queryInfo.conditions.name); + } catch (e) { + done(e); + } + + return function(err, result, millis) { + try { + assert.equal(93, result.age); + } catch (e) { + done(e); + } + resultTraceCalled = true; + }; + }); + + m.findOne({name: 'trace'}, function (err, doc) { + assert.ifError(err); + assert.equal(resultTraceCalled, true); + assert.equal(93, doc.age); + done(); + }); + }); + + it('inherits trace function when calling toConstructor', function(done) { + function traceFunction () { return function() {} }; + + var tracedQuery = mquery().setTraceFunction(traceFunction).toConstructor(); + + var query = tracedQuery(); + assert.equal(traceFunction, query._traceFunction); + + done(); + }); + }); + + describe('thunk', function() { + it('returns a function', function(done) { + assert.equal('function', typeof mquery().thunk()); + done(); + }); + + it('passes the fn arg to `exec`', function(done) { + function cb() {} + var m = mquery(); + + m.exec = function testing(fn) { + assert.equal(this, m); + assert.equal(cb, fn); + done(); + } + + m.thunk()(cb); + }); + }); + + describe('then', function() { + before(function(done){ + col.insert([{ name: 'then', age: 1 }, { name: 'then', age: 2 }], done); + }) + + after(function(done){ + mquery(col).remove({ name: 'then' }).exec(done); + }) + + it('returns a promise A+ compat object', function(done) { + var m = mquery(col).find(); + assert.equal('function', typeof m.then); + done(); + }); + + it('creates a promise that is resolved on success', function(done) { + var promise = mquery(col).count({ name: 'then' }).then(); + promise.then(function(count){ + assert.equal(2, count); + done(); + }, done); + }); + + it('supports exec() cb being called synchronously #66', function(done) { + var query = mquery(col).count({ name: 'then' }); + query.exec = function(cb) { + cb(null, 66); + } + + query.then(success, done); + function success(count){ + assert.equal(66, count); + done(); + } + }); + + it('supports other Promise libs', function(done) { + var bluebird = mquery.Promise; + + // hack for testing + mquery.Promise = function P() { + mquery.Promise = bluebird; + this.then = function(x, y) { + return x + y; + } + } + + var val = mquery(col).count({ name: 'exec' }).then(1, 2); + assert.equal(val, 3); + done(); + }); + }); + + describe('stream', function() { + before(function(done){ + col.insert([{ name: 'stream', age: 1 }, { name: 'stream', age: 2 }], done); + }) + + after(function(done){ + mquery(col).remove({ name: 'stream' }).exec(done); + }) + + describe('throws', function() { + describe('if used with non-find operations', function() { + var ops = ['update', 'findOneAndUpdate', 'remove', 'count', 'distinct']; + + ops.forEach(function(op) { + assert.throws(function(){ + mquery(col)[op]().stream(); + }); + }); + }); + }); + + it('returns a stream', function(done) { + var stream = mquery(col).find({ name: 'stream' }).stream(); + var count = 0; + var err; + + stream.on('data', function(doc){ + assert.equal('stream', doc.name); + ++count; + }); + + stream.on('error', function(er) { + err = er; + }); + + stream.on('close', function(){ + if (err) return done(err); + assert.equal(2, count); + done(); + }); + }); + + it('supports find options', function(done) { + var stream = mquery(col) + .find({ name: 'stream' }) + .limit(1) + .select('-_id') + .stream({ transform: xform }); + + function xform(doc) { + doc.name = doc.name + '-xformed'; + return doc; + } + + var count = 0; + var err; + + stream.on('data', function(doc){ + assert(!doc._id); + assert.equal('stream-xformed', doc.name); + ++count; + }); + + stream.on('error', function(er) { + err = er; + }); + + stream.on('close', function(){ + if (err) return done(err); + assert.equal(1, count); + done(); + }); + }); + + }); + + function noDistinct (type) { + it('cannot be used with distinct()', function(done){ + assert.throws(function () { + mquery().distinct('name')[type](4); + }, new RegExp(type + ' cannot be used with distinct')); + done(); + }) + } + + function no (method, type) { + it('cannot be used with ' + method + '()', function(done){ + assert.throws(function () { + mquery()[method]()[type](4); + }, new RegExp(type + ' cannot be used with ' + method)); + done(); + }) + } + + // query internal + + describe('_updateForExec', function(){ + it('returns a clone of the update object with same key order #19', function(done){ + var update = {}; + update.$push = { n: { $each: [{x:10}], $slice: -1, $sort: {x:1}}}; + + var q = mquery().update({ x: 1 }, update); + + // capture original key order + var order = []; + for (var key in q._update.$push.n) { + order.push(key); + } + + // compare output + var doc = q._updateForExec(); + var i = 0; + for (var key in doc.$push.n) { + assert.equal(key, order[i]); + i++; + } + + done(); + }) + }) +}) diff --git a/5-2/service/node_modules/mongoose/node_modules/mquery/test/utils.test.js b/5-2/service/node_modules/mongoose/node_modules/mquery/test/utils.test.js new file mode 100644 index 0000000..fa5972a --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/mquery/test/utils.test.js @@ -0,0 +1,143 @@ + +var utils = require('../lib/utils'); +var assert = require('assert'); + +var mongo; +try { + mongo = new require('mongodb'); +} catch (e) {} + +describe('lib/utils', function() { + describe('clone', function() { + it('clones constructors named ObjectId', function(done) { + function ObjectId (id) { + this.id = id; + } + + var o1 = new ObjectId('1234'); + var o2 = utils.clone(o1); + assert.ok(o2 instanceof ObjectId); + + done(); + }); + + it('clones constructors named ObjectID', function(done) { + function ObjectID (id) { + this.id = id; + } + + var o1 = new ObjectID('1234'); + var o2 = utils.clone(o1); + + assert.ok(o2 instanceof ObjectID); + done(); + }); + + it('does not clone constructors named ObjectIdd', function(done) { + function ObjectIdd (id) { + this.id = id; + } + + var o1 = new ObjectIdd('1234'); + var o2 = utils.clone(o1); + assert.ok(!(o2 instanceof ObjectIdd)); + + done(); + }); + + it('optionally clones ObjectId constructors using its clone method', function(done) { + function ObjectID (id) { + this.id = id; + this.cloned = false; + } + + ObjectID.prototype.clone = function () { + var ret = new ObjectID(this.id); + ret.cloned = true; + return ret; + } + + var id = 1234; + var o1 = new ObjectID(id); + assert.equal(id, o1.id); + assert.equal(false, o1.cloned); + + var o2 = utils.clone(o1); + assert.ok(o2 instanceof ObjectID); + assert.equal(id, o2.id); + assert.ok(o2.cloned); + done(); + }); + + it('clones mongodb.ReadPreferences', function (done) { + if (!mongo) return done(); + + var tags = [ + {dc: 'tag1'} + ]; + var prefs = [ + new mongo.ReadPreference("primary"), + new mongo.ReadPreference(mongo.ReadPreference.PRIMARY_PREFERRED), + new mongo.ReadPreference("primary", tags), + mongo.ReadPreference("primary", tags) + ]; + + var prefsCloned = utils.clone(prefs); + + for (var i = 0; i < prefsCloned.length; i++) { + assert.notEqual(prefs[i], prefsCloned[i]); + assert.ok(prefsCloned[i] instanceof mongo.ReadPreference); + assert.ok(prefsCloned[i].isValid()); + if (prefs[i].tags) { + assert.ok(prefsCloned[i].tags); + assert.notEqual(prefs[i].tags, prefsCloned[i].tags); + assert.notEqual(prefs[i].tags[0], prefsCloned[i].tags[0]); + } else { + assert.equal(prefsCloned[i].tags, null); + } + } + + done(); + }); + + it('clones mongodb.Binary', function(done){ + if (!mongo) return done(); + + var buf = new Buffer('hi'); + var binary= new mongo.Binary(buf, 2); + var clone = utils.clone(binary); + assert.equal(binary.sub_type, clone.sub_type); + assert.equal(String(binary.buffer), String(buf)); + assert.ok(binary !== clone); + done(); + }) + + it('handles objects with no constructor', function(done) { + var name ='335'; + + var o = Object.create(null); + o.name = name; + + var clone; + assert.doesNotThrow(function() { + clone = utils.clone(o); + }); + + assert.equal(name, clone.name); + assert.ok(o != clone); + done(); + }); + + it('handles buffers', function(done){ + var buff = new Buffer(10); + buff.fill(1); + var clone = utils.clone(buff); + + for (var i = 0; i < buff.length; i++) { + assert.equal(buff[i], clone[i]); + } + + done(); + }); + }); +}); diff --git a/5-2/service/node_modules/mongoose/node_modules/ms/.npmignore b/5-2/service/node_modules/mongoose/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/5-2/service/node_modules/mongoose/node_modules/ms/History.md b/5-2/service/node_modules/mongoose/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/5-2/service/node_modules/mongoose/node_modules/ms/LICENSE b/5-2/service/node_modules/mongoose/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/5-2/service/node_modules/mongoose/node_modules/ms/README.md b/5-2/service/node_modules/mongoose/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/5-2/service/node_modules/mongoose/node_modules/ms/index.js b/5-2/service/node_modules/mongoose/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/5-2/service/node_modules/mongoose/node_modules/ms/package.json b/5-2/service/node_modules/mongoose/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/muri/.npmignore b/5-2/service/node_modules/mongoose/node_modules/muri/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/muri/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/5-2/service/node_modules/mongoose/node_modules/muri/.travis.yml b/5-2/service/node_modules/mongoose/node_modules/muri/.travis.yml new file mode 100644 index 0000000..895dbd3 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/muri/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/5-2/service/node_modules/mongoose/node_modules/muri/History.md b/5-2/service/node_modules/mongoose/node_modules/muri/History.md new file mode 100644 index 0000000..87b7053 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/muri/History.md @@ -0,0 +1,52 @@ + +1.0.0 / 2014-10-18 +================== + + * fixed; compatibility w/ strict mode #4 [vkarpov15](https://github.com/vkarpov15) + +0.3.1 / 2013-02-17 +================== + + * fixed; allow '#' in username and password #3 + +0.3.0 / 2013-01-14 +================== + + * fixed; default db logic #2 + +0.2.0 / 2013-01-09 +================== + + * changed; default db is now 'test' + +0.1.0 / 2012-12-18 +================== + + * changed; include .sock in UDS + +0.0.5 / 2012-12-18 +================== + + * fixed; unix domain sockets used with db names + +0.0.4 / 2012-12-01 +================== + + * handle multple specified protocols + +0.0.3 / 2012-11-29 +================== + + * validate mongodb:///db + * more detailed error message + +0.0.2 / 2012-11-02 +================== + + * add readPreferenceTags support + * add unix domain support + +0.0.1 / 2012-11-01 +================== + + * initial release diff --git a/5-2/service/node_modules/mongoose/node_modules/muri/LICENSE b/5-2/service/node_modules/mongoose/node_modules/muri/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/muri/LICENSE @@ -0,0 +1,22 @@ +(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/5-2/service/node_modules/mongoose/node_modules/muri/Makefile b/5-2/service/node_modules/mongoose/node_modules/muri/Makefile new file mode 100644 index 0000000..e6337bd --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/muri/Makefile @@ -0,0 +1,5 @@ + +test: + @node_modules/mocha/bin/mocha $(T) + +.PHONY: test diff --git a/5-2/service/node_modules/mongoose/node_modules/muri/README.md b/5-2/service/node_modules/mongoose/node_modules/muri/README.md new file mode 100644 index 0000000..3757419 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/muri/README.md @@ -0,0 +1,46 @@ +#Meet Muri! + +Muri is your friendly neighborhood [MongoDB URI](http://www.mongodb.org/display/DOCS/Connections) parser for Node.js. + + +###Install + + $ npm install muri + +###Use + +```js + var muri = require('muri'); + var o = muri('mongodb://user:pass@local,remote:27018,japan:27019/neatdb?replicaSet=myreplset&journal=true&w=2&wtimeoutMS=50'); + + console.log(o); + + { hosts: [ { host: 'local', port: 27017 }, + { host: 'remote', port: 27018 }, + { host: 'japan', port: 27019 } ], + db: 'neatdb', + options: { + replicaSet: 'myreplset', + journal: true, + w: 2, + wtimeoutMS: 50 + }, + auth: { + user: 'user', + pass: 'pass' + } + } +``` + +### Details + +The returned object contains the following properties: + +- db: the name of the database. defaults to "admin" if not specified +- auth: if auth is specified, this object will exist `{ user: 'username', pass: 'password' }` +- hosts: array of host/port objects, one for each specified `[{ host: 'local', port: 27107 }, { host: '..', port: port }]` + - if a port is not specified for a given host, the default port (27017) is used + - if a unix domain socket is passed, host/port will be undefined and `ipc` will be set to the value specified `[{ ipc: '/tmp/mongodb-27017' }]` +- options: this is a hash of all options specified in the querystring + +[LICENSE](https://github.com/aheckmann/muri/blob/master/LICENSE) diff --git a/5-2/service/node_modules/mongoose/node_modules/muri/index.js b/5-2/service/node_modules/mongoose/node_modules/muri/index.js new file mode 100644 index 0000000..f7b65dd --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/muri/index.js @@ -0,0 +1 @@ +module.exports = exports = require('./lib'); diff --git a/5-2/service/node_modules/mongoose/node_modules/muri/lib/index.js b/5-2/service/node_modules/mongoose/node_modules/muri/lib/index.js new file mode 100644 index 0000000..59cb396 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/muri/lib/index.js @@ -0,0 +1,241 @@ +// muri + +/** + * MongoDB URI parser as described here: + * http://www.mongodb.org/display/DOCS/Connections + */ + +/** + * Module dependencies + */ + +var qs = require('querystring'); + +/** + * Defaults + */ + +var DEFAULT_PORT = 27017; +var DEFAULT_DB = 'test'; +var ADMIN_DB = 'admin'; + +/** + * Muri + */ + +module.exports = exports = function muri (str) { + if (!/^mongodb:\/\//.test(str)) { + throw new Error('Invalid mongodb uri. Must begin with "mongodb://"' + + '\n Received: ' + str); + } + + var ret = { + hosts: [] + , db: DEFAULT_DB + , options: {} + } + + var match = /^mongodb:\/\/([^?]+)(\??.*)$/.exec(str); + if (!match || '/' == match[1]) { + throw new Error('Invalid mongodb uri. Missing hostname'); + } + + var uris = match[1]; + var path = match[2]; + var db; + + uris.split(',').forEach(function (uri) { + var o = parse(uri); + + if (o.host) { + ret.hosts.push({ + host: o.host + , port: parseInt(o.port, 10) + }) + + if (!db && o.db) { + db = o.db; + } + } else if (o.ipc) { + ret.hosts.push({ ipc: o.ipc }); + } + + if (o.auth) { + ret.auth = { + user: o.auth.user + , pass: o.auth.pass + } + } + }) + + if (!ret.hosts.length) { + throw new Error('Invalid mongodb uri. Missing hostname'); + } + + var parts = path.split('?'); + + if (!db) { + if (parts[0]) { + db = parts[0].replace(/^\//, ''); + } else { + // deal with ipc formats + db = /\/([^\.]+)$/.exec(match[1]); + if (db && db[1]) { + db = db[1]; + } + } + } + + if (db) { + ret.db = db; + } else if (ret.auth) { + ret.db = ADMIN_DB; + } + + if (parts[1]) { + ret.options = options(parts[1]); + } + + return ret; +} + +/** + * Parse str into key/val pairs casting values appropriately. + */ + +function options (str) { + var sep = /;/.test(str) + ? ';' + : '&'; + + var ret = qs.parse(str, sep); + + Object.keys(ret).forEach(function (key) { + var val = ret[key]; + if ('readPreferenceTags' == key) { + val = readPref(val); + if (val) { + ret[key] = Array.isArray(val) + ? val + : [val]; + } + } else { + ret[key] = format(val); + } + }); + + return ret; +} + +function format (val) { + var num; + + if ('true' == val) { + return true; + } else if ('false' == val) { + return false; + } else { + num = parseInt(val, 10); + if (!isNaN(num)) { + return num; + } + } + + return val; +} + +function readPref (val) { + var ret; + + if (Array.isArray(val)) { + ret = val.map(readPref).filter(Boolean); + return ret.length + ? ret + : undefined + } + + var pair = val.split(','); + var hasKeys; + ret = {}; + + pair.forEach(function (kv) { + kv = (kv || '').trim(); + if (!kv) return; + hasKeys = true; + var split = kv.split(':'); + ret[split[0]] = format(split[1]); + }); + + return hasKeys && ret; +} + +var ipcRgx = /\.sock/; + +function parse (uriString) { + // do not use require('url').parse b/c it can't handle # in username or pwd + // mongo uris are strange + + var uri = uriString; + var ret = {}; + var parts; + var auth; + var ipcs; + + // skip protocol + uri = uri.replace(/^mongodb:\/\//, ''); + + // auth + if (/@/.test(uri)) { + parts = uri.split(/@/); + auth = parts[0]; + uri = parts[1]; + + parts = auth.split(':'); + ret.auth = {}; + ret.auth.user = parts[0]; + ret.auth.pass = parts[1]; + } + + // unix domain sockets + if (ipcRgx.test(uri)) { + ipcs = uri.split(ipcRgx); + ret.ipc = ipcs[0] + '.sock'; + + // included a database? + if (ipcs[1]) { + // strip leading / from database name + ipcs[1] = ipcs[1].replace(/^\//, ''); + + if (ipcs[1]) { + ret.db = ipcs[1]; + } + } + + return ret; + } + + // database name + parts = uri.split('/'); + if (parts[1]) ret.db = parts[1]; + + // ipv6, [ip]:host + if (/^\[[^\]]+\]:\d+/.test(parts[0])) { + ret.host = parts[0].substring(1, parts[0].indexOf(']:')); + ret.port = parts[0].substring(parts[0].indexOf(']:') + ']:'.length); + } else { + // host:port + parts = parts[0].split(':'); + ret.host = parts[0]; + ret.port = parts[1] || DEFAULT_PORT; + } + + return ret; +} + +/** + * Version + */ + +module.exports.version = JSON.parse( + require('fs').readFileSync(__dirname + '/../package.json', 'utf8') +).version; diff --git a/5-2/service/node_modules/mongoose/node_modules/muri/package.json b/5-2/service/node_modules/mongoose/node_modules/muri/package.json new file mode 100644 index 0000000..32a9e43 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/muri/package.json @@ -0,0 +1,56 @@ +{ + "name": "muri", + "version": "1.1.0", + "description": "MongoDB URI parser", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/muri.git" + }, + "keywords": [ + "mongodb", + "uri", + "parser" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.21.5" + }, + "gitHead": "8f373948ef317865044994aaa98a013e769b2952", + "bugs": { + "url": "https://github.com/aheckmann/muri/issues" + }, + "homepage": "https://github.com/aheckmann/muri", + "_id": "muri@1.1.0", + "_shasum": "a3a6d74e68a880f433a249a74969cbb665cc0add", + "_from": "muri@1.1.0", + "_npmVersion": "2.5.1", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "vkarpov15", + "email": "val@karpov.io" + } + ], + "dist": { + "shasum": "a3a6d74e68a880f433a249a74969cbb665cc0add", + "tarball": "http://registry.npmjs.org/muri/-/muri-1.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/muri/-/muri-1.1.0.tgz" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/muri/test/index.js b/5-2/service/node_modules/mongoose/node_modules/muri/test/index.js new file mode 100644 index 0000000..65a4cfc --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/muri/test/index.js @@ -0,0 +1,321 @@ + +var muri = require('../') +var assert = require('assert') + +describe('muri', function(){ + it('must begin with mongodb://', function(done){ + assert.throws(function () { + muri('localhost:27017'); + }, /Invalid mongodb uri/); + assert.doesNotThrow(function () { + muri('mongodb://localhost:27017'); + }) + done(); + }) + + describe('user:password', function(done){ + it('is optional', function(done){ + var uri = 'mongodb://local:27017'; + var val = muri(uri); + assert.ok(!val.auth); + done(); + }) + + it('parses properly', function(done){ + var uri = 'mongodb://user:password@local:27017'; + var val = muri(uri); + assert.ok(val.auth); + assert.equal('user', val.auth.user); + assert.equal('password', val.auth.pass); + done(); + }) + + it('handles # in the username', function(done){ + var uri = 'mongodb://us#er:password@local:27017'; + var val = muri(uri); + assert.ok(val.auth); + assert.equal('us#er', val.auth.user); + assert.equal('password', val.auth.pass); + done(); + }) + + it('handles # in the password', function(done){ + var uri = 'mongodb://user:pa#ssword@local:27017'; + var val = muri(uri); + assert.ok(val.auth); + assert.equal('user', val.auth.user); + assert.equal('pa#ssword', val.auth.pass); + done(); + }) + }) + + describe('host', function(){ + it('must be specified', function(done){ + assert.throws(function () { + muri('mongodb://'); + }, /Missing host/) + assert.throws(function () { + muri('mongodb:///fake'); + }, /Missing host/) + assert.throws(function () { + muri('mongodb://?yep'); + }, /Missing host/) + assert.throws(function () { + muri('mongodb:///?yep'); + }, /Missing host/) + + var val = muri('mongodb://local'); + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal('local', val.hosts[0].host); + done(); + }) + + it('supports replica sets', function(done){ + var val = muri('mongodb://local:27017,remote:27018,japan:99999'); + assert.ok(Array.isArray(val.hosts)); + assert.equal(3, val.hosts.length); + assert.equal('local', val.hosts[0].host); + assert.equal(27017, val.hosts[0].port); + assert.equal('remote', val.hosts[1].host); + assert.equal(27018, val.hosts[1].port); + assert.equal('japan', val.hosts[2].host); + assert.equal(99999, val.hosts[2].port); + done(); + }) + }) + + describe('port', function(){ + + describe('with single host', function(){ + it('defaults to 27017 if not specified', function(done){ + var val = muri('mongodb://local/'); + assert.equal(27017, val.hosts[0].port); + done(); + }) + + it('uses what is specified', function(done){ + var val = muri('mongodb://local:27018'); + assert.equal(27018, val.hosts[0].port); + done(); + }) + }) + + describe('with replica sets', function(){ + var val; + + before(function(){ + val = muri('mongodb://local,remote:27018,another'); + }) + + it('defaults to 27017 if not specified', function(done){ + assert.equal(27017, val.hosts[0].port); + assert.equal(27017, val.hosts[2].port); + done(); + }) + + it('uses what is specified', function(done){ + assert.equal(27018, val.hosts[1].port); + done(); + }) + }) + }) + + describe('database', function(){ + it('default', function(done){ + var val = muri('mongodb://localhost/'); + assert.equal('test', val.db); + var val = muri('mongodb://localhost'); + assert.equal('test', val.db); + done(); + }) + it('is overridable', function(done){ + var val = muri('mongodb://localhost,a,x:34343,b/muri'); + assert.equal('muri', val.db); + done(); + }) + it('works with multiple specified protocols', function(done){ + var uri = 'mongodb://localhost:27020/testing,mongodb://localhost:27019,mongodb://localhost:27018' + var val = muri(uri); + assert.equal('testing', val.db); + done(); + }) + }) + + describe('querystring separator', function(){ + it('can be ; ', function(done){ + var val = muri('mongodb://muri/?replicaSet=myreplset;slaveOk=true;x=1'); + assert.ok(val.options); + assert.equal(true, val.options.slaveOk); + assert.equal('myreplset', val.options.replicaSet); + assert.equal(1, val.options.x); + done(); + }) + it('can be & ', function(done){ + var val = muri('mongodb://muri/?replicaSet=myreplset&slaveOk=true&x=1'); + assert.ok(val.options); + assert.equal(true, val.options.slaveOk); + assert.equal('myreplset', val.options.replicaSet); + assert.equal(1, val.options.x); + done(); + }) + }) + + describe('readPref tags', function(){ + describe('with & ', function(){ + it('mongodb://localhost/?readPreferenceTags=dc:ny', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny'); + assert.equal('test', val.db); + assert.deepEqual([{ dc: 'ny' }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1'); + assert.deepEqual([{ dc: 'ny', rack: 1 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2'); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2&readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2&readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny&readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny&readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'ny' }], val.options.readPreferenceTags); + done(); + }) + }) + describe('with ; ', function(){ + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2'); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2;readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2;readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'ny' }], val.options.readPreferenceTags); + done(); + }) + }) + }) + + describe('unix domain sockets', function(){ + it('without auth', function(done){ + var val = muri('mongodb:///tmp/mongodb-27017.sock?safe=false'); + assert.equal(val.db, 'test') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('without auth with a database name', function(done){ + var val = muri('mongodb:///tmp/mongodb-27017.sock/tester?safe=false'); + assert.equal(val.db, 'tester') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock?safe=false'); + assert.equal(val.db, 'admin') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth with a db name', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock/tester?safe=false'); + assert.equal(val.db, 'tester') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth + repl sets', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock,/tmp/another-27018.sock?safe=false'); + assert.equal(val.db, 'admin') + assert.ok(Array.isArray(val.hosts)); + assert.equal(2, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(val.hosts[1].ipc, '/tmp/another-27018.sock') + assert.equal(val.hosts[1].host, undefined); + assert.equal(val.hosts[1].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth + repl sets with a db name', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock,/tmp/another-27018.sock/tester?safe=false'); + assert.equal(val.db, 'tester') + assert.ok(Array.isArray(val.hosts)); + assert.equal(2, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(val.hosts[1].ipc, '/tmp/another-27018.sock') + assert.equal(val.hosts[1].host, undefined); + assert.equal(val.hosts[1].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + }) + + it('all together now', function(done){ + var uri = 'mongodb://u#ser:pas#s@local,remote:27018,japan:27019/neatdb' + uri += '?replicaSet=myreplset&journal=true&w=2&wtimeoutMS=50' + var val = muri(uri); + + assert.equal('u#ser', val.auth.user); + assert.equal('pas#s', val.auth.pass); + assert.equal('neatdb', val.db); + assert.equal(3, val.hosts.length); + assert.equal('local', val.hosts[0].host); + assert.strictEqual(27017, val.hosts[0].port); + assert.equal('remote', val.hosts[1].host); + assert.strictEqual(27018, val.hosts[1].port); + assert.equal('japan', val.hosts[2].host); + assert.strictEqual(27019, val.hosts[2].port); + assert.equal('myreplset', val.options.replicaSet); + assert.equal(true, val.options.journal); + assert.equal(50, val.options.wtimeoutMS); + done(); + }); + + it('ipv6', function(done) { + var uri = 'mongodb://[::1]:27017/test'; + var val = muri(uri); + assert.equal(1, val.hosts.length); + assert.equal('::1', val.hosts[0].host); + assert.equal(27017, val.hosts[0].port); + done(); + }); + + it('has a version', function(done){ + assert.ok(muri.version); + done(); + }) +}) diff --git a/5-2/service/node_modules/mongoose/node_modules/regexp-clone/.npmignore b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/5-2/service/node_modules/mongoose/node_modules/regexp-clone/.travis.yml b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/.travis.yml new file mode 100644 index 0000000..58f2371 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.6 + - 0.8 + - 0.10 diff --git a/5-2/service/node_modules/mongoose/node_modules/regexp-clone/History.md b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/History.md new file mode 100644 index 0000000..0beedfc --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/History.md @@ -0,0 +1,5 @@ + +0.0.1 / 2013-04-17 +================== + + * initial commit diff --git a/5-2/service/node_modules/mongoose/node_modules/regexp-clone/LICENSE b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/LICENSE new file mode 100644 index 0000000..98c7c89 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 [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/5-2/service/node_modules/mongoose/node_modules/regexp-clone/Makefile b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/Makefile new file mode 100644 index 0000000..6c8fb75 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/Makefile @@ -0,0 +1,5 @@ + +test: + @./node_modules/.bin/mocha $(T) --async-only $(TESTS) + +.PHONY: test diff --git a/5-2/service/node_modules/mongoose/node_modules/regexp-clone/README.md b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/README.md new file mode 100644 index 0000000..2aabe5c --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/README.md @@ -0,0 +1,18 @@ +#regexp-clone +============== + +Clones RegExps with flag preservation + +```js +var regexpClone = require('regexp-clone'); + +var a = /somethin/g; +console.log(a.global); // true + +var b = regexpClone(a); +console.log(b.global); // true +``` + +## License + +[MIT](https://github.com/aheckmann/regexp-clone/blob/master/LICENSE) diff --git a/5-2/service/node_modules/mongoose/node_modules/regexp-clone/index.js b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/index.js new file mode 100644 index 0000000..e5850ca --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/index.js @@ -0,0 +1,20 @@ + +var toString = Object.prototype.toString; + +function isRegExp (o) { + return 'object' == typeof o + && '[object RegExp]' == toString.call(o); +} + +module.exports = exports = function (regexp) { + if (!isRegExp(regexp)) { + throw new TypeError('Not a RegExp'); + } + + var flags = []; + if (regexp.global) flags.push('g'); + if (regexp.multiline) flags.push('m'); + if (regexp.ignoreCase) flags.push('i'); + return new RegExp(regexp.source, flags.join('')); +} + diff --git a/5-2/service/node_modules/mongoose/node_modules/regexp-clone/package.json b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/package.json new file mode 100644 index 0000000..29b6d17 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/package.json @@ -0,0 +1,51 @@ +{ + "name": "regexp-clone", + "version": "0.0.1", + "description": "Clone RegExps with options", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/regexp-clone.git" + }, + "keywords": [ + "RegExp", + "clone" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.8.1" + }, + "readme": "#regexp-clone\n==============\n\nClones RegExps with flag preservation\n\n```js\nvar regexpClone = require('regexp-clone');\n\nvar a = /somethin/g;\nconsole.log(a.global); // true\n\nvar b = regexpClone(a);\nconsole.log(b.global); // true\n```\n\n## License\n\n[MIT](https://github.com/aheckmann/regexp-clone/blob/master/LICENSE)\n", + "readmeFilename": "README.md", + "_id": "regexp-clone@0.0.1", + "dist": { + "shasum": "a7c2e09891fdbf38fbb10d376fb73003e68ac589", + "tarball": "http://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz" + }, + "_from": "regexp-clone@0.0.1", + "_npmVersion": "1.2.14", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "directories": {}, + "_shasum": "a7c2e09891fdbf38fbb10d376fb73003e68ac589", + "_resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz", + "bugs": { + "url": "https://github.com/aheckmann/regexp-clone/issues" + }, + "homepage": "https://github.com/aheckmann/regexp-clone#readme" +} diff --git a/5-2/service/node_modules/mongoose/node_modules/regexp-clone/test/index.js b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/test/index.js new file mode 100644 index 0000000..264a776 --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/regexp-clone/test/index.js @@ -0,0 +1,112 @@ + +var assert = require('assert') +var clone = require('../'); + +describe('regexp-clone', function(){ + function hasEqualSource (a, b) { + assert.ok(a !== b); + assert.equal(a.source, b.source); + } + + function isInsensitive (a) { + assert.ok(a.ignoreCase); + } + + function isGlobal (a) { + assert.ok(a.global); + } + + function isMultiline (a) { + assert.ok(a.multiline); + } + + function insensitiveFlag (a) { + var b = clone(a); + hasEqualSource(a, b); + isInsensitive(a); + isInsensitive(b); + } + + function globalFlag (a) { + var b = clone(a); + hasEqualSource(a, b); + isGlobal(a); + isGlobal(b); + } + + function multilineFlag (a) { + var b = clone(a); + hasEqualSource(a, b); + isMultiline(a); + isMultiline(b); + } + + describe('literals', function(){ + it('insensitive flag', function(done){ + var a = /hello/i; + insensitiveFlag(a); + done(); + }) + it('global flag', function(done){ + var a = /hello/g; + globalFlag(a); + done(); + }) + it('multiline flag', function(done){ + var a = /hello/m; + multilineFlag(a); + done(); + }) + it('no flags', function(done){ + var a = /hello/; + var b = clone(a); + hasEqualSource(a, b); + assert.ok(!a.insensitive); + assert.ok(!a.global); + assert.ok(!a.global); + done(); + }) + it('all flags', function(done){ + var a = /hello/gim; + insensitiveFlag(a); + globalFlag(a); + multilineFlag(a); + done(); + }) + }) + + describe('instances', function(){ + it('insensitive flag', function(done){ + var a = new RegExp('hello', 'i'); + insensitiveFlag(a); + done(); + }) + it('global flag', function(done){ + var a = new RegExp('hello', 'g'); + globalFlag(a); + done(); + }) + it('multiline flag', function(done){ + var a = new RegExp('hello', 'm'); + multilineFlag(a); + done(); + }) + it('no flags', function(done){ + var a = new RegExp('hmm'); + var b = clone(a); + hasEqualSource(a, b); + assert.ok(!a.insensitive); + assert.ok(!a.global); + assert.ok(!a.global); + done(); + }) + it('all flags', function(done){ + var a = new RegExp('hello', 'gim'); + insensitiveFlag(a); + globalFlag(a); + multilineFlag(a); + done(); + }) + }) +}) + diff --git a/5-2/service/node_modules/mongoose/node_modules/sliced/History.md b/5-2/service/node_modules/mongoose/node_modules/sliced/History.md new file mode 100644 index 0000000..e45cefe --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/sliced/History.md @@ -0,0 +1,41 @@ + +1.0.1 / 2015-07-14 +================== + + * fixed; missing file introduced in 4f5cea1 + +1.0.0 / 2015-07-12 +================== + + * Remove unnecessary files from npm package - #6 via joaquimserafim + * updated readme stats + +0.0.5 / 2013-02-05 +================== + + * optimization: remove use of arguments [jkroso](https://github.com/jkroso) + * add scripts to component.json [jkroso](https://github.com/jkroso) + * tests; remove time for travis + +0.0.4 / 2013-01-07 +================== + + * added component.json #1 [jkroso](https://github.com/jkroso) + * reversed array loop #1 [jkroso](https://github.com/jkroso) + * remove fn params + +0.0.3 / 2012-09-29 +================== + + * faster with negative start args + +0.0.2 / 2012-09-29 +================== + + * support full [].slice semantics + +0.0.1 / 2012-09-29 +=================== + + * initial release + diff --git a/5-2/service/node_modules/mongoose/node_modules/sliced/LICENSE b/5-2/service/node_modules/mongoose/node_modules/sliced/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/sliced/LICENSE @@ -0,0 +1,22 @@ +(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/5-2/service/node_modules/mongoose/node_modules/sliced/README.md b/5-2/service/node_modules/mongoose/node_modules/sliced/README.md new file mode 100644 index 0000000..b6ff85e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/sliced/README.md @@ -0,0 +1,62 @@ +#sliced +========== + +A faster alternative to `[].slice.call(arguments)`. + +[![Build Status](https://secure.travis-ci.org/aheckmann/sliced.png)](http://travis-ci.org/aheckmann/sliced) + +Example output from [benchmark.js](https://github.com/bestiejs/benchmark.js) + + Array.prototype.slice.call x 1,401,820 ops/sec ±2.16% (90 runs sampled) + [].slice.call x 1,313,116 ops/sec ±2.04% (96 runs sampled) + cached slice.call x 10,297,910 ops/sec ±1.81% (96 runs sampled) + sliced x 19,906,019 ops/sec ±1.23% (89 runs sampled) + fastest is sliced + + Array.prototype.slice.call(arguments, 1) x 1,373,238 ops/sec ±1.84% (95 runs sampled) + [].slice.call(arguments, 1) x 1,395,336 ops/sec ±1.36% (93 runs sampled) + cached slice.call(arguments, 1) x 9,926,018 ops/sec ±1.67% (92 runs sampled) + sliced(arguments, 1) x 20,747,990 ops/sec ±1.16% (93 runs sampled) + fastest is sliced(arguments, 1) + + Array.prototype.slice.call(arguments, -1) x 1,319,908 ops/sec ±2.12% (91 runs sampled) + [].slice.call(arguments, -1) x 1,336,170 ops/sec ±1.33% (97 runs sampled) + cached slice.call(arguments, -1) x 10,078,718 ops/sec ±1.21% (98 runs sampled) + sliced(arguments, -1) x 20,471,474 ops/sec ±1.81% (92 runs sampled) + fastest is sliced(arguments, -1) + + Array.prototype.slice.call(arguments, -2, -10) x 1,369,246 ops/sec ±1.68% (97 runs sampled) + [].slice.call(arguments, -2, -10) x 1,387,935 ops/sec ±1.70% (95 runs sampled) + cached slice.call(arguments, -2, -10) x 9,593,428 ops/sec ±1.23% (97 runs sampled) + sliced(arguments, -2, -10) x 23,178,931 ops/sec ±1.70% (92 runs sampled) + fastest is sliced(arguments, -2, -10) + + Array.prototype.slice.call(arguments, -2, -1) x 1,441,300 ops/sec ±1.26% (98 runs sampled) + [].slice.call(arguments, -2, -1) x 1,410,326 ops/sec ±1.96% (93 runs sampled) + cached slice.call(arguments, -2, -1) x 9,854,419 ops/sec ±1.02% (97 runs sampled) + sliced(arguments, -2, -1) x 22,550,801 ops/sec ±1.86% (91 runs sampled) + fastest is sliced(arguments, -2, -1) + +_Benchmark [source](https://github.com/aheckmann/sliced/blob/master/bench.js)._ + +##Usage + +`sliced` accepts the same arguments as `Array#slice` so you can easily swap it out. + +```js +function zing () { + var slow = [].slice.call(arguments, 1, 8); + var args = slice(arguments, 1, 8); + + var slow = Array.prototype.slice.call(arguments); + var args = slice(arguments); + // etc +} +``` + +## install + + npm install sliced + + +[LICENSE](https://github.com/aheckmann/sliced/blob/master/LICENSE) diff --git a/5-2/service/node_modules/mongoose/node_modules/sliced/index.js b/5-2/service/node_modules/mongoose/node_modules/sliced/index.js new file mode 100644 index 0000000..d88c85b --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/sliced/index.js @@ -0,0 +1,33 @@ + +/** + * An Array.prototype.slice.call(arguments) alternative + * + * @param {Object} args something with a length + * @param {Number} slice + * @param {Number} sliceEnd + * @api public + */ + +module.exports = function (args, slice, sliceEnd) { + var ret = []; + var len = args.length; + + if (0 === len) return ret; + + var start = slice < 0 + ? Math.max(0, slice + len) + : slice || 0; + + if (sliceEnd !== undefined) { + len = sliceEnd < 0 + ? sliceEnd + len + : sliceEnd + } + + while (len-- > start) { + ret[len - start] = args[len]; + } + + return ret; +} + diff --git a/5-2/service/node_modules/mongoose/node_modules/sliced/package.json b/5-2/service/node_modules/mongoose/node_modules/sliced/package.json new file mode 100644 index 0000000..6bfb26e --- /dev/null +++ b/5-2/service/node_modules/mongoose/node_modules/sliced/package.json @@ -0,0 +1,59 @@ +{ + "name": "sliced", + "version": "1.0.1", + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "main": "index.js", + "files": [ + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/sliced" + }, + "keywords": [ + "arguments", + "slice", + "array" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.5.0", + "benchmark": "~1.0.0" + }, + "dependencies": {}, + "gitHead": "e7c989016d2062995cd102322b65784ba8977ee3", + "bugs": { + "url": "https://github.com/aheckmann/sliced/issues" + }, + "homepage": "https://github.com/aheckmann/sliced", + "_id": "sliced@1.0.1", + "_shasum": "0b3a662b5d04c3177b1926bea82b03f837a2ef41", + "_from": "sliced@1.0.1", + "_npmVersion": "2.8.3", + "_nodeVersion": "1.8.1", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "dist": { + "shasum": "0b3a662b5d04c3177b1926bea82b03f837a2ef41", + "tarball": "http://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz" +} diff --git a/5-2/service/node_modules/mongoose/package.json b/5-2/service/node_modules/mongoose/package.json new file mode 100644 index 0000000..b45fc2e --- /dev/null +++ b/5-2/service/node_modules/mongoose/package.json @@ -0,0 +1,133 @@ +{ + "name": "mongoose", + "description": "Mongoose MongoDB ODM", + "version": "4.4.3", + "author": { + "name": "Guillermo Rauch", + "email": "guillermo@learnboost.com" + }, + "keywords": [ + "mongodb", + "document", + "model", + "schema", + "database", + "odm", + "data", + "datastore", + "query", + "nosql", + "orm", + "db" + ], + "license": "MIT", + "dependencies": { + "async": "1.5.2", + "bson": "0.4.21", + "hooks-fixed": "1.1.0", + "kareem": "1.0.1", + "mongodb": "2.1.6", + "mpath": "0.2.1", + "mpromise": "0.5.5", + "mquery": "1.6.3", + "ms": "0.7.1", + "muri": "1.1.0", + "regexp-clone": "0.0.1", + "sliced": "1.0.1" + }, + "devDependencies": { + "acquit": "0.4.1", + "acquit-ignore": "0.0.3", + "benchmark": "2.0.0", + "bluebird": "3.1.4", + "co": "4.6.0", + "dox": "0.3.1", + "eslint": "2.0.0-beta.3", + "highlight.js": "7.0.1", + "istanbul": "0.4.2", + "jade": "0.26.3", + "markdown": "0.3.1", + "marked": "0.3.5", + "mocha": "2.3.4", + "node-static": "0.7.7", + "power-assert": "1.2.0", + "q": "1.4.1", + "tbd": "0.6.4", + "uglify-js": "2.6.1", + "underscore": "1.8.3" + }, + "browserDependencies": { + "browserify": "4.1.10", + "chai": "3.5.0", + "karma": "0.12.16", + "karma-chai": "0.1.0", + "karma-mocha": "0.1.4", + "karma-chrome-launcher": "0.1.4", + "karma-sauce-launcher": "0.2.8" + }, + "directories": { + "lib": "./lib/mongoose" + }, + "scripts": { + "fix-lint": "eslint . --fix", + "install-browser": "npm install `node format_deps.js`", + "test": "mocha test/*.test.js test/**/*.test.js", + "posttest": "eslint . --quiet", + "test-cov": "istanbul cover --report text --report html _mocha test/*.test.js" + }, + "main": "./index.js", + "engines": { + "node": ">=0.6.19" + }, + "bugs": { + "url": "https://github.com/Automattic/mongoose/issues/new", + "email": "mongoose-orm@googlegroups.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/Automattic/mongoose.git" + }, + "homepage": "http://mongoosejs.com", + "browser": "lib/browser.js", + "gitHead": "059520ff1c2242c02e1bf9f00ddb9a962947dd37", + "_id": "mongoose@4.4.3", + "_shasum": "0c7aeb37615cb631307cd2dff5d76c8681dac9ea", + "_from": "mongoose@*", + "_npmVersion": "3.3.12", + "_nodeVersion": "5.4.1", + "_npmUser": { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + "dist": { + "shasum": "0c7aeb37615cb631307cd2dff5d76c8681dac9ea", + "tarball": "http://registry.npmjs.org/mongoose/-/mongoose-4.4.3.tgz" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-6-west.internal.npmjs.com", + "tmp": "tmp/mongoose-4.4.3.tgz_1455061137802_0.8885454896371812" + }, + "_resolved": "https://registry.npmjs.org/mongoose/-/mongoose-4.4.3.tgz" +} diff --git a/5-2/service/node_modules/mongoose/release-items.md b/5-2/service/node_modules/mongoose/release-items.md new file mode 100644 index 0000000..3dc270e --- /dev/null +++ b/5-2/service/node_modules/mongoose/release-items.md @@ -0,0 +1,29 @@ +## mongoose release procedure + +1. tests must pass +2. update package.json version +3. update History.md using `git changelog` or similar. list the related ticket(s) # as well as a link to the github user who fixed it if applicable. +4. git commit -m 'release x.x.x' +5. git tag x.x.x +6. git push origin BRANCH --tags && npm publish +7. update mongoosejs.com (see "updating the website" below) +8. announce to google groups - include the relevant change log and links to issues +9. tweet google group announcement from [@mongoosejs](https://twitter.com/mongoosejs) +10. change package.json version to next patch version suffixed with '-pre' and commit "now working on x.x.x" +11. if this is a legacy release, `git merge` changes into master. + +## updating the website + +For 4.x + +0. Change to the master branch +1. execute `make docs` (when this process completes you'll be on the gh-pages branch) +2. `git commit -a -m 'website; regen <4.x.x>'` +3. `git push origin gh-pages` + +For 3.8.x: + +0. Change to the 3.8.x branch +1. execute `make docs_legacy` (when this process completes you'll be on the gh-pages branch) +2. `git commit -a -m 'website; regen '` +3. `git push origin gh-pages` diff --git a/5-2/service/node_modules/mongoose/static.js b/5-2/service/node_modules/mongoose/static.js new file mode 100644 index 0000000..d84e59f --- /dev/null +++ b/5-2/service/node_modules/mongoose/static.js @@ -0,0 +1,24 @@ + +var static = require('node-static'); +var server = new static.Server('.', {cache: 0}); + +require('http').createServer(function(req, res) { + if (req.url === '/favicon.ico') { + req.destroy(); + res.statusCode = 204; + return res.end(); + } + + req.on('end', function() { + server.serve(req, res, function(err) { + if (err) { + console.error(err, req.url); + res.writeHead(err.status, err.headers); + res.end(); + } + }); + }); + req.resume(); +}).listen(8088); + +console.error('now listening on http://localhost:8088'); diff --git a/5-2/service/node_modules/mongoose/website.js b/5-2/service/node_modules/mongoose/website.js new file mode 100644 index 0000000..a1186a5 --- /dev/null +++ b/5-2/service/node_modules/mongoose/website.js @@ -0,0 +1,87 @@ +var fs = require('fs'); +var jade = require('jade'); +var package = require('./package'); +var hl = require('./docs/helpers/highlight'); +var linktype = require('./docs/helpers/linktype'); +var href = require('./docs/helpers/href'); +var klass = require('./docs/helpers/klass'); + +// add custom jade filters +require('./docs/helpers/filters')(jade); + +function getVersion() { + var hist = fs.readFileSync('./History.md', 'utf8').replace(/\r/g, '\n').split('\n'); + for (var i = 0; i < hist.length; ++i) { + var line = (hist[i] || '').trim(); + if (!line) { + continue; + } + var match = /^\s*([^\s]+)\s/.exec(line); + if (match && match[1]) { + return match[1]; + } + } + throw new Error('no match found'); +} + +function getUnstable(ver) { + ver = ver.replace('-pre'); + var spl = ver.split('.'); + spl = spl.map(function(i) { + return parseInt(i, 10); + }); + spl[1]++; + spl[2] = 'x'; + return spl.join('.'); +} + +// use last release +package.version = getVersion(); +package.unstable = getUnstable(package.version); + +var filemap = require('./docs/source'); +var files = Object.keys(filemap); + +function jadeify(filename, options, newfile) { + options = options || {}; + options.package = package; + options.hl = hl; + options.linktype = linktype; + options.href = href; + options.klass = klass; + jade.renderFile(filename, options, function(err, str) { + if (err) { + console.error(err.stack); + return; + } + + newfile = newfile || filename.replace('.jade', '.html'); + fs.writeFile(newfile, str, function(err) { + if (err) { + console.error('could not write', err.stack); + } else { + console.log('%s : rendered ', new Date, newfile); + } + }); + }); +} + +files.forEach(function(file) { + var filename = __dirname + '/' + file; + jadeify(filename, filemap[file]); + + if (process.argv[2] === '--watch') { + fs.watchFile(filename, {interval: 1000}, function(cur, prev) { + if (cur.mtime > prev.mtime) { + jadeify(filename, filemap[file]); + } + }); + } +}); + +var acquit = require('./docs/source/acquit'); +var acquitFiles = Object.keys(acquit); +acquitFiles.forEach(function(file) { + var filename = __dirname + '/docs/acquit.jade'; + jadeify(filename, acquit[file], __dirname + '/docs/' + file); +}); diff --git a/5-2/service/package.json b/5-2/service/package.json new file mode 100644 index 0000000..d88821e --- /dev/null +++ b/5-2/service/package.json @@ -0,0 +1,12 @@ +{ + "name": "service", + "version": "1.0.0", + "description": "", + "main": "server.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "start": "node server.js" + }, + "author": "", + "license": "ISC" +} diff --git a/5-2/service/server.js b/5-2/service/server.js new file mode 100644 index 0000000..9799cff --- /dev/null +++ b/5-2/service/server.js @@ -0,0 +1,28 @@ +var express = require('express'); +var bodyParser = require('body-parser'); +var mongoose = require('mongoose'); +var User = require('./models/User'); +var app = express(); +app.use(bodyParser.json()); + +mongoUri = process.env.mongoUri +mongoose.connect(mongoUri); + +app.get('/users', function(req, res) { + User.find({}, function(err, users) { + res.json(users); + }); +}); + +app.post('/users', function(req,res) { + console.log('post /users'); + var user = new User(req.body); + user.save(function(err, user) { + res.json(user); + }); +}); + +var port = process.env.port || 3000; +app.listen(port, function() { + console.log('server started'); +}); \ No newline at end of file diff --git a/5-3.txt b/5-3.txt new file mode 100644 index 0000000..a30a805 --- /dev/null +++ b/5-3.txt @@ -0,0 +1,123 @@ +//terminal +// cd notifications-service/ +// vi Dockerfile + +/* Dockerfile +FROM node:0.12.7 + +RUN mkdir -p /user/src/app +WORKDIR /usr/src/app + +COPY . /usr/src/app +RUN npm install + +EXPOSE 3000 + +CMD [ "npm", "start" ] + +*/ + +//terminal +// vi server.js + +/* server.js +var express = require('express'); +var app = expess(); + +app.get('/notify', function(req, res) { + //Code to sned user an email notification... + console.log('user notified'); + res.json({msg: 'user notified'}); +}); + +app.listen(process.env.port || 3000); +*/ + +// vi server.js + +/* server.js +var express = require('express'); +var bodyParser = require('body-parser'); +var mongoose = require('mongoose'); +var request = require('superagent'); +var User = require('./models/User'); +var app = express(); +app.use(bodyParser.json()); + +mongoUri = process.env.mongoUri +mongoose.connect(mongoUri); + +app.get('/users', function(req, res) { + User.find({}, function(err, users) { + if(err) res.status(500).json({success: false}) + else { + res.json(users); + } + }); +}); + +app.post('/users', function(req,res) { + console.log('post /users'); + var user = new User(req.body); + user.save(function(err, user) { + if (err) res.status(500).json({success: false}) + else { + reques.get('http://notifications/notify', function(response) { + res.json(user); + }); + } + }); +}); + +var port = process.env.port || 3000; +app.listen(port, function() { + console.log('server started'); +}); +*/ + +//terminal +// vi docker-compose.yml + +/* docker-compose.yml +database: + image: mongo + +notifications: + build: ./notifications-service + environment: + port: "80" + +api: + build: . + volumes: + - .:/usr/src/app + ports: + - "3000:80" + links: + - database + - notifications + environment: + port: "80" + mongoUri: "mongodb://database/app-dev" +*/ + +//terminal +// docker-compose up +// docker ps +// docker exec -it 3a0a9b353bee /bin/bash +// cat /etc/hosts +// exit +// vi docker-compose.yml +// cd notifications-service/ +// vi docker-compose.yml + +/* notifications-service/docker-compose.yml +notifications: + build: . + ports: + - "3000:80" +*/ + + + + diff --git a/5-3/Dockerfile b/5-3/Dockerfile new file mode 100644 index 0000000..7ac2798 --- /dev/null +++ b/5-3/Dockerfile @@ -0,0 +1,11 @@ +FROM node:0.12.7 + +RUN mkdir -p /user/src/app +WORKDIR /usr/src/app + +COPY . /usr/src/app +RUN npm install + +EXPOSE 3000 + +CMD [ "npm", "start" ] \ No newline at end of file diff --git a/5-3/docker-compose.yml b/5-3/docker-compose.yml new file mode 100644 index 0000000..d927941 --- /dev/null +++ b/5-3/docker-compose.yml @@ -0,0 +1,20 @@ +database: + image: mongo + +notifications: + build: ./notifications-service + environment: + port: "80" + +api: + build: . + volumes: + - .:/usr/src/app + ports: + - "3000:80" + links: + - database + - notifications + environment: + port: "80" + mongoUri: "mongodb://database/app-dev" \ No newline at end of file diff --git a/5-3/node_modules/body-parser/HISTORY.md b/5-3/node_modules/body-parser/HISTORY.md new file mode 100644 index 0000000..c9d5168 --- /dev/null +++ b/5-3/node_modules/body-parser/HISTORY.md @@ -0,0 +1,425 @@ +1.14.2 / 2015-12-16 +=================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + * deps: qs@5.2.0 + * deps: raw-body@~2.1.5 + - deps: bytes@2.2.0 + - deps: iconv-lite@0.4.13 + * deps: type-is@~1.6.10 + - deps: mime-types@~2.1.9 + +1.14.1 / 2015-09-27 +=================== + + * Fix issue where invalid charset results in 400 when `verify` used + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + * deps: raw-body@~2.1.4 + - Fix masking critical errors from `iconv-lite` + - deps: iconv-lite@0.4.12 + * deps: type-is@~1.6.9 + - deps: mime-types@~2.1.7 + +1.14.0 / 2015-09-16 +=================== + + * Fix JSON strict parse error to match syntax errors + * Provide static `require` analysis in `urlencoded` parser + * deps: depd@~1.1.0 + - Support web browser loading + * deps: qs@5.1.0 + * deps: raw-body@~2.1.3 + - Fix sync callback when attaching data listener causes sync read + * deps: type-is@~1.6.8 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.6 + +1.13.3 / 2015-07-31 +=================== + + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +1.13.2 / 2015-07-05 +=================== + + * deps: iconv-lite@0.4.11 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix user-visible incompatibilities from 3.1.0 + - Fix various parsing edge cases + * deps: raw-body@~2.1.2 + - Fix error stack traces to skip `makeError` + - deps: iconv-lite@0.4.11 + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +1.13.1 / 2015-06-16 +=================== + + * deps: qs@2.4.2 + - Downgraded from 3.1.0 because of user-visible incompatibilities + +1.13.0 / 2015-06-14 +=================== + + * Add `statusCode` property on `Error`s, in addition to `status` + * Change `type` default to `application/json` for JSON parser + * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser + * Provide static `require` analysis + * Use the `http-errors` module to generate errors + * deps: bytes@2.1.0 + - Slight optimizations + * deps: iconv-lite@0.4.10 + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + - Leading BOM is now removed when decoding + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: qs@3.1.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + - Parsed object now has `null` prototype + * deps: raw-body@~2.1.1 + - Use `unpipe` module for unpiping requests + - deps: iconv-lite@0.4.10 + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: remove argument reassignment + * perf: remove delete call + +1.12.4 / 2015-05-10 +=================== + + * deps: debug@~2.2.0 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: on-finished@~2.2.1 + * deps: raw-body@~2.0.1 + - Fix a false-positive when unpiping in Node.js 0.8 + - deps: bytes@2.0.1 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +1.12.3 / 2015-04-15 +=================== + + * Slight efficiency improvement when not debugging + * deps: depd@~1.0.1 + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + * deps: raw-body@1.3.4 + - Fix hanging callback if request aborts during read + - deps: iconv-lite@0.4.8 + +1.12.2 / 2015-03-16 +=================== + + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + +1.12.1 / 2015-03-15 +=================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +1.12.0 / 2015-02-13 +=================== + + * add `debug` messages + * accept a function for the `type` option + * use `content-type` to parse `Content-Type` headers + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + * deps: raw-body@1.3.3 + - deps: iconv-lite@0.4.7 + * 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 + +1.11.0 / 2015-01-30 +=================== + + * make internal `extended: true` depth limit infinity + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +1.10.2 / 2015-01-20 +=================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + * deps: raw-body@1.3.2 + - deps: iconv-lite@0.4.6 + +1.10.1 / 2015-01-01 +=================== + + * deps: on-finished@~2.2.0 + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +1.10.0 / 2014-12-02 +=================== + + * make internal `extended: true` array limit dynamic + +1.9.3 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + * deps: raw-body@1.3.1 + - deps: iconv-lite@0.4.5 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +1.9.2 / 2014-10-27 +================== + + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +1.9.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +1.9.0 / 2014-09-24 +================== + + * include the charset in "unsupported charset" error message + * include the encoding in "unsupported content encoding" error message + * deps: depd@~1.0.0 + +1.8.4 / 2014-09-23 +================== + + * fix content encoding to be case-insensitive + +1.8.3 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +1.8.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + +1.8.1 / 2014-09-07 +================== + + * deps: media-typer@0.3.0 + * deps: type-is@~1.5.1 + +1.8.0 / 2014-09-05 +================== + + * make empty-body-handling consistent between chunked requests + - empty `json` produces `{}` + - empty `raw` produces `new Buffer(0)` + - empty `text` produces `''` + - empty `urlencoded` produces `{}` + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: type-is@~1.5.0 + - fix `hasbody` to be true for `content-length: 0` + +1.7.0 / 2014-09-01 +================== + + * add `parameterLimit` option to `urlencoded` parser + * change `urlencoded` extended array limit to 100 + * respond with 413 when over `parameterLimit` in `urlencoded` + +1.6.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +1.6.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/5-3/node_modules/body-parser/LICENSE b/5-3/node_modules/body-parser/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/5-3/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +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: + +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/5-3/node_modules/body-parser/README.md b/5-3/node_modules/body-parser/README.md new file mode 100644 index 0000000..c819bb1 --- /dev/null +++ b/5-3/node_modules/body-parser/README.md @@ -0,0 +1,403 @@ +# body-parser + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Node.js body parsing middleware. + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.org/package/busboy#readme) and + [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.org/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.org/package/formidable#readme) + * [multer](https://www.npmjs.org/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + +```js +var bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body, or an +empty object (`{}`) if there was no body to parse (or an error was returned). + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json(options) + +Returns middleware that only parses `json`. This parser accepts any Unicode +encoding of the body and supports automatic inflation of `gzip` and `deflate` +encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an option `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `json`), a mime type (like +`application/json`), or a mime type with a wildcard (like `*/*` or `*/json`). +If a function, the `type` option is called as `fn(req)` and the request is +parsed if it returns a truthy value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw(options) + +Returns middleware that parses all bodies as a `Buffer`. This parser +supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an option `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text(options) + +Returns middleware that parses all bodies as a string. This parser supports +automatic inflation of `gzip` and `deflate` encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an option `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `txt`), a mime type (like +`text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`). +If a function, the `type` option is called as `fn(req)` and the request is +parsed if it returns a truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded(options) + +Returns middleware that only parses `urlencoded` bodies. This parser accepts +only UTF-8 encoding of the body and supports automatic inflation of `gzip` +and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an option `options` object that may contain +any of the following keys: + +##### extended + +The `extended` option allows to choose between parsing the URL-encoded data +with the `querystring` library (when `false`) or the `qs` library (when +`true`). The "extended" syntax allows for rich objects and arrays to be +encoded into the URL-encoded format, allowing for a JSON-like experience +with URL-encoded. For more information, please +[see the qs library](https://www.npmjs.org/package/qs#readme). + +Defaults to `true`, but using the default has been deprecated. Please +research into the difference between `qs` and `querystring` and choose the +appropriate setting. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +## Errors + +The middlewares provided by this module create errors depending on the error +condition during parsing. The errors will typically have a `status` property +that contains the suggested HTTP response code. + +The following are the common errors emitted, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`. + +## Examples + +### express/connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: false })) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(JSON.stringify(req.body, null, 2)) +}) +``` + +### express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommend way to use body-parser with +express. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// create application/json parser +var jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +var urlencodedParser = bodyParser.urlencoded({ extended: false }) + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + if (!req.body) return res.sendStatus(400) + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + if (!req.body) return res.sendStatus(400) + // create user in req.body +}) +``` + +### change content-type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/body-parser.svg +[npm-url]: https://npmjs.org/package/body-parser +[travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg +[travis-url]: https://travis-ci.org/expressjs/body-parser +[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg +[downloads-url]: https://npmjs.org/package/body-parser +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/5-3/node_modules/body-parser/index.js b/5-3/node_modules/body-parser/index.js new file mode 100644 index 0000000..f430387 --- /dev/null +++ b/5-3/node_modules/body-parser/index.js @@ -0,0 +1,157 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('body-parser') + +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + +/** + * Module exports. + * @type {Parsers} + */ + +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') + +/** + * JSON parser. + * @public + */ + +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: createParserGetter('json') +}) + +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: createParserGetter('raw') +}) + +/** + * Text parser. + * @public + */ + +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: createParserGetter('text') +}) + +/** + * URL-encoded parser. + * @public + */ + +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ + +function bodyParser(options){ + var opts = {} + + // exclude type option + if (options) { + for (var prop in options) { + if ('type' !== prop) { + opts[prop] = options[prop] + } + } + } + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser(req, res, next) { + _json(req, res, function(err){ + if (err) return next(err); + _urlencoded(req, res, next); + }); + } +} + +/** + * Create a getter for loading a parser. + * @private + */ + +function createParserGetter(name) { + return function get() { + return loadParser(name) + } +} + +/** + * Load a parser module. + * @private + */ + +function loadParser(parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser + } + + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = require('./lib/types/json') + break + case 'raw': + parser = require('./lib/types/raw') + break + case 'text': + parser = require('./lib/types/text') + break + case 'urlencoded': + parser = require('./lib/types/urlencoded') + break + } + + // store to prevent invoking require() + return parsers[parserName] = parser +} diff --git a/5-3/node_modules/body-parser/lib/read.js b/5-3/node_modules/body-parser/lib/read.js new file mode 100644 index 0000000..95af8a7 --- /dev/null +++ b/5-3/node_modules/body-parser/lib/read.js @@ -0,0 +1,188 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var zlib = require('zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} [options] + * @api private + */ + +function read(req, res, next, parse, debug, options) { + var length + var opts = options || {} + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding || 'utf-8' + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase() + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (err, body) { + if (err) { + // default to 400 + setErrorStatus(err, 400) + + // echo back charset + if (err.type === 'encoding.unsupported') { + err = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase() + }) + } + + // read off entire request + stream.resume() + onFinished(req, function onfinished() { + next(err) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + // default to 403 + setErrorStatus(err, 403) + next(err) + return + } + } + + // parse + var str + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + err.body = str === undefined + ? body + : str + + // default to 400 + setErrorStatus(err, 400) + + next(err) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream(req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported') + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding + }) + } + + return stream +} + +/** + * Set a status on an error object, if ones does not exist + * @private + */ + +function setErrorStatus(error, status) { + if (!error.status && !error.statusCode) { + error.status = status + error.statusCode = status + } +} diff --git a/5-3/node_modules/body-parser/lib/types/json.js b/5-3/node_modules/body-parser/lib/types/json.js new file mode 100644 index 0000000..1a70e37 --- /dev/null +++ b/5-3/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,170 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:json') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ + +var firstcharRegExp = /^[\x20\x09\x0a\x0d]*(.)/ + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function json(options) { + var opts = options || {} + + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse(body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw new SyntaxError('Unexpected token ' + first) + } + } + + debug('parse json') + return JSON.parse(body, reviver) + } + + return function jsonParser(req, res, next) { + if (req._body) { + return debug('body already parsed'), next() + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + return debug('skip empty body'), next() + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + return debug('skip parsing'), next() + } + + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.substr(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @api public + */ + + +function firstchar(str) { + var match = firstcharRegExp.exec(str) + return match ? match[1] : '' +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset(req) { + try { + return contentType.parse(req).parameters.charset.toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker(type) { + return function checkType(req) { + return Boolean(typeis(req, type)) + } +} diff --git a/5-3/node_modules/body-parser/lib/types/raw.js b/5-3/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 0000000..519146c --- /dev/null +++ b/5-3/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,95 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var debug = require('debug')('body-parser:raw') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw(options) { + var opts = options || {}; + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse(buf) { + return buf + } + + return function rawParser(req, res, next) { + if (req._body) { + return debug('body already parsed'), next() + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + return debug('skip empty body'), next() + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + return debug('skip parsing'), next() + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker(type) { + return function checkType(req) { + return Boolean(typeis(req, type)) + } +} diff --git a/5-3/node_modules/body-parser/lib/types/text.js b/5-3/node_modules/body-parser/lib/types/text.js new file mode 100644 index 0000000..caf7968 --- /dev/null +++ b/5-3/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,115 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var debug = require('debug')('body-parser:text') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text(options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse(buf) { + return buf + } + + return function textParser(req, res, next) { + if (req._body) { + return debug('body already parsed'), next() + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + return debug('skip empty body'), next() + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + return debug('skip parsing'), next() + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset(req) { + try { + return contentType.parse(req).parameters.charset.toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker(type) { + return function checkType(req) { + return Boolean(typeis(req, type)) + } +} diff --git a/5-3/node_modules/body-parser/lib/types/urlencoded.js b/5-3/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 0000000..76f5aa4 --- /dev/null +++ b/5-3/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,273 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var deprecate = require('depd')('body-parser') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function urlencoded(options) { + var opts = options || {} + + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse(body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser(req, res, next) { + if (req._body) { + return debug('body already parsed'), next() + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + return debug('skip empty body'), next() + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + return debug('skip parsing'), next() + } + + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset + })) + return + } + + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the extended query parser. + * + * @param {object} options + */ + +function extendedparser(options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse(body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters') + } + + var arrayLimit = Math.max(100, paramCount) + + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset(req) { + try { + return contentType.parse(req).parameters.charset.toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ + +function parameterCount(body, limit) { + var count = 0 + var index = 0 + + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } + } + + return count +} + +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ + +function parser(name) { + var mod = parsers[name] + + if (mod !== undefined) { + return mod.parse + } + + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = require('qs') + break + case 'querystring': + mod = require('querystring') + break + } + + // store to prevent invoking require() + parsers[name] = mod + + return mod.parse +} + +/** + * Get the simple query parser. + * + * @param {object} options + */ + +function simpleparser(options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse(body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters') + } + + debug('parse urlencoding') + return parse(body, undefined, undefined, {maxKeys: parameterLimit}) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker(type) { + return function checkType(req) { + return Boolean(typeis(req, type)) + } +} diff --git a/5-3/node_modules/body-parser/node_modules/bytes/History.md b/5-3/node_modules/body-parser/node_modules/bytes/History.md new file mode 100644 index 0000000..5bd5136 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/bytes/History.md @@ -0,0 +1,57 @@ +2.2.0 / 2015-11-13 +================== + + * add option "decimalPlaces" + * add option "fixedDecimals" + +2.1.0 / 2015-05-21 +================== + + * add `.format` export + * add `.parse` export + +2.0.2 / 2015-05-20 +================== + + * remove map recreation + * remove unnecessary object construction + +2.0.1 / 2015-05-07 +================== + + * fix browserify require + * remove node.extend dependency + +2.0.0 / 2015-04-12 +================== + + * add option "case" + * add option "thousandsSeparator" + * return "null" on invalid parse input + * support proper round-trip: bytes(bytes(num)) === num + * units no longer case sensitive when parsing + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/5-3/node_modules/body-parser/node_modules/bytes/LICENSE b/5-3/node_modules/body-parser/node_modules/bytes/LICENSE new file mode 100644 index 0000000..63e95a9 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/bytes/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015 Jed Watson + +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/5-3/node_modules/body-parser/node_modules/bytes/Readme.md b/5-3/node_modules/body-parser/node_modules/bytes/Readme.md new file mode 100644 index 0000000..fb4b3ea --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/bytes/Readme.md @@ -0,0 +1,99 @@ +# Bytes utility + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] + +Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. + +## Usage + +```js +var bytes = require('bytes'); +``` + +#### bytes.format(number value, [options]): string|null + +Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is + rounded. + +**Arguments** + +| Name | Type | Description | +|---------|--------|--------------------| +| value | `number` | Value in bytes | +| options | `Object` | Conversion options | + +**Options** + +| Property | Type | Description | +|-------------------|--------|-----------------------------------------------------------------------------------------| +| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | +| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | +| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `.`... Default value to `' '`. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `string`|`null` | Return null upon error. String value otherwise. | + +**Example** + +```js +bytes(1024); +// output: '1kB' + +bytes(1000); +// output: '1000B' + +bytes(1000, {thousandsSeparator: ' '}); +// output: '1 000B' + +bytes(1024 * 1.7, {decimalPlaces: 0}); +// output: '2kB' +``` + +#### bytes.parse(string value): number|null + +Parse the string value into an integer in bytes. If no unit is given, it is assumed the value is in bytes. + +**Arguments** + +| Name | Type | Description | +|---------------|--------|--------------------| +| value | `string` | String to parse. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | + +**Example** + +```js +bytes('1kB'); +// output: 1024 + +bytes('1024'); +// output: 1024 +``` + +## Installation + +```bash +npm install bytes --save +component install visionmedia/bytes.js +``` + +## License + +[![npm](https://img.shields.io/npm/l/express.svg)](https://github.com/visionmedia/bytes.js/blob/master/LICENSE) + +[downloads-image]: https://img.shields.io/npm/dm/bytes.svg +[downloads-url]: https://npmjs.org/package/bytes +[npm-image]: https://img.shields.io/npm/v/bytes.svg +[npm-url]: https://npmjs.org/package/bytes +[travis-image]: https://img.shields.io/travis/visionmedia/bytes.js/master.svg +[travis-url]: https://travis-ci.org/visionmedia/bytes.js diff --git a/5-3/node_modules/body-parser/node_modules/bytes/index.js b/5-3/node_modules/body-parser/node_modules/bytes/index.js new file mode 100644 index 0000000..02d5bee --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/bytes/index.js @@ -0,0 +1,141 @@ +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: ((1 << 30) * 1024) +}; + +/** + *Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @public + */ + +function format(value, options) { + if (typeof value !== 'number') { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = 'B'; + + if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'kB'; + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(/(?:\.0*|(\.[^0]+)0+)$/, '$1'); + } + + if (thousandsSeparator) { + str = str.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator); + } + + return str + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = val.match(/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + return map[unit] * floatValue; +} diff --git a/5-3/node_modules/body-parser/node_modules/bytes/package.json b/5-3/node_modules/body-parser/node_modules/bytes/package.json new file mode 100644 index 0000000..bc37c97 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/bytes/package.json @@ -0,0 +1,81 @@ +{ + "name": "bytes", + "description": "Utility to parse a string bytes to bytes and vice-versa", + "version": "2.2.0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "contributors": [ + { + "name": "Jed Watson", + "email": "jed.watson@me.com" + }, + { + "name": "Théo FIDRY", + "email": "theo.fidry@gmail.com" + } + ], + "license": "MIT", + "keywords": [ + "byte", + "bytes", + "utility", + "parse", + "parser", + "convert", + "converter" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/visionmedia/bytes.js.git" + }, + "component": { + "scripts": { + "bytes/index.js": "index.js" + } + }, + "devDependencies": { + "mocha": "1.21.5" + }, + "files": [ + "History.md", + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "test": "mocha --check-leaks --reporter spec" + }, + "gitHead": "509a01a5472b9163ae5a7db41e2d6bd986fdf595", + "bugs": { + "url": "https://github.com/visionmedia/bytes.js/issues" + }, + "homepage": "https://github.com/visionmedia/bytes.js", + "_id": "bytes@2.2.0", + "_shasum": "fd35464a403f6f9117c2de3609ecff9cae000588", + "_from": "bytes@2.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "fd35464a403f6f9117c2de3609ecff9cae000588", + "tarball": "http://registry.npmjs.org/bytes/-/bytes-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/bytes/-/bytes-2.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/content-type/HISTORY.md b/5-3/node_modules/body-parser/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..8a623a2 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/content-type/HISTORY.md @@ -0,0 +1,9 @@ +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/5-3/node_modules/body-parser/node_modules/content-type/LICENSE b/5-3/node_modules/body-parser/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/5-3/node_modules/body-parser/node_modules/content-type/README.md b/5-3/node_modules/body-parser/node_modules/content-type/README.md new file mode 100644 index 0000000..3ed6741 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/content-type/README.md @@ -0,0 +1,92 @@ +# content-type + +[![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] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a content 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 media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({type: 'image/svg+xml'}) +``` + +Format an object into a content type string. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-type.svg +[npm-url]: https://npmjs.org/package/content-type +[node-version-image]: https://img.shields.io/node/v/content-type.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg +[travis-url]: https://travis-ci.org/jshttp/content-type +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-type +[downloads-image]: https://img.shields.io/npm/dm/content-type.svg +[downloads-url]: https://npmjs.org/package/content-type diff --git a/5-3/node_modules/body-parser/node_modules/content-type/index.js b/5-3/node_modules/body-parser/node_modules/content-type/index.js new file mode 100644 index 0000000..6a2ea9f --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/content-type/index.js @@ -0,0 +1,214 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) */g +var textRegExp = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var qescRegExp = /\\([\u000b\u0020-\u00ff])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var quoteRegExp = /([\\"])/g + +/** + * RegExp to match type in RFC 6838 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+\/[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !typeRegExp.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // 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} + * @public + */ + +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string === 'object') { + // support req/res-like objects as argument + string = getcontenttype(string) + + if (typeof string !== 'string') { + throw new TypeError('content-type header is missing from object'); + } + } + + 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).trim() + : string.trim() + + if (!typeRegExp.test(type)) { + throw new TypeError('invalid media type') + } + + var key + var match + var obj = new ContentType(type.toLowerCase()) + 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') + } + + obj.parameters[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @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} + * @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') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType(type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/5-3/node_modules/body-parser/node_modules/content-type/package.json b/5-3/node_modules/body-parser/node_modules/content-type/package.json new file mode 100644 index 0000000..e23403c --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/content-type/package.json @@ -0,0 +1,65 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-type.git" + }, + "devDependencies": { + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail 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": "3aa58f9c5a358a3634b8601602177888b4a477d8", + "bugs": { + "url": "https://github.com/jshttp/content-type/issues" + }, + "homepage": "https://github.com/jshttp/content-type", + "_id": "content-type@1.0.1", + "_shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "_from": "content-type@>=1.0.1 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "tarball": "http://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/debug/.jshintrc b/5-3/node_modules/body-parser/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/5-3/node_modules/body-parser/node_modules/debug/.npmignore b/5-3/node_modules/body-parser/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/5-3/node_modules/body-parser/node_modules/debug/History.md b/5-3/node_modules/body-parser/node_modules/debug/History.md new file mode 100644 index 0000000..854c971 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/History.md @@ -0,0 +1,195 @@ + +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 +================== + + * 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/5-3/node_modules/body-parser/node_modules/debug/Makefile b/5-3/node_modules/body-parser/node_modules/debug/Makefile new file mode 100644 index 0000000..5cf4a59 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/Makefile @@ -0,0 +1,36 @@ + +# 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 dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +distclean: clean + @rm -rf node_modules + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean distclean diff --git a/5-3/node_modules/body-parser/node_modules/debug/Readme.md b/5-3/node_modules/body-parser/node_modules/debug/Readme.md new file mode 100644 index 0000000..b4f45e3 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/Readme.md @@ -0,0 +1,188 @@ +# 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'); +``` + +### 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 + - 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/5-3/node_modules/body-parser/node_modules/debug/bower.json b/5-3/node_modules/body-parser/node_modules/debug/bower.json new file mode 100644 index 0000000..6af573f --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/bower.json @@ -0,0 +1,28 @@ +{ + "name": "visionmedia-debug", + "main": "dist/debug.js", + "version": "2.2.0", + "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/5-3/node_modules/body-parser/node_modules/debug/browser.js b/5-3/node_modules/body-parser/node_modules/debug/browser.js new file mode 100644 index 0000000..7c76452 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/browser.js @@ -0,0 +1,168 @@ + +/** + * 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; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : 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) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.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/5-3/node_modules/body-parser/node_modules/debug/component.json b/5-3/node_modules/body-parser/node_modules/debug/component.json new file mode 100644 index 0000000..ca10637 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.2.0", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/5-3/node_modules/body-parser/node_modules/debug/debug.js b/5-3/node_modules/body-parser/node_modules/debug/debug.js new file mode 100644 index 0000000..7571a86 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * 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/5-3/node_modules/body-parser/node_modules/debug/node.js b/5-3/node_modules/body-parser/node_modules/debug/node.js new file mode 100644 index 0000000..1d392a8 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/node.js @@ -0,0 +1,209 @@ + +/** + * 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/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/.npmignore b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/History.md b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/LICENSE b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/README.md b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/index.js b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/package.json b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/debug/package.json b/5-3/node_modules/body-parser/node_modules/debug/package.json new file mode 100644 index 0000000..24bb9c9 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/debug/package.json @@ -0,0 +1,73 @@ +{ + "name": "debug", + "version": "2.2.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "license": "MIT", + "dependencies": { + "ms": "0.7.1" + }, + "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": "b38458422b5aa8aa6d286b10dfe427e8a67e2b35", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@2.2.0", + "scripts": {}, + "_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "_from": "debug@>=2.2.0 <2.3.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "tarball": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/depd/History.md b/5-3/node_modules/body-parser/node_modules/depd/History.md new file mode 100644 index 0000000..ace1171 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/depd/History.md @@ -0,0 +1,84 @@ +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/5-3/node_modules/body-parser/node_modules/depd/LICENSE b/5-3/node_modules/body-parser/node_modules/depd/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-3/node_modules/body-parser/node_modules/depd/Readme.md b/5-3/node_modules/body-parser/node_modules/depd/Readme.md new file mode 100644 index 0000000..09bb979 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/depd/Readme.md @@ -0,0 +1,281 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction() { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: http://nodejs.org/download/ +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/5-3/node_modules/body-parser/node_modules/depd/index.js b/5-3/node_modules/body-parser/node_modules/depd/index.js new file mode 100644 index 0000000..fddcae8 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/depd/index.js @@ -0,0 +1,521 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace(str, namespace) { + var val = str.split(/[ ,]+/) + + namespace = String(namespace).toLowerCase() + + for (var i = 0 ; i < val.length; i++) { + if (!(str = val[i])) continue; + + // namespace contained + if (str === '*' || str.toLowerCase() === namespace) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor(obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter() { return value } + + if (descriptor.writable) { + descriptor.set = function setter(val) { return value = val } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString(arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString(stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate(message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log(message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + callSite = callSiteLocation(stack[1]) + callSite.name = site.name + file = callSite[0] + } else { + // get call site + i = 2 + site = callSiteLocation(stack[i]) + callSite = site + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? site.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + if (!message) { + message = callSite === site || !callSite.name + ? defaultMessage(site) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, message, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var msg = format.call(this, message, caller, stack.slice(i)) + process.stderr.write(msg + '\n', 'utf8') + + return +} + +/** + * Get call site location as array. + */ + +function callSiteLocation(callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage(site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain(msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor(msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' // bold cyan + + ' \x1b[33;1mdeprecated\x1b[22;39m' // bold yellow + + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation(callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace(obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter() { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter() { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError(namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return stackString = createStackString.call(this, stack) + }, + set: function setter(val) { + stackString = val + } + }) + + return error +} diff --git a/5-3/node_modules/body-parser/node_modules/depd/lib/browser/index.js b/5-3/node_modules/body-parser/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..f464e05 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/depd/lib/browser/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate(message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + return +} diff --git a/5-3/node_modules/body-parser/node_modules/depd/lib/compat/buffer-concat.js b/5-3/node_modules/body-parser/node_modules/depd/lib/compat/buffer-concat.js new file mode 100644 index 0000000..4b73381 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/depd/lib/compat/buffer-concat.js @@ -0,0 +1,35 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = bufferConcat + +/** + * Concatenate an array of Buffers. + */ + +function bufferConcat(bufs) { + var length = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + length += bufs[i].length + } + + var buf = new Buffer(length) + var pos = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + bufs[i].copy(buf, pos) + pos += bufs[i].length + } + + return buf +} diff --git a/5-3/node_modules/body-parser/node_modules/depd/lib/compat/callsite-tostring.js b/5-3/node_modules/body-parser/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 0000000..9ecef34 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation(callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString(callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName(obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/5-3/node_modules/body-parser/node_modules/depd/lib/compat/event-listener-count.js b/5-3/node_modules/body-parser/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 0000000..a05fceb --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount(emitter, type) { + return emitter.listeners(type).length +} diff --git a/5-3/node_modules/body-parser/node_modules/depd/lib/compat/index.js b/5-3/node_modules/body-parser/node_modules/depd/lib/compat/index.js new file mode 100644 index 0000000..aa3c1de --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/depd/lib/compat/index.js @@ -0,0 +1,84 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('buffer') +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'bufferConcat', function bufferConcat() { + return Buffer.concat || require('./buffer-concat') +}) + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace(obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount() { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty(obj, prop, getter) { + function get() { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString(obj) { + return obj.toString() +} diff --git a/5-3/node_modules/body-parser/node_modules/depd/package.json b/5-3/node_modules/body-parser/node_modules/depd/package.json new file mode 100644 index 0000000..9da460a --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/depd/package.json @@ -0,0 +1,67 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "1.1.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/dougwilson/nodejs-depd.git" + }, + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail test/", + "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": "78c659de20283e3a6bee92bda455e6daff01686a", + "bugs": { + "url": "https://github.com/dougwilson/nodejs-depd/issues" + }, + "homepage": "https://github.com/dougwilson/nodejs-depd", + "_id": "depd@1.1.0", + "_shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "_from": "depd@>=1.1.0 <1.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "tarball": "http://registry.npmjs.org/depd/-/depd-1.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/depd/-/depd-1.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/HISTORY.md b/5-3/node_modules/body-parser/node_modules/http-errors/HISTORY.md new file mode 100644 index 0000000..4c7087d --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/HISTORY.md @@ -0,0 +1,76 @@ +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/LICENSE b/5-3/node_modules/body-parser/node_modules/http-errors/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/README.md b/5-3/node_modules/body-parser/node_modules/http-errors/README.md new file mode 100644 index 0000000..520271e --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/README.md @@ -0,0 +1,63 @@ +# http-errors + +[![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] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Example + +```js +var createError = require('http-errors'); + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')); + next(); +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +### Error Properties + +- `message` +- `status` and `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + +```js +var err = createError(404, 'This video does not exist!'); +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### new createError\[code || name\](\[msg]\)) + +```js +var err = new createError.NotFound(); +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/http-errors.svg?style=flat +[npm-url]: https://npmjs.org/package/http-errors +[node-version-image]: https://img.shields.io/node/v/http-errors.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/http-errors.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/http-errors +[coveralls-image]: https://img.shields.io/coveralls/jshttp/http-errors.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors +[downloads-image]: https://img.shields.io/npm/dm/http-errors.svg?style=flat +[downloads-url]: https://npmjs.org/package/http-errors diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/index.js b/5-3/node_modules/body-parser/node_modules/http-errors/index.js new file mode 100644 index 0000000..d84b114 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/index.js @@ -0,0 +1,120 @@ + +var statuses = require('statuses'); +var inherits = require('inherits'); + +function toIdentifier(str) { + return str.split(' ').map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }).join('').replace(/[^ _0-9a-z]/gi, '') +} + +exports = module.exports = function httpError() { + // so much arity going on ~_~ + var err; + var msg; + var status = 500; + var props = {}; + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (arg instanceof Error) { + err = arg; + status = err.status || err.statusCode || status; + continue; + } + switch (typeof arg) { + case 'string': + msg = arg; + break; + case 'number': + status = arg; + break; + case 'object': + props = arg; + break; + } + } + + if (typeof status !== 'number' || !statuses[status]) { + status = 500 + } + + // constructor + var HttpError = exports[status] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, httpError) + } + + if (!HttpError || !(err instanceof HttpError)) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err; +}; + +// create generic error objects +var codes = statuses.codes.filter(function (num) { + return num >= 400; +}); + +codes.forEach(function (code) { + var name = toIdentifier(statuses[code]) + var className = name.match(/Error$/) ? name : name + 'Error' + + if (code >= 500) { + var ServerError = function ServerError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ServerError) + self.__proto__ = ServerError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ServerError, Error); + ServerError.prototype.status = + ServerError.prototype.statusCode = code; + ServerError.prototype.expose = false; + exports[code] = + exports[name] = ServerError + return; + } + + var ClientError = function ClientError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ClientError) + self.__proto__ = ClientError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ClientError, Error); + ClientError.prototype.status = + ClientError.prototype.statusCode = code; + ClientError.prototype.expose = true; + exports[code] = + exports[name] = ClientError + return; +}); + +// backwards-compatibility +exports["I'mateapot"] = exports.ImATeapot diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/LICENSE b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +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/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/README.md b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +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/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits.js b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits_browser.js b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +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/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/package.json b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/package.json new file mode 100644 index 0000000..93d5078 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/package.json @@ -0,0 +1,50 @@ +{ + "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.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "_id": "inherits@2.0.1", + "dist": { + "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/inherits#readme" +} diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/test.js b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +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/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/LICENSE b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/README.md b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/README.md new file mode 100644 index 0000000..f6ae24c --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/README.md @@ -0,0 +1,114 @@ +# Statuses + +[![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] + +HTTP status utility for node. + +## API + +```js +var status = require('statuses'); +``` + +### var code = status(Integer || String) + +If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown. + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status('forbidden') // => 403 +status('Forbidden') // => 403 +status(306) // throws, as it's not supported by node.js +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### var msg = status[code] + +Map of `code` to `status message`. `undefined` for invalid `code`s. + +```js +status[404] // => 'Not Found' +``` + +### var code = status[msg] + +Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s. + +```js +status['not found'] // => 404 +status['Not Found'] // => 404 +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +### statuses/codes.json + +```js +var codes = require('statuses/codes.json'); +``` + +This is a JSON file of the status codes +taken from `require('http').STATUS_CODES`. +This is saved so that codes are consistent even in older node.js versions. +For example, `308` will be added in v0.12. + +## Adding Status Codes + +The status codes are primarily sourced from http://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv. +Additionally, custom codes are added from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes. +These are added manually in the `lib/*.json` files. +If you would like to add a status code, add it to the appropriate JSON file. + +To rebuild `codes.json`, run the following: + +```bash +# update src/iana.json +npm run update +# build codes.json +npm run build +``` + +[npm-image]: https://img.shields.io/npm/v/statuses.svg?style=flat +[npm-url]: https://npmjs.org/package/statuses +[node-version-image]: http://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/statuses.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/statuses +[coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[downloads-image]: http://img.shields.io/npm/dm/statuses.svg?style=flat +[downloads-url]: https://npmjs.org/package/statuses diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/codes.json b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/codes.json new file mode 100644 index 0000000..4c45a88 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/codes.json @@ -0,0 +1,64 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "(Unused)", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} \ No newline at end of file diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/index.js b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/index.js new file mode 100644 index 0000000..b06182d --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/index.js @@ -0,0 +1,60 @@ + +var codes = require('./codes.json'); + +module.exports = status; + +// [Integer...] +status.codes = Object.keys(codes).map(function (code) { + code = ~~code; + var msg = codes[code]; + status[code] = msg; + status[msg] = status[msg.toLowerCase()] = code; + return code; +}); + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true, +}; + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true, +}; + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true, +}; + +function status(code) { + if (typeof code === 'number') { + if (!status[code]) throw new Error('invalid status code: ' + code); + return code; + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string'); + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n); + return n; + } + + n = status[code.toLowerCase()]; + if (!n) throw new Error('invalid status message: "' + code + '"'); + return n; +} diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/package.json b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/package.json new file mode 100644 index 0000000..748e6ca --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/node_modules/statuses/package.json @@ -0,0 +1,84 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "1.2.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/statuses.git" + }, + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "0.0.6", + "istanbul": "0", + "mocha": "1", + "stream-to-array": "2" + }, + "scripts": { + "build": "node scripts/build.js", + "update": "node scripts/update.js", + "test": "mocha --reporter spec --bail --check-leaks", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks" + }, + "gitHead": "49e6ac7ae4c63ee8186f56cb52112a7eeda28ed7", + "bugs": { + "url": "https://github.com/jshttp/statuses/issues" + }, + "homepage": "https://github.com/jshttp/statuses", + "_id": "statuses@1.2.1", + "_shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "_from": "statuses@>=1.0.0 <2.0.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "tarball": "http://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/http-errors/package.json b/5-3/node_modules/body-parser/node_modules/http-errors/package.json new file mode 100644 index 0000000..41f845d --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/http-errors/package.json @@ -0,0 +1,85 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "1.3.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Alan Plum", + "email": "me@pluma.io" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/http-errors.git" + }, + "dependencies": { + "inherits": "~2.0.1", + "statuses": "1" + }, + "devDependencies": { + "istanbul": "0", + "mocha": "1" + }, + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ], + "gitHead": "89a8502b40d5dd42da2908f265275e2eeb8d0699", + "bugs": { + "url": "https://github.com/jshttp/http-errors/issues" + }, + "homepage": "https://github.com/jshttp/http-errors", + "_id": "http-errors@1.3.1", + "_shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "_from": "http-errors@>=1.3.1 <1.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "egeste", + "email": "npm@egeste.net" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "tarball": "http://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/.npmignore b/5-3/node_modules/body-parser/node_modules/iconv-lite/.npmignore new file mode 100644 index 0000000..5cd2673 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/.npmignore @@ -0,0 +1,6 @@ +*~ +*sublime-* +generation +test +wiki +coverage diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/.travis.yml b/5-3/node_modules/body-parser/node_modules/iconv-lite/.travis.yml new file mode 100644 index 0000000..f5343f1 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/.travis.yml @@ -0,0 +1,20 @@ + sudo: false + env: + - CXX=g++-4.8 + language: node_js + node_js: + - "0.8" + - "0.10" + - "0.11" + - "0.12" + - "iojs" + - "4.0" + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - gcc-4.8 + - g++-4.8 + before_install: + - "test $TRAVIS_NODE_VERSION != '0.8' || npm install -g npm@1.2.8000" diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/Changelog.md b/5-3/node_modules/body-parser/node_modules/iconv-lite/Changelog.md new file mode 100644 index 0000000..421b1e2 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/Changelog.md @@ -0,0 +1,93 @@ + +# 0.4.13 / 2015-10-01 + + * Fix silly mistake in deprecation notice. + + +# 0.4.12 / 2015-09-26 + + * Node v4 support: + * Added CESU-8 decoding (#106) + * Added deprecation notice for `extendNodeEncodings` + * Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol) + + +# 0.4.11 / 2015-07-03 + + * Added CESU-8 encoding. + + +# 0.4.10 / 2015-05-26 + + * Changed UTF-16 endianness heuristic to take into account any ASCII chars, not + just spaces. This should minimize the importance of "default" endianness. + + +# 0.4.9 / 2015-05-24 + + * Streamlined BOM handling: strip BOM by default, add BOM when encoding if + addBOM: true. Added docs to Readme. + * UTF16 now uses UTF16-LE by default. + * Fixed minor issue with big5 encoding. + * Added io.js testing on Travis; updated node-iconv version to test against. + Now we just skip testing SBCS encodings that node-iconv doesn't support. + * (internal refactoring) Updated codec interface to use classes. + * Use strict mode in all files. + + +# 0.4.8 / 2015-04-14 + + * added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94) + + +# 0.4.7 / 2015-02-05 + + * stop official support of Node.js v0.8. Should still work, but no guarantees. + reason: Packages needed for testing are hard to get on Travis CI. + * work in environment where Object.prototype is monkey patched with enumerable + props (#89). + + +# 0.4.6 / 2015-01-12 + + * fix rare aliases of single-byte encodings (thanks @mscdex) + * double the timeout for dbcs tests to make them less flaky on travis + + +# 0.4.5 / 2014-11-20 + + * fix windows-31j and x-sjis encoding support (@nleush) + * minor fix: undefined variable reference when internal error happens + + +# 0.4.4 / 2014-07-16 + + * added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3) + * fixed streaming base64 encoding + + +# 0.4.3 / 2014-06-14 + + * added encodings UTF-16BE and UTF-16 with BOM + + +# 0.4.2 / 2014-06-12 + + * don't throw exception if `extendNodeEncodings()` is called more than once + + +# 0.4.1 / 2014-06-11 + + * codepage 808 added + + +# 0.4.0 / 2014-06-10 + + * code is rewritten from scratch + * all widespread encodings are supported + * streaming interface added + * browserify compatibility added + * (optional) extend core primitive encodings to make usage even simpler + * moved from vows to mocha as the testing framework + + diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/LICENSE b/5-3/node_modules/body-parser/node_modules/iconv-lite/LICENSE new file mode 100644 index 0000000..d518d83 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Alexander Shtuchkin + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/README.md b/5-3/node_modules/body-parser/node_modules/iconv-lite/README.md new file mode 100644 index 0000000..160b7cf --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/README.md @@ -0,0 +1,157 @@ +## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) + + * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). + * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), + [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. + * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). + * Intuitive encode/decode API + * Streaming support for Node v0.10+ + * [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. + * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). + * License: MIT. + +[![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/) + +## Usage +### Basic API +```javascript +var iconv = require('iconv-lite'); + +// Convert from an encoded buffer to js string. +str = iconv.decode(new Buffer([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); + +// Convert from js string to an encoded buffer. +buf = iconv.encode("Sample input string", 'win1251'); + +// Check if encoding is supported +iconv.encodingExists("us-ascii") +``` + +### Streaming API (Node v0.10+) +```javascript + +// Decode stream (from binary stream to js strings) +http.createServer(function(req, res) { + var converterStream = iconv.decodeStream('win1251'); + req.pipe(converterStream); + + converterStream.on('data', function(str) { + console.log(str); // Do something with decoded strings, chunk-by-chunk. + }); +}); + +// Convert encoding streaming example +fs.createReadStream('file-in-win1251.txt') + .pipe(iconv.decodeStream('win1251')) + .pipe(iconv.encodeStream('ucs2')) + .pipe(fs.createWriteStream('file-in-ucs2.txt')); + +// Sugar: all encode/decode streams have .collect(cb) method to accumulate data. +http.createServer(function(req, res) { + req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { + assert(typeof body == 'string'); + console.log(body); // full request body string + }); +}); +``` + +### [Deprecated] Extend Node.js own encodings +> NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility). + +```javascript +// After this call all Node basic primitives will understand iconv-lite encodings. +iconv.extendNodeEncodings(); + +// Examples: +buf = new Buffer(str, 'win1251'); +buf.write(str, 'gbk'); +str = buf.toString('latin1'); +assert(Buffer.isEncoding('iso-8859-15')); +Buffer.byteLength(str, 'us-ascii'); + +http.createServer(function(req, res) { + req.setEncoding('big5'); + req.collect(function(err, body) { + console.log(body); + }); +}); + +fs.createReadStream("file.txt", "shift_jis"); + +// External modules are also supported (if they use Node primitives, which they probably do). +request = require('request'); +request({ + url: "http://github.com/", + encoding: "cp932" +}); + +// To remove extensions +iconv.undoExtendNodeEncodings(); +``` + +## Supported encodings + + * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. + * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. + * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, + IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. + Aliases like 'latin1', 'us-ascii' also supported. + * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2313, GBK, GB18030, Big5, Shift_JIS, EUC-JP. + +See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). + +Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! + +Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! + + +## Encoding/decoding speed + +Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). +Note: your results may vary, so please always check on your hardware. + + operation iconv@2.1.4 iconv-lite@0.4.7 + ---------------------------------------------------------- + encode('win1251') ~96 Mb/s ~320 Mb/s + decode('win1251') ~95 Mb/s ~246 Mb/s + +## BOM handling + + * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options + (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). + A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. + * Encoding: No BOM added, unless overridden by `addBOM: true` option. + +## UTF-16 Encodings + +This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be +smart about endianness in the following ways: + * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be + overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. + * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. + +## Other notes + +When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). +Untranslatable characters are set to � or ?. No transliteration is currently supported. +Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). + +## Testing + +```bash +$ git clone git@github.com:ashtuchkin/iconv-lite.git +$ cd iconv-lite +$ npm install +$ npm test + +$ # To view performance: +$ node test/performance.js + +$ # To view test coverage: +$ npm run coverage +$ open coverage/lcov-report/index.html +``` + +## Adoption +[![NPM](https://nodei.co/npm-dl/iconv-lite.png)](https://nodei.co/npm/iconv-lite/) +[![Codeship Status for ashtuchkin/iconv-lite](https://www.codeship.io/projects/81670840-fa72-0131-4520-4a01a6c01acc/status)](https://www.codeship.io/projects/29053) diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-codec.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-codec.js new file mode 100644 index 0000000..366809e --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-codec.js @@ -0,0 +1,554 @@ +"use strict" + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = DBCSCodec; + +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; + +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; + + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); + + // Load tables. + var mappingTable = codecOptions.table(); + + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); + + this.defaultCharUnicode = iconv.defaultCharUnicode; + + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); + + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + } + + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); + + + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} + +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); + + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} + + +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} + +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} + +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} + +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} + + + +// == Encoder ================================================================== + +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} + +DBCSEncoder.prototype.write = function(str) { + var newBuf = new Buffer(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } + + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } + + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; + + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; + + } else if (resCode == undefined) { // Current character is not part of the sequence. + + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. + + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } + + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } + + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } + + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} + +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. + + var newBuf = new Buffer(10), j = 0; + + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} + +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; + + +// == Decoder ================================================================== + +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = new Buffer(0); + + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} + +DBCSDecoder.prototype.write = function(buf) { + var newBuf = new Buffer(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; + + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } + + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} + +DBCSDecoder.prototype.end = function() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); + + // Parse remaining as usual. + this.prevBuf = new Buffer(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); + } + + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; + } + return l; +} + diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-data.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-data.js new file mode 100644 index 0000000..2bf7415 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/dbcs-data.js @@ -0,0 +1,170 @@ +"use strict" + +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. + +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + + + 'shiftjis': { + type: '_dbcs', + table: function() { return require('./tables/shiftjis.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', + + 'eucjp': { + type: '_dbcs', + table: function() { return require('./tables/eucjp.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, + + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + 'isoir58': 'gbk', + + // Microsoft's CP936 is a subset and approximation of GBK. + // TODO: Euro = 0x80 in cp936, but not in GBK (where it's valid but undefined) + 'windows936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json') }, + }, + + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + }, + 'xgbk': 'gbk', + + // GB18030 is an algorithmic extension of GBK. + 'gb18030': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + gb18030: function() { return require('./tables/gb18030-ranges.json') }, + }, + + 'chinese': 'gb18030', + + // TODO: Support GB18030 (~27000 chars + whole unicode mapping, cp54936) + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return require('./tables/cp949.json') }, + }, + + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', + + + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + + 'windows950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json') }, + }, + + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, + encodeSkipVals: [0xa2cc], + }, + + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', + +}; diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/index.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/index.js new file mode 100644 index 0000000..f7892fa --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/index.js @@ -0,0 +1,22 @@ +"use strict" + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + require("./internal"), + require("./utf16"), + require("./utf7"), + require("./sbcs-codec"), + require("./sbcs-data"), + require("./sbcs-data-generated"), + require("./dbcs-codec"), + require("./dbcs-data"), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; +} diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/internal.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/internal.js new file mode 100644 index 0000000..a8ae512 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/internal.js @@ -0,0 +1,187 @@ +"use strict" + +// Export Node.js internal encodings. + +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", + + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", + + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + + // Codec. + _internal: InternalCodec, +}; + +//------------------------------------------------------------------------------ + +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (new Buffer("eda080", 'hex').toString().length == 3) { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } +} + +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; + +//------------------------------------------------------------------------------ + +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = require('string_decoder').StringDecoder; + +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; + + +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); +} + +InternalDecoder.prototype = StringDecoder.prototype; + + +//------------------------------------------------------------------------------ +// Encoder is mostly trivial + +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} + +InternalEncoder.prototype.write = function(str) { + return new Buffer(str, this.enc); +} + +InternalEncoder.prototype.end = function() { +} + + +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. + +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} + +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + + return new Buffer(str, "base64"); +} + +InternalEncoderBase64.prototype.end = function() { + return new Buffer(this.prevStr, "base64"); +} + + +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8(options, codec) { +} + +InternalEncoderCesu8.prototype.write = function(str) { + var buf = new Buffer(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + } + return buf.slice(0, bufIdx); +} + +InternalEncoderCesu8.prototype.end = function() { +} + +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} + +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; + } + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; + } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; + } + } + } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; +} + +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; +} diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-codec.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-codec.js new file mode 100644 index 0000000..ca00171 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-codec.js @@ -0,0 +1,72 @@ +"use strict" + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; + } + + this.decodeBuf = new Buffer(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = new Buffer(65536); + encodeBuf.fill(iconv.defaultCharSingleByte.charCodeAt(0)); + + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + + this.encodeBuf = encodeBuf; +} + +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; + + +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} + +SBCSEncoder.prototype.write = function(str) { + var buf = new Buffer(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} + +SBCSEncoder.prototype.end = function() { +} + + +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} + +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = new Buffer(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; + } + return newBuf.toString('ucs2'); +} + +SBCSDecoder.prototype.end = function() { +} diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data-generated.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data-generated.js new file mode 100644 index 0000000..2308c91 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data-generated.js @@ -0,0 +1,451 @@ +"use strict" + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹ�ֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } +} \ No newline at end of file diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data.js new file mode 100644 index 0000000..2058a71 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/sbcs-data.js @@ -0,0 +1,169 @@ +"use strict" + +// Manually added data to be used by sbcs codec in addition to generated one. + +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", + + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", + + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", + + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + + "cp819": "iso88591", + "ibm819": "iso88591", + + "cyrillic": "iso88595", + + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", + + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", + + "hebrew": "iso88598", + "hebrew8": "iso88598", + + "turkish": "iso88599", + "turkish8": "iso88599", + + "thai": "iso885911", + "thai8": "iso885911", + + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", + + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", + + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", +}; + diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/big5-added.json b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/big5-added.json new file mode 100644 index 0000000..3c3d3c2 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/big5-added.json @@ -0,0 +1,122 @@ +[ +["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], +["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], +["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], +["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], +["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], +["8940","𪎩𡅅"], +["8943","攊"], +["8946","丽滝鵎釟"], +["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], +["89a1","琑糼緍楆竉刧"], +["89ab","醌碸酞肼"], +["89b0","贋胶𠧧"], +["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], +["89c1","溚舾甙"], +["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], +["8a40","𧶄唥"], +["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], +["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], +["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], +["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], +["8aac","䠋𠆩㿺塳𢶍"], +["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], +["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], +["8ac9","𪘁𠸉𢫏𢳉"], +["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], +["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], +["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], +["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], +["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], +["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], +["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], +["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], +["8ca1","𣏹椙橃𣱣泿"], +["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], +["8cc9","顨杫䉶圽"], +["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], +["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], +["8d40","𠮟"], +["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], +["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], +["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], +["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], +["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], +["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], +["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], +["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], +["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], +["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], +["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], +["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], +["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], +["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], +["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], +["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], +["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], +["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], +["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], +["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], +["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], +["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], +["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], +["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], +["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], +["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], +["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], +["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], +["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], +["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], +["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], +["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], +["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], +["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], +["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], +["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], +["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], +["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], +["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], +["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], +["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], +["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], +["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], +["9fae","酙隁酜"], +["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], +["9fc1","𤤙盖鮝个𠳔莾衂"], +["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], +["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], +["9fe7","毺蠘罸"], +["9feb","嘠𪙊蹷齓"], +["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], +["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], +["a055","𡠻𦸅"], +["a058","詾𢔛"], +["a05b","惽癧髗鵄鍮鮏蟵"], +["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], +["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], +["a0a1","嵗𨯂迚𨸹"], +["a0a6","僙𡵆礆匲阸𠼻䁥"], +["a0ae","矾"], +["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], +["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], +["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], +["a3c0","␀",31,"␡"], +["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], +["c740","す",58,"ァアィイ"], +["c7a1","ゥ",81,"А",5,"ЁЖ",4], +["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], +["c8a1","龰冈龱𧘇"], +["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], +["c8f5","ʃɐɛɔɵœøŋʊɪ"], +["f9fe","■"], +["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], +["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], +["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], +["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], +["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], +["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], +["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], +["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], +["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], +["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] +] diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp936.json b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp936.json new file mode 100644 index 0000000..49ddb9a --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp936.json @@ -0,0 +1,264 @@ +[ +["0","\u0000",127,"€"], +["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], +["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], +["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], +["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], +["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], +["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], +["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], +["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], +["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], +["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], +["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], +["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], +["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], +["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], +["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], +["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], +["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], +["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], +["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], +["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], +["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], +["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], +["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], +["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], +["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], +["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], +["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], +["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], +["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], +["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], +["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], +["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], +["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], +["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], +["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], +["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], +["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], +["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], +["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], +["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], +["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], +["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], +["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], +["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], +["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], +["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], +["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], +["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], +["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], +["9980","檧檨檪檭",114,"欥欦欨",6], +["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], +["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], +["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], +["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], +["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], +["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], +["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], +["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], +["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], +["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], +["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], +["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], +["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], +["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], +["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], +["a2a1","ⅰ",9], +["a2b1","⒈",19,"⑴",19,"①",9], +["a2e5","㈠",9], +["a2f1","Ⅰ",11], +["a3a1","!"#¥%",88," ̄"], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], +["a6ee","︻︼︷︸︱"], +["a6f4","︳︴"], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], +["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], +["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], +["a8bd","ńň"], +["a8c0","ɡ"], +["a8c5","ㄅ",36], +["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], +["a959","℡㈱"], +["a95c","‐"], +["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], +["a980","﹢",4,"﹨﹩﹪﹫"], +["a996","〇"], +["a9a4","─",75], +["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], +["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], +["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], +["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], +["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], +["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], +["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], +["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], +["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], +["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], +["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], +["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], +["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], +["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], +["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], +["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], +["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], +["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], +["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], +["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], +["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], +["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], +["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], +["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], +["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], +["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], +["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], +["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], +["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], +["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], +["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], +["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], +["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], +["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], +["bb40","籃",9,"籎",36,"籵",5,"籾",9], +["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], +["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], +["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], +["bd40","紷",54,"絯",7], +["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], +["be40","継",12,"綧",6,"綯",42], +["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], +["bf40","緻",62], +["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], +["c040","繞",35,"纃",23,"纜纝纞"], +["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], +["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], +["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], +["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], +["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], +["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], +["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], +["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], +["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], +["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], +["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], +["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], +["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], +["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], +["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], +["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], +["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], +["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], +["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], +["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], +["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], +["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], +["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], +["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], +["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], +["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], +["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], +["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], +["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], +["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], +["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], +["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], +["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], +["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], +["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], +["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], +["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], +["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], +["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], +["d440","訞",31,"訿",8,"詉",21], +["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], +["d540","誁",7,"誋",7,"誔",46], +["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], +["d640","諤",34,"謈",27], +["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], +["d740","譆",31,"譧",4,"譭",25], +["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], +["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], +["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], +["d940","貮",62], +["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], +["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], +["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], +["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], +["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], +["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], +["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], +["dd40","軥",62], +["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], +["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], +["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], +["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], +["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], +["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], +["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], +["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], +["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], +["e240","釦",62], +["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], +["e340","鉆",45,"鉵",16], +["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], +["e440","銨",5,"銯",24,"鋉",31], +["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], +["e540","錊",51,"錿",10], +["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], +["e640","鍬",34,"鎐",27], +["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], +["e740","鏎",7,"鏗",54], +["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], +["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], +["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], +["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], +["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], +["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], +["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], +["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], +["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], +["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], +["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], +["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], +["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], +["ee40","頏",62], +["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], +["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], +["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], +["f040","餈",4,"餎餏餑",28,"餯",26], +["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], +["f140","馌馎馚",10,"馦馧馩",47], +["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], +["f240","駺",62], +["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], +["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], +["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], +["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], +["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], +["f540","魼",62], +["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], +["f640","鯜",62], +["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], +["f740","鰼",62], +["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], +["f840","鳣",62], +["f880","鴢",32], +["f940","鵃",62], +["f980","鶂",32], +["fa40","鶣",62], +["fa80","鷢",32], +["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], +["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], +["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], +["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], +["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], +["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], +["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] +] diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp949.json b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp949.json new file mode 100644 index 0000000..2022a00 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp949.json @@ -0,0 +1,273 @@ +[ +["0","\u0000",127], +["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], +["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], +["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], +["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], +["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], +["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], +["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], +["8361","긝",18,"긲긳긵긶긹긻긼"], +["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], +["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], +["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], +["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], +["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], +["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], +["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], +["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], +["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], +["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], +["8741","놞",9,"놩",15], +["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], +["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], +["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], +["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], +["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], +["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], +["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], +["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], +["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], +["8a61","둧",4,"둭",18,"뒁뒂"], +["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], +["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], +["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], +["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], +["8c41","똀",15,"똒똓똕똖똗똙",4], +["8c61","똞",6,"똦",5,"똭",6,"똵",5], +["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], +["8d41","뛃",16,"뛕",8], +["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], +["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], +["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], +["8e61","럂",4,"럈럊",19], +["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], +["8f41","뢅",7,"뢎",17], +["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], +["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], +["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], +["9061","륾",5,"릆릈릋릌릏",15], +["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], +["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], +["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], +["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], +["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], +["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], +["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], +["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], +["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], +["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], +["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], +["9461","봞",5,"봥",6,"봭",12], +["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], +["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], +["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], +["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], +["9641","뺸",23,"뻒뻓"], +["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], +["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], +["9741","뾃",16,"뾕",8], +["9761","뾞",17,"뾱",7], +["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], +["9841","쁀",16,"쁒",5,"쁙쁚쁛"], +["9861","쁝쁞쁟쁡",6,"쁪",15], +["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], +["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], +["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], +["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], +["9a41","숤숥숦숧숪숬숮숰숳숵",16], +["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], +["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], +["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], +["9b61","쌳",17,"썆",7], +["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], +["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], +["9c61","쏿",8,"쐉",6,"쐑",9], +["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], +["9d41","쒪",13,"쒹쒺쒻쒽",8], +["9d61","쓆",25], +["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], +["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], +["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], +["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], +["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], +["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], +["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], +["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], +["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], +["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], +["a141","좥좦좧좩",18,"좾좿죀죁"], +["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], +["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], +["a241","줐줒",5,"줙",18], +["a261","줭",6,"줵",18], +["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], +["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], +["a361","즑",6,"즚즜즞",16], +["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], +["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], +["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], +["a481","쨦쨧쨨쨪",28,"ㄱ",93], +["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], +["a561","쩫",17,"쩾",5,"쪅쪆"], +["a581","쪇",16,"쪙",14,"ⅰ",9], +["a5b0","Ⅰ",9], +["a5c1","Α",16,"Σ",6], +["a5e1","α",16,"σ",6], +["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], +["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], +["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], +["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], +["a761","쬪",22,"쭂쭃쭄"], +["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], +["a841","쭭",10,"쭺",14], +["a861","쮉",18,"쮝",6], +["a881","쮤",19,"쮹",11,"ÆЪĦ"], +["a8a6","IJ"], +["a8a8","ĿŁØŒºÞŦŊ"], +["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], +["a941","쯅",14,"쯕",10], +["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], +["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], +["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], +["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], +["aa81","챳챴챶",29,"ぁ",82], +["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], +["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], +["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], +["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], +["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], +["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], +["acd1","а",5,"ёж",25], +["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], +["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], +["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], +["ae41","췆",5,"췍췎췏췑",16], +["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], +["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], +["af41","츬츭츮츯츲츴츶",19], +["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], +["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], +["b041","캚",5,"캢캦",5,"캮",12], +["b061","캻",5,"컂",19], +["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], +["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], +["b161","켥",6,"켮켲",5,"켹",11], +["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], +["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], +["b261","쾎",18,"쾢",5,"쾩"], +["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], +["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], +["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], +["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], +["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], +["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], +["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], +["b541","킕",14,"킦킧킩킪킫킭",5], +["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], +["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], +["b641","턅",7,"턎",17], +["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], +["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], +["b741","텮",13,"텽",6,"톅톆톇톉톊"], +["b761","톋",20,"톢톣톥톦톧"], +["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], +["b841","퇐",7,"퇙",17], +["b861","퇫",8,"퇵퇶퇷퇹",13], +["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], +["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], +["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], +["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], +["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], +["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], +["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], +["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], +["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], +["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], +["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], +["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], +["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], +["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], +["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], +["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], +["be41","퐸",7,"푁푂푃푅",14], +["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], +["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], +["bf41","풞",10,"풪",14], +["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], +["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], +["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], +["c061","픞",25], +["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], +["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], +["c161","햌햍햎햏햑",19,"햦햧"], +["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], +["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], +["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], +["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], +["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], +["c361","홢",4,"홨홪",5,"홲홳홵",11], +["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], +["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], +["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], +["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], +["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], +["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], +["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], +["c641","힍힎힏힑",6,"힚힜힞",5], +["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], +["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], +["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], +["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], +["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], +["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], +["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], +["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], +["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], +["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], +["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], +["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], +["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], +["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], +["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], +["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], +["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], +["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], +["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], +["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], +["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], +["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], +["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], +["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], +["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], +["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], +["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], +["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], +["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], +["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], +["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], +["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], +["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], +["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], +["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], +["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], +["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], +["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], +["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], +["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], +["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], +["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], +["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], +["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], +["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], +["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], +["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], +["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], +["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], +["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], +["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], +["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], +["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], +["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], +["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] +] diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp950.json b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp950.json new file mode 100644 index 0000000..d8bc871 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/cp950.json @@ -0,0 +1,177 @@ +[ +["0","\u0000",127], +["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], +["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], +["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], +["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], +["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], +["a3a1","ㄐ",25,"˙ˉˊˇˋ"], +["a3e1","€"], +["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], +["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], +["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], +["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], +["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], +["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], +["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], +["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], +["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], +["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], +["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], +["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], +["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], +["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], +["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], +["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], +["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], +["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], +["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], +["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], +["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], +["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], +["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], +["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], +["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], +["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], +["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], +["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], +["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], +["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], +["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], +["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], +["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], +["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], +["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], +["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], +["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], +["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], +["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], +["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], +["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], +["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], +["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], +["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], +["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], +["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], +["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], +["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], +["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], +["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], +["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], +["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], +["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], +["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], +["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], +["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], +["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], +["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], +["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], +["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], +["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], +["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], +["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], +["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], +["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], +["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], +["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], +["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], +["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], +["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], +["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], +["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], +["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], +["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], +["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], +["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], +["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], +["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], +["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], +["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], +["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], +["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], +["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], +["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], +["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], +["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], +["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], +["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], +["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], +["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], +["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], +["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], +["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], +["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], +["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], +["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], +["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], +["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], +["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], +["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], +["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], +["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], +["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], +["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], +["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], +["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], +["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], +["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], +["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], +["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], +["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], +["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], +["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], +["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], +["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], +["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], +["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], +["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], +["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], +["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], +["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], +["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], +["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], +["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], +["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], +["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], +["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], +["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], +["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], +["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], +["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], +["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], +["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], +["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], +["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], +["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], +["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], +["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], +["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], +["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], +["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], +["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], +["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], +["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], +["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], +["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], +["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], +["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], +["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], +["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], +["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], +["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], +["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], +["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], +["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], +["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], +["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], +["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], +["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], +["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], +["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], +["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], +["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], +["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], +["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], +["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], +["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] +] diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/eucjp.json b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/eucjp.json new file mode 100644 index 0000000..4fa61ca --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/eucjp.json @@ -0,0 +1,182 @@ +[ +["0","\u0000",127], +["8ea1","。",62], +["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], +["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], +["a2ba","∈∋⊆⊇⊂⊃∪∩"], +["a2ca","∧∨¬⇒⇔∀∃"], +["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["a2f2","ʼn♯♭♪†‡¶"], +["a2fe","◯"], +["a3b0","0",9], +["a3c1","A",25], +["a3e1","a",25], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["ada1","①",19,"Ⅰ",9], +["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], +["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], +["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], +["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], +["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], +["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], +["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], +["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], +["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], +["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], +["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], +["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], +["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], +["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], +["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], +["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], +["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], +["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], +["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], +["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], +["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], +["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], +["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], +["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], +["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], +["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], +["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], +["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], +["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], +["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], +["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], +["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], +["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], +["f4a1","堯槇遙瑤凜熙"], +["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], +["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], +["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["fcf1","ⅰ",9,"¬¦'""], +["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], +["8fa2c2","¡¦¿"], +["8fa2eb","ºª©®™¤№"], +["8fa6e1","ΆΈΉΊΪ"], +["8fa6e7","Ό"], +["8fa6e9","ΎΫ"], +["8fa6ec","Ώ"], +["8fa6f1","άέήίϊΐόςύϋΰώ"], +["8fa7c2","Ђ",10,"ЎЏ"], +["8fa7f2","ђ",10,"ўџ"], +["8fa9a1","ÆĐ"], +["8fa9a4","Ħ"], +["8fa9a6","IJ"], +["8fa9a8","ŁĿ"], +["8fa9ab","ŊØŒ"], +["8fa9af","ŦÞ"], +["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], +["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], +["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], +["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], +["8fabbd","ġĥíìïîǐ"], +["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], +["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], +["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], +["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], +["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], +["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], +["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], +["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], +["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], +["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], +["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], +["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], +["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], +["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], +["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], +["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], +["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], +["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], +["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], +["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], +["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], +["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], +["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], +["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], +["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], +["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], +["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], +["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], +["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], +["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], +["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], +["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], +["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], +["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], +["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], +["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], +["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], +["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], +["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], +["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], +["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], +["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], +["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], +["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], +["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], +["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], +["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], +["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], +["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], +["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], +["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], +["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], +["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], +["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], +["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], +["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], +["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], +["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], +["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], +["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], +["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], +["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], +["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] +] diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json new file mode 100644 index 0000000..85c6934 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json @@ -0,0 +1 @@ +{"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} \ No newline at end of file diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gbk-added.json b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gbk-added.json new file mode 100644 index 0000000..8abfa9f --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/gbk-added.json @@ -0,0 +1,55 @@ +[ +["a140","",62], +["a180","",32], +["a240","",62], +["a280","",32], +["a2ab","",5], +["a2e3","€"], +["a2ef",""], +["a2fd",""], +["a340","",62], +["a380","",31," "], +["a440","",62], +["a480","",32], +["a4f4","",10], +["a540","",62], +["a580","",32], +["a5f7","",7], +["a640","",62], +["a680","",32], +["a6b9","",7], +["a6d9","",6], +["a6ec",""], +["a6f3",""], +["a6f6","",8], +["a740","",62], +["a780","",32], +["a7c2","",14], +["a7f2","",12], +["a896","",10], +["a8bc",""], +["a8bf","ǹ"], +["a8c1",""], +["a8ea","",20], +["a958",""], +["a95b",""], +["a95d",""], +["a989","〾⿰",11], +["a997","",12], +["a9f0","",14], +["aaa1","",93], +["aba1","",93], +["aca1","",93], +["ada1","",93], +["aea1","",93], +["afa1","",93], +["d7fa","",4], +["f8a1","",93], +["f9a1","",93], +["faa1","",93], +["fba1","",93], +["fca1","",93], +["fda1","",93], +["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], +["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93] +] diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/shiftjis.json b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/shiftjis.json new file mode 100644 index 0000000..5a3a43c --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/tables/shiftjis.json @@ -0,0 +1,125 @@ +[ +["0","\u0000",128], +["a1","。",62], +["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], +["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], +["81b8","∈∋⊆⊇⊂⊃∪∩"], +["81c8","∧∨¬⇒⇔∀∃"], +["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["81f0","ʼn♯♭♪†‡¶"], +["81fc","◯"], +["824f","0",9], +["8260","A",25], +["8281","a",25], +["829f","ぁ",82], +["8340","ァ",62], +["8380","ム",22], +["839f","Α",16,"Σ",6], +["83bf","α",16,"σ",6], +["8440","А",5,"ЁЖ",25], +["8470","а",5,"ёж",7], +["8480","о",17], +["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["8740","①",19,"Ⅰ",9], +["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["877e","㍻"], +["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], +["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], +["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], +["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], +["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], +["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], +["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], +["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], +["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], +["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], +["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], +["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], +["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], +["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], +["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], +["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], +["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], +["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], +["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], +["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], +["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], +["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], +["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], +["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], +["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], +["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], +["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], +["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], +["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], +["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], +["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], +["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], +["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], +["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], +["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], +["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], +["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["eeef","ⅰ",9,"¬¦'""], +["f040","",62], +["f080","",124], +["f140","",62], +["f180","",124], +["f240","",62], +["f280","",124], +["f340","",62], +["f380","",124], +["f440","",62], +["f480","",124], +["f540","",62], +["f580","",124], +["f640","",62], +["f680","",124], +["f740","",62], +["f780","",124], +["f840","",62], +["f880","",124], +["f940",""], +["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], +["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], +["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], +["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], +["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] +] diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/utf16.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/utf16.js new file mode 100644 index 0000000..399f551 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/utf16.js @@ -0,0 +1,174 @@ +"use strict" + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { +} + +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf16BEEncoder() { +} + +Utf16BEEncoder.prototype.write = function(str) { + var buf = new Buffer(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; + } + return buf; +} + +Utf16BEEncoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf16BEDecoder() { + this.overflowByte = -1; +} + +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; + + var buf2 = new Buffer(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); +} + +Utf16BEDecoder.prototype.end = function() { +} + + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} + +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} + +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} + +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} + + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; + } + + return this.decoder.write(buf); +} + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var res = this.decoder.write(buf), + trail = this.decoder.end(); + + return trail ? (res + trail) : res; + } + return this.decoder.end(); +} + +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; + + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be'; + else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le'; + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; + } + + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; + } + } + + return enc; +} + + diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/utf7.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/utf7.js new file mode 100644 index 0000000..bab5099 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/encodings/utf7.js @@ -0,0 +1,289 @@ +"use strict" + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} + +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return new Buffer(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + +Utf7Encoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(new Buffer(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = new Buffer(6); + this.base64AccumIdx = 0; +} + +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = new Buffer(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } + } + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +Utf7IMAPEncoder.prototype.end = function() { + var buf = new Buffer(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; + } + + return buf.slice(0, bufIdx); +} + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(new Buffer(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/bom-handling.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/bom-handling.js new file mode 100644 index 0000000..3f0ed93 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/bom-handling.js @@ -0,0 +1,52 @@ +"use strict" + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; + } + + return this.encoder.write(str); +} + +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} + + +//------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} + +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); + } + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} + diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/extend-node.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/extend-node.js new file mode 100644 index 0000000..1d8c953 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/extend-node.js @@ -0,0 +1,214 @@ +"use strict" + +// == Extend Node primitives to use iconv-lite ================================= + +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + iconv.supportsNodeEncodingsExtension = !(new Buffer(0) instanceof Uint8Array); + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; + } + + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, + }; + + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; + } + + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = require('buffer').SlowBuffer; + + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + } + + // -- Buffer --------------------------------------------------------------- + + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); + } + + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); + + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; + } + + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + + // TODO: Set _charsWritten. + } + + + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; + } + + Readable.prototype.collect = iconv._collect; + } + } + + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) + return; + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + + delete Buffer.isNativeEncoding; + + var SlowBuffer = require('buffer').SlowBuffer; + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } +} diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/index.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/index.js new file mode 100644 index 0000000..ac1403c --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/index.js @@ -0,0 +1,141 @@ +"use strict" + +var bomHandling = require('./bom-handling'), + iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = new Buffer("" + (buf || ""), "binary"); // Ensure buffer. + } + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; + } +} + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = (''+encoding).toLowerCase().replace(/[^0-9a-z]|:\d{4}$/g, ""); + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; + + var codecDef = iconv.encodings[enc]; + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; + + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); + + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} + +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); + + return encoder; +} + +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; +} + + +// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; +if (nodeVer) { + + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + require("./streams")(iconv); + } + + // Load Node primitive extensions. + require("./extend-node")(iconv); +} + diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/streams.js b/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/streams.js new file mode 100644 index 0000000..c95b26c --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/lib/streams.js @@ -0,0 +1,120 @@ +"use strict" + +var Transform = require("stream").Transform; + + +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + } + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + } + + iconv.supportsStreams = true; + + + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; + + +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); +} + +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; +} + + +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); +} + +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); + +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; +} + diff --git a/5-3/node_modules/body-parser/node_modules/iconv-lite/package.json b/5-3/node_modules/body-parser/node_modules/iconv-lite/package.json new file mode 100644 index 0000000..c9c5ec9 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/iconv-lite/package.json @@ -0,0 +1,119 @@ +{ + "name": "iconv-lite", + "description": "Convert character encodings in pure javascript.", + "version": "0.4.13", + "license": "MIT", + "keywords": [ + "iconv", + "convert", + "charset", + "icu" + ], + "author": { + "name": "Alexander Shtuchkin", + "email": "ashtuchkin@gmail.com" + }, + "contributors": [ + { + "name": "Jinwu Zhan", + "url": "https://github.com/jenkinv" + }, + { + "name": "Adamansky Anton", + "url": "https://github.com/adamansky" + }, + { + "name": "George Stagas", + "url": "https://github.com/stagas" + }, + { + "name": "Mike D Pilsbury", + "url": "https://github.com/pekim" + }, + { + "name": "Niggler", + "url": "https://github.com/Niggler" + }, + { + "name": "wychi", + "url": "https://github.com/wychi" + }, + { + "name": "David Kuo", + "url": "https://github.com/david50407" + }, + { + "name": "ChangZhuo Chen", + "url": "https://github.com/czchen" + }, + { + "name": "Lee Treveil", + "url": "https://github.com/leetreveil" + }, + { + "name": "Brian White", + "url": "https://github.com/mscdex" + }, + { + "name": "Mithgol", + "url": "https://github.com/Mithgol" + }, + { + "name": "Nazar Leush", + "url": "https://github.com/nleush" + } + ], + "main": "./lib/index.js", + "homepage": "https://github.com/ashtuchkin/iconv-lite", + "bugs": { + "url": "https://github.com/ashtuchkin/iconv-lite/issues" + }, + "repository": { + "type": "git", + "url": "git://github.com/ashtuchkin/iconv-lite.git" + }, + "engines": { + "node": ">=0.8.0" + }, + "scripts": { + "coverage": "istanbul cover _mocha -- --grep .", + "coverage-open": "open coverage/lcov-report/index.html", + "test": "mocha --reporter spec --grep ." + }, + "browser": { + "./extend-node": false, + "./streams": false + }, + "devDependencies": { + "mocha": "*", + "request": "2.47", + "unorm": "*", + "errto": "*", + "async": "*", + "istanbul": "*", + "iconv": "2.1" + }, + "gitHead": "f5ec51b1e7dd1477a3570824960641eebdc5fbc6", + "_id": "iconv-lite@0.4.13", + "_shasum": "1f88aba4ab0b1508e8312acc39345f36e992e2f2", + "_from": "iconv-lite@0.4.13", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.1", + "_npmUser": { + "name": "ashtuchkin", + "email": "ashtuchkin@gmail.com" + }, + "maintainers": [ + { + "name": "ashtuchkin", + "email": "ashtuchkin@gmail.com" + } + ], + "dist": { + "shasum": "1f88aba4ab0b1508e8312acc39345f36e992e2f2", + "tarball": "http://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.13.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.13.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/on-finished/HISTORY.md b/5-3/node_modules/body-parser/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000..98ff0e9 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/on-finished/HISTORY.md @@ -0,0 +1,88 @@ +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +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 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/5-3/node_modules/body-parser/node_modules/on-finished/LICENSE b/5-3/node_modules/body-parser/node_modules/on-finished/LICENSE new file mode 100644 index 0000000..5931fd2 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/body-parser/node_modules/on-finished/README.md b/5-3/node_modules/body-parser/node_modules/on-finished/README.md new file mode 100644 index 0000000..a0e1157 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/on-finished/README.md @@ -0,0 +1,154 @@ +# on-finished + +[![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] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to 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, res) { + // clean up open fds, etc. + // err contains the error is request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to 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 = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg +[downloads-url]: https://npmjs.org/package/on-finished diff --git a/5-3/node_modules/body-parser/node_modules/on-finished/index.js b/5-3/node_modules/body-parser/node_modules/on-finished/index.js new file mode 100644 index 0000000..9abd98f --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/on-finished/index.js @@ -0,0 +1,196 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener(msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish(error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket) + callback(socket) + } +} diff --git a/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/LICENSE b/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/README.md b/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/index.js b/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/package.json b/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/package.json new file mode 100644 index 0000000..1d223fb --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/on-finished/node_modules/ee-first/package.json @@ -0,0 +1,64 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jonathanong/ee-first.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "512e0ce4cc3643f603708f965a97b61b1a9c0441", + "bugs": { + "url": "https://github.com/jonathanong/ee-first/issues" + }, + "homepage": "https://github.com/jonathanong/ee-first", + "_id": "ee-first@1.1.1", + "_shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "_from": "ee-first@1.1.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/on-finished/package.json b/5-3/node_modules/body-parser/node_modules/on-finished/package.json new file mode 100644 index 0000000..7b2ebdd --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/on-finished/package.json @@ -0,0 +1,71 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.3.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/on-finished.git" + }, + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "34babcb58126a416fcf5205768204f2e12699dda", + "bugs": { + "url": "https://github.com/jshttp/on-finished/issues" + }, + "homepage": "https://github.com/jshttp/on-finished", + "_id": "on-finished@2.3.0", + "_shasum": "20f1336481b083cd75337992a16971aa2d906947", + "_from": "on-finished@>=2.3.0 <2.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "20f1336481b083cd75337992a16971aa2d906947", + "tarball": "http://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/qs/.eslintignore b/5-3/node_modules/body-parser/node_modules/qs/.eslintignore new file mode 100644 index 0000000..1521c8b --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/.eslintignore @@ -0,0 +1 @@ +dist diff --git a/5-3/node_modules/body-parser/node_modules/qs/.npmignore b/5-3/node_modules/body-parser/node_modules/qs/.npmignore new file mode 100644 index 0000000..7e1574d --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/.npmignore @@ -0,0 +1,18 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov +complexity.md diff --git a/5-3/node_modules/body-parser/node_modules/qs/.travis.yml b/5-3/node_modules/body-parser/node_modules/qs/.travis.yml new file mode 100644 index 0000000..335fded --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/.travis.yml @@ -0,0 +1,8 @@ +language: node_js + +node_js: + - 0.10 + - 4.0 + - 4 + +sudo: false diff --git a/5-3/node_modules/body-parser/node_modules/qs/CHANGELOG.md b/5-3/node_modules/body-parser/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000..e43b1ac --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/CHANGELOG.md @@ -0,0 +1,99 @@ + +## [**5.1.0**](https://github.com/hapijs/qs/issues?milestone=29&state=open) +- [**#117**](https://github.com/hapijs/qs/issues/117) make URI encoding stringified results optional +- [**#106**](https://github.com/hapijs/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify + +## [**5.0.0**](https://github.com/hapijs/qs/issues?milestone=28&state=closed) +- [**#114**](https://github.com/hapijs/qs/issues/114) default allowDots to false +- [**#100**](https://github.com/hapijs/qs/issues/100) include dist to npm + +## [**4.0.0**](https://github.com/hapijs/qs/issues?milestone=26&state=closed) +- [**#98**](https://github.com/hapijs/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional + +## [**3.1.0**](https://github.com/hapijs/qs/issues?milestone=24&state=closed) +- [**#89**](https://github.com/hapijs/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/hapijs/qs/issues?milestone=23&state=closed) +- [**#80**](https://github.com/hapijs/qs/issues/80) qs.parse silently drops properties +- [**#77**](https://github.com/hapijs/qs/issues/77) Perf boost +- [**#60**](https://github.com/hapijs/qs/issues/60) Add explicit option to disable array parsing +- [**#74**](https://github.com/hapijs/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/hapijs/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/hapijs/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/hapijs/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/hapijs/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/hapijs/qs/issues/85) No equal sign +- [**#84**](https://github.com/hapijs/qs/issues/84) update license attribute + +## [**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". + +## [**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 + +## [**2.2.5**](https://github.com/hapijs/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/hapijs/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/hapijs/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/hapijs/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/hapijs/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/hapijs/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/hapijs/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/hapijs/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/hapijs/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/hapijs/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/hapijs/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/hapijs/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/hapijs/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/hapijs/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/hapijs/qs/issues/32) account for circular references properly, closes #31 +- [**#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 +- [**#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 +- [**#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) +- [**#22**](https://github.com/hapijs/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/hapijs/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/hapijs/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/hapijs/qs/issues/20) Configurable parametersLimit +- [**#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 + +## [**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 +- [**#15**](https://github.com/hapijs/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/hapijs/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/hapijs/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/hapijs/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/hapijs/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/hapijs/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/hapijs/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/hapijs/qs/issues/6) Minor grammar fix in README + +## [**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/5-3/node_modules/body-parser/node_modules/qs/CONTRIBUTING.md b/5-3/node_modules/body-parser/node_modules/qs/CONTRIBUTING.md new file mode 100644 index 0000000..8928361 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/CONTRIBUTING.md @@ -0,0 +1 @@ +Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md). diff --git a/5-3/node_modules/body-parser/node_modules/qs/LICENSE b/5-3/node_modules/body-parser/node_modules/qs/LICENSE new file mode 100644 index 0000000..d456948 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/5-3/node_modules/body-parser/node_modules/qs/README.md b/5-3/node_modules/body-parser/node_modules/qs/README.md new file mode 100644 index 0000000..3c61db3 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/README.md @@ -0,0 +1,331 @@ +# qs + +A querystring parsing and stringifying library with some added security. + +[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs) + +Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var Qs = require('qs'); + +var obj = Qs.parse('a=c'); // { a: 'c' } +var str = Qs.stringify(obj); // 'a=c' +``` + +### Parsing Objects + +```javascript +Qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +{ + foo: { + bar: 'baz' + } +} +``` + +When using the `plainObjects` option the parsed value is returned as a plain object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +Qs.parse('a.hasOwnProperty=b', { plainObjects: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. + +```javascript +Qs.parse('a.hasOwnProperty=b', { allowPrototypes: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +URI encoded strings work too: + +```javascript +Qs.parse('a%5Bb%5D=c'); +// { a: { b: 'c' } } +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +{ + foo: { + bar: { + baz: 'foobarbaz' + } + } +} +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +{ + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +} +``` + +This depth can be overridden by passing a `depth` option to `Qs.parse(string, [options])`: + +```javascript +Qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } } +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +Qs.parse('a=b&c=d', { parameterLimit: 1 }); +// { a: 'b' } +``` + +An optional delimiter can also be passed: + +```javascript +Qs.parse('a=b;c=d', { delimiter: ';' }); +// { a: 'b', c: 'd' } +``` + +Delimiters can be a regular expression too: + +```javascript +Qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +// { a: 'b', c: 'd', e: 'f' } +``` + +Option `allowDots` can be used to enable dot notation: + +```javascript +Qs.parse('a.b=c', { allowDots: true }); +// { a: { b: 'c' } } +``` + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +Qs.parse('a[]=b&a[]=c'); +// { a: ['b', 'c'] } +``` + +You may specify an index as well: + +```javascript +Qs.parse('a[1]=c&a[0]=b'); +// { a: ['b', 'c'] } +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +Qs.parse('a[1]=b&a[15]=c'); +// { a: ['b', 'c'] } +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +Qs.parse('a[]=&a[]=b'); +// { a: ['', 'b'] } +Qs.parse('a[0]=b&a[1]=&a[2]=c'); +// { a: ['b', '', 'c'] } +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key: + +```javascript +Qs.parse('a[100]=b'); +// { a: { '100': 'b' } } +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +Qs.parse('a[1]=b', { arrayLimit: 0 }); +// { a: { '1': 'b' } } +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +Qs.parse('a[]=b', { parseArrays: false }); +// { a: { '0': 'b' } } +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +Qs.parse('a[0]=b&a[b]=c'); +// { a: { '0': 'b', b: 'c' } } +``` + +You can also create arrays of objects: + +```javascript +Qs.parse('a[][b]=c'); +// { a: [{ b: 'c' }] } +``` + +### Stringifying + +```javascript +Qs.stringify(object, [options]); +``` + +When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: + +```javascript +Qs.stringify({ a: 'b' }); +// 'a=b' +Qs.stringify({ a: { b: 'c' } }); +// 'a%5Bb%5D=c' +``` + +This encoding can be disabled by setting the `encode` option to `false`: + +```javascript +Qs.stringify({ a: { b: 'c' } }, { encode: false }); +// 'a[b]=c' +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +Qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +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 +Qs.stringify({ a: '' }); +// 'a=' +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +Qs.stringify({ a: null, b: undefined }); +// 'a=' +``` + +The delimiter may be overridden with stringify as well: + +```javascript +Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }); +// 'a=b;c=d' +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +Qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }) +// 'a=b&c=d&e[f]=123&e[g][0]=4' +Qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }) +// 'a=b&e=f' +Qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }) +// 'a[0]=b&a[2]=d' +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +Qs.stringify({ a: null, b: '' }); +// 'a=&b=' +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +Qs.parse('a&b=') +// { a: '', b: '' } +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +Qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +// 'a&b=' +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +Qs.parse('a&b=', { strictNullHandling: true }); +// { a: null, b: '' } + +``` + +To completely skip rendering keys with `null` values, use the `skipNulls` flag: + +```javascript +qs.stringify({ a: 'b', c: null}, { skipNulls: true }) +// 'a=b' +``` diff --git a/5-3/node_modules/body-parser/node_modules/qs/bower.json b/5-3/node_modules/body-parser/node_modules/qs/bower.json new file mode 100644 index 0000000..53a70d0 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/bower.json @@ -0,0 +1,22 @@ +{ + "name": "qs", + "main": "dist/qs.js", + "version": "5.1.0", + "homepage": "https://github.com/hapijs/qs", + "authors": [ + "Nathan LaFreniere " + ], + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/5-3/node_modules/body-parser/node_modules/qs/component.json b/5-3/node_modules/body-parser/node_modules/qs/component.json new file mode 100644 index 0000000..1a1f72c --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/component.json @@ -0,0 +1,15 @@ +{ + "name": "qs", + "repository": "hapijs/qs", + "description": "query-string parser / stringifier with nesting support", + "version": "5.1.0", + "keywords": ["querystring", "query", "parser"], + "main": "lib/index.js", + "scripts": [ + "lib/index.js", + "lib/parse.js", + "lib/stringify.js", + "lib/utils.js" + ], + "license": "BSD-3-Clause" +} diff --git a/5-3/node_modules/body-parser/node_modules/qs/dist/qs.js b/5-3/node_modules/body-parser/node_modules/qs/dist/qs.js new file mode 100644 index 0000000..b72e976 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/dist/qs.js @@ -0,0 +1,544 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= 0 && + (options.parseArrays && + index <= options.arrayLimit)) { + + obj = []; + obj[index] = internals.parseObject(chain, val, options); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val, options); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, options) { + + if (!key) { + return; + } + + // Transform dot notation to bracket notation + + if (options.allowDots) { + key = key.replace(/\.([^\.\[]+)/g, '[$1]'); + } + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1])) { + + if (!options.allowPrototypes) { + return; + } + } + + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + + ++i; + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { + + if (!options.allowPrototypes) { + continue; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val, options); +}; + + +module.exports = function (str, options) { + + options = options || {}; + options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : internals.allowDots; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : internals.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : internals.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var newObj = internals.parseKeys(key, tempObj[key], options); + obj = Utils.merge(obj, newObj, options); + } + + return Utils.compact(obj); +}; + +},{"./utils":4}],3:[function(require,module,exports){ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + arrayPrefixGenerators: { + brackets: function (prefix, key) { + + return prefix + '[]'; + }, + indices: function (prefix, key) { + + return prefix + '[' + key + ']'; + }, + repeat: function (prefix, key) { + + return prefix; + } + }, + strictNullHandling: false, + skipNulls: false, + encode: true +}; + + +internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter) { + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } + else if (Utils.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + else if (obj === null) { + if (strictNullHandling) { + return encode ? Utils.encode(prefix) : prefix; + } + + obj = ''; + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + if (encode) { + return [Utils.encode(prefix) + '=' + Utils.encode(obj)]; + } + return [prefix + '=' + obj]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys = Array.isArray(filter) ? filter : Object.keys(obj); + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (skipNulls && + obj[key] === null) { + + continue; + } + + if (Array.isArray(obj)) { + values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encode, filter)); + } + else { + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, skipNulls, encode, filter)); + } + } + + return values; +}; + + +module.exports = function (obj, options) { + + options = options || {}; + var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : internals.skipNulls; + var encode = typeof options.encode === 'boolean' ? options.encode : internals.encode; + var objKeys; + var filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } + else if (Array.isArray(options.filter)) { + objKeys = filter = options.filter; + } + + var keys = []; + + if (typeof obj !== 'object' || + obj === null) { + + 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]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (skipNulls && + obj[key] === null) { + + continue; + } + + keys = keys.concat(internals.stringify(obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter)); + } + + return keys.join(delimiter); +}; + +},{"./utils":4}],4:[function(require,module,exports){ +// Load modules + + +// Declare internals + +var internals = {}; +internals.hexTable = new Array(256); +for (var h = 0; h < 256; ++h) { + internals.hexTable[h] = '%' + ((h < 16 ? '0' : '') + h.toString(16)).toUpperCase(); +} + + +exports.arrayToObject = function (source, options) { + + var obj = options.plainObjects ? Object.create(null) : {}; + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.merge = function (target, source, options) { + + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } + else if (typeof target === 'object') { + target[source] = true; + } + else { + target = [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + target = [target].concat(source); + return target; + } + + if (Array.isArray(target) && + !Array.isArray(source)) { + + target = exports.arrayToObject(target, options); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = value; + } + else { + target[key] = exports.merge(target[key], value, options); + } + } + + return target; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function (str) { + + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + if (typeof str !== 'string') { + str = '' + str; + } + + var out = ''; + for (var i = 0, il = str.length; i < il; ++i) { + var c = str.charCodeAt(i); + + if (c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A)) { // A-Z + + out += str[i]; + continue; + } + + if (c < 0x80) { + out += internals.hexTable[c]; + continue; + } + + if (c < 0x800) { + out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + ++i; + c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF)); + out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function (obj, refs) { + + if (typeof obj !== 'object' || + obj === null) { + + return obj; + } + + refs = refs || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } + + refs.push(obj); + + if (Array.isArray(obj)) { + var compacted = []; + + for (var i = 0, il = obj.length; i < il; ++i) { + if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } + + return compacted; + } + + var keys = Object.keys(obj); + for (i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + obj[key] = exports.compact(obj[key], refs); + } + + return obj; +}; + + +exports.isRegExp = function (obj) { + + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + + +exports.isBuffer = function (obj) { + + if (obj === null || + typeof obj === 'undefined') { + + return false; + } + + return !!(obj.constructor && + obj.constructor.isBuffer && + obj.constructor.isBuffer(obj)); +}; + +},{}]},{},[1])(1) +}); \ No newline at end of file diff --git a/5-3/node_modules/body-parser/node_modules/qs/lib/index.js b/5-3/node_modules/body-parser/node_modules/qs/lib/index.js new file mode 100644 index 0000000..0e09493 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/lib/index.js @@ -0,0 +1,15 @@ +// Load modules + +var Stringify = require('./stringify'); +var Parse = require('./parse'); + + +// Declare internals + +var internals = {}; + + +module.exports = { + stringify: Stringify, + parse: Parse +}; diff --git a/5-3/node_modules/body-parser/node_modules/qs/lib/parse.js b/5-3/node_modules/body-parser/node_modules/qs/lib/parse.js new file mode 100644 index 0000000..4a2137e --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/lib/parse.js @@ -0,0 +1,187 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + depth: 5, + arrayLimit: 20, + parameterLimit: 1000, + strictNullHandling: false, + plainObjects: false, + allowPrototypes: false, + allowDots: false +}; + + +internals.parseValues = function (str, options) { + + var obj = {}; + var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); + + for (var i = 0, il = parts.length; i < il; ++i) { + var part = parts[i]; + var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; + + if (pos === -1) { + obj[Utils.decode(part)] = ''; + + if (options.strictNullHandling) { + obj[Utils.decode(part)] = null; + } + } + else { + var key = Utils.decode(part.slice(0, pos)); + var val = Utils.decode(part.slice(pos + 1)); + + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + obj[key] = val; + } + else { + obj[key] = [].concat(obj[key]).concat(val); + } + } + } + + return obj; +}; + + +internals.parseObject = function (chain, val, options) { + + if (!chain.length) { + return val; + } + + var root = chain.shift(); + + var obj; + if (root === '[]') { + obj = []; + obj = obj.concat(internals.parseObject(chain, val, options)); + } + else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; + var index = parseInt(cleanRoot, 10); + var indexString = '' + index; + if (!isNaN(index) && + root !== cleanRoot && + indexString === cleanRoot && + index >= 0 && + (options.parseArrays && + index <= options.arrayLimit)) { + + obj = []; + obj[index] = internals.parseObject(chain, val, options); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val, options); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, options) { + + if (!key) { + return; + } + + // Transform dot notation to bracket notation + + if (options.allowDots) { + key = key.replace(/\.([^\.\[]+)/g, '[$1]'); + } + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1])) { + + if (!options.allowPrototypes) { + return; + } + } + + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + + ++i; + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { + + if (!options.allowPrototypes) { + continue; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val, options); +}; + + +module.exports = function (str, options) { + + options = options || {}; + options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : internals.allowDots; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : internals.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : internals.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var newObj = internals.parseKeys(key, tempObj[key], options); + obj = Utils.merge(obj, newObj, options); + } + + return Utils.compact(obj); +}; diff --git a/5-3/node_modules/body-parser/node_modules/qs/lib/stringify.js b/5-3/node_modules/body-parser/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000..d05aa87 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/lib/stringify.js @@ -0,0 +1,154 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + arrayPrefixGenerators: { + brackets: function (prefix, key) { + + return prefix + '[]'; + }, + indices: function (prefix, key) { + + return prefix + '[' + key + ']'; + }, + repeat: function (prefix, key) { + + return prefix; + } + }, + strictNullHandling: false, + skipNulls: false, + encode: true +}; + + +internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter, sort) { + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } + else if (Utils.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + else if (obj === null) { + if (strictNullHandling) { + return encode ? Utils.encode(prefix) : prefix; + } + + obj = ''; + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + if (encode) { + return [Utils.encode(prefix) + '=' + Utils.encode(obj)]; + } + return [prefix + '=' + obj]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (Array.isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (skipNulls && + obj[key] === null) { + + continue; + } + + if (Array.isArray(obj)) { + values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encode, filter)); + } + else { + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, skipNulls, encode, filter)); + } + } + + return values; +}; + + +module.exports = function (obj, options) { + + options = options || {}; + var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : internals.skipNulls; + var encode = typeof options.encode === 'boolean' ? options.encode : internals.encode; + var sort = typeof options.sort === 'function' ? options.sort : null; + var objKeys; + var filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } + else if (Array.isArray(options.filter)) { + objKeys = filter = options.filter; + } + + var keys = []; + + if (typeof obj !== 'object' || + obj === null) { + + 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]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (sort) { + objKeys.sort(sort); + } + + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (skipNulls && + obj[key] === null) { + + continue; + } + + keys = keys.concat(internals.stringify(obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode, filter, sort)); + } + + return keys.join(delimiter); +}; diff --git a/5-3/node_modules/body-parser/node_modules/qs/lib/utils.js b/5-3/node_modules/body-parser/node_modules/qs/lib/utils.js new file mode 100644 index 0000000..88f3147 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/lib/utils.js @@ -0,0 +1,190 @@ +// Load modules + + +// Declare internals + +var internals = {}; +internals.hexTable = new Array(256); +for (var h = 0; h < 256; ++h) { + internals.hexTable[h] = '%' + ((h < 16 ? '0' : '') + h.toString(16)).toUpperCase(); +} + + +exports.arrayToObject = function (source, options) { + + var obj = options.plainObjects ? Object.create(null) : {}; + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.merge = function (target, source, options) { + + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } + else if (typeof target === 'object') { + target[source] = true; + } + else { + target = [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + target = [target].concat(source); + return target; + } + + if (Array.isArray(target) && + !Array.isArray(source)) { + + target = exports.arrayToObject(target, options); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = value; + } + else { + target[key] = exports.merge(target[key], value, options); + } + } + + return target; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function (str) { + + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + if (typeof str !== 'string') { + str = '' + str; + } + + var out = ''; + for (var i = 0, il = str.length; i < il; ++i) { + var c = str.charCodeAt(i); + + if (c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A)) { // A-Z + + out += str[i]; + continue; + } + + if (c < 0x80) { + out += internals.hexTable[c]; + continue; + } + + if (c < 0x800) { + out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + ++i; + c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF)); + out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function (obj, refs) { + + if (typeof obj !== 'object' || + obj === null) { + + return obj; + } + + refs = refs || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } + + refs.push(obj); + + if (Array.isArray(obj)) { + var compacted = []; + + for (var i = 0, il = obj.length; i < il; ++i) { + if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } + + return compacted; + } + + var keys = Object.keys(obj); + for (i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + obj[key] = exports.compact(obj[key], refs); + } + + return obj; +}; + + +exports.isRegExp = function (obj) { + + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + + +exports.isBuffer = function (obj) { + + if (obj === null || + typeof obj === 'undefined') { + + return false; + } + + return !!(obj.constructor && + obj.constructor.isBuffer && + obj.constructor.isBuffer(obj)); +}; diff --git a/5-3/node_modules/body-parser/node_modules/qs/package.json b/5-3/node_modules/body-parser/node_modules/qs/package.json new file mode 100644 index 0000000..4dffe46 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/package.json @@ -0,0 +1,59 @@ +{ + "name": "qs", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/hapijs/qs", + "version": "5.2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/hapijs/qs.git" + }, + "main": "lib/index.js", + "keywords": [ + "querystring", + "qs" + ], + "engines": ">=0.10.40", + "dependencies": {}, + "devDependencies": { + "browserify": "^10.2.1", + "code": "1.x.x", + "lab": "5.x.x" + }, + "scripts": { + "test": "lab -a code -t 100 -L", + "test-tap": "lab -a code -r tap -o tests.tap", + "test-cov-html": "lab -a code -r html -o coverage.html", + "dist": "browserify --standalone Qs lib/index.js > dist/qs.js" + }, + "license": "BSD-3-Clause", + "gitHead": "a341cdf2fadba5ede1ce6c95c7051f6f31f37b81", + "bugs": { + "url": "https://github.com/hapijs/qs/issues" + }, + "_id": "qs@5.2.0", + "_shasum": "a9f31142af468cb72b25b30136ba2456834916be", + "_from": "qs@5.2.0", + "_npmVersion": "3.3.5", + "_nodeVersion": "0.10.40", + "_npmUser": { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + "dist": { + "shasum": "a9f31142af468cb72b25b30136ba2456834916be", + "tarball": "http://registry.npmjs.org/qs/-/qs-5.2.0.tgz" + }, + "maintainers": [ + { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/qs/-/qs-5.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/qs/test/parse.js b/5-3/node_modules/body-parser/node_modules/qs/test/parse.js new file mode 100644 index 0000000..679f197 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/test/parse.js @@ -0,0 +1,478 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('parse()', function () { + + it('parses a simple string', function (done) { + + expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' }); + expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' }); + expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } }); + expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } }); + expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } }); + expect(Qs.parse('foo', { strictNullHandling: true })).to.deep.equal({ foo: null }); + expect(Qs.parse('foo' )).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=')).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' }); + expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' }); + expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' }); + expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' }); + expect(Qs.parse('foo2=bar2&baz2=')).to.deep.equal({ foo2: 'bar2', baz2: '' }); + expect(Qs.parse('foo=bar&baz', { strictNullHandling: true })).to.deep.equal({ foo: 'bar', baz: null }); + expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' }); + expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({ + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + done(); + }); + + it('allows enabling dot notation', function (done) { + + expect(Qs.parse('a.b=c')).to.deep.equal({ 'a.b': 'c' }); + expect(Qs.parse('a.b=c', { allowDots: true })).to.deep.equal({ a: { b: 'c' } }); + done(); + }); + + it('parses a single nested string', function (done) { + + expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } }); + done(); + }); + + it('parses a double nested string', function (done) { + + expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } }); + done(); + }); + + it('defaults to a depth of 5', function (done) { + + expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }); + done(); + }); + + it('only parses one level when depth = 1', function (done) { + + expect(Qs.parse('a[b][c]=d', { depth: 1 })).to.deep.equal({ a: { b: { '[c]': 'd' } } }); + expect(Qs.parse('a[b][c][d]=e', { depth: 1 })).to.deep.equal({ a: { b: { '[c][d]': 'e' } } }); + done(); + }); + + it('parses a simple array', function (done) { + + expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses an explicit array', function (done) { + + expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] }); + expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + done(); + }); + + it('parses a mix of simple and explicit arrays', function (done) { + + expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses a nested array', function (done) { + + expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } }); + expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } }); + done(); + }); + + it('allows to specify array indices', function (done) { + + expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] }); + done(); + }); + + it('limits specific array indices to 20', function (done) { + + expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] }); + expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } }); + done(); + }); + + it('supports keys that begin with a number', function (done) { + + expect(Qs.parse('a[12b]=c')).to.deep.equal({ a: { '12b': 'c' } }); + done(); + }); + + it('supports encoded = signs', function (done) { + + expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' }); + done(); + }); + + it('is ok with url encoded strings', function (done) { + + expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } }); + expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } }); + done(); + }); + + it('allows brackets in the value', function (done) { + + expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' }); + expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' }); + done(); + }); + + it('allows empty values', function (done) { + + expect(Qs.parse('')).to.deep.equal({}); + expect(Qs.parse(null)).to.deep.equal({}); + expect(Qs.parse(undefined)).to.deep.equal({}); + done(); + }); + + it('transforms arrays to objects', function (done) { + + expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + expect(Qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c')).to.deep.equal({ a: { '0': 'b', t: 'u', c: true } }); + expect(Qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y')).to.deep.equal({ a: { '0': 'b', '1': 'c', x: 'y' } }); + done(); + }); + + it('transforms arrays to objects (dot notation)', function (done) { + + expect(Qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true })).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true })).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + expect(Qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true })).to.deep.equal({ foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true })).to.deep.equal({ foo: [{ baz: ['15'], bar: '2' }] }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true })).to.deep.equal({ foo: [{ baz: ['15', '16'], bar: '2' }] }); + expect(Qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true })).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true })).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true })).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + done(); + }); + + it('can add keys to objects', function (done) { + + expect(Qs.parse('a[b]=c&a=d')).to.deep.equal({ a: { b: 'c', d: true } }); + done(); + }); + + it('correctly prunes undefined values when converting an array to an object', function (done) { + + expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } }); + done(); + }); + + it('supports malformed uri characters', function (done) { + + expect(Qs.parse('{%:%}', { strictNullHandling: true })).to.deep.equal({ '{%:%}': null }); + expect(Qs.parse('{%:%}=')).to.deep.equal({ '{%:%}': '' }); + expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' }); + done(); + }); + + it('doesn\'t produce empty keys', function (done) { + + expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' }); + done(); + }); + + it('cannot access Object prototype', function (done) { + + Qs.parse('constructor[prototype][bad]=bad'); + Qs.parse('bad[constructor][prototype][bad]=bad'); + expect(typeof Object.prototype.bad).to.equal('undefined'); + done(); + }); + + it('parses arrays of objects', function (done) { + + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + done(); + }); + + it('allows for empty strings in arrays', function (done) { + + expect(Qs.parse('a[]=b&a[]=&a[]=c')).to.deep.equal({ a: ['b', '', 'c'] }); + expect(Qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true })).to.deep.equal({ a: ['b', null, 'c', ''] }); + expect(Qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true })).to.deep.equal({ a: ['b', '', 'c', null] }); + expect(Qs.parse('a[]=&a[]=b&a[]=c')).to.deep.equal({ a: ['', 'b', 'c'] }); + done(); + }); + + it('compacts sparse arrays', function (done) { + + expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] }); + done(); + }); + + it('parses semi-parsed strings', function (done) { + + expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } }); + done(); + }); + + it('parses buffers correctly', function (done) { + + var b = new Buffer('test'); + expect(Qs.parse({ a: b })).to.deep.equal({ a: b }); + done(); + }); + + it('continues parsing when no parent is found', function (done) { + + expect(Qs.parse('[]=&a=b')).to.deep.equal({ '0': '', a: 'b' }); + expect(Qs.parse('[]&a=b', { strictNullHandling: true })).to.deep.equal({ '0': null, a: 'b' }); + expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' }); + done(); + }); + + it('does not error when parsing a very long array', function (done) { + + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str += '&' + str; + } + + expect(function () { + + Qs.parse(str); + }).to.not.throw(); + + done(); + }); + + it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) { + + Object.prototype.crash = ''; + Array.prototype.crash = ''; + expect(Qs.parse.bind(null, 'a=b')).to.not.throw(); + expect(Qs.parse('a=b')).to.deep.equal({ a: 'b' }); + expect(Qs.parse.bind(null, 'a[][b]=c')).to.not.throw(); + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + done(); + }); + + it('parses a string with an alternative string delimiter', function (done) { + + expect(Qs.parse('a=b;c=d', { delimiter: ';' })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('parses a string with an alternative RegExp delimiter', function (done) { + + expect(Qs.parse('a=b; c=d', { delimiter: /[;,] */ })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not use non-splittable objects as delimiters', function (done) { + + expect(Qs.parse('a=b&c=d', { delimiter: true })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('allows overriding parameter limit', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: 1 })).to.deep.equal({ a: 'b' }); + done(); + }); + + it('allows setting the parameter limit to Infinity', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: Infinity })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + 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(); + }); + + it('allows disabling array parsing', function (done) { + + expect(Qs.parse('a[0]=b&a[1]=c', { parseArrays: false })).to.deep.equal({ a: { '0': 'b', '1': 'c' } }); + done(); + }); + + it('parses an object', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object in dot notation', function (done) { + + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input, { allowDots: true }); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object and not child values', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': { 'test': 3 } }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': { 'test': 3 } }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('does not blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = Qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + expect(result).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not crash when parsing circular references', function (done) { + + var a = {}; + a.b = a; + + var parsed; + + expect(function () { + + parsed = Qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }).to.not.throw(); + + 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(); + }); + + it('parses plain objects correctly', function (done) { + + var a = Object.create(null); + a.b = 'c'; + + expect(Qs.parse(a)).to.deep.equal({ b: 'c' }); + var result = Qs.parse({ a: a }); + expect(result).to.contain('a'); + expect(result.a).to.deep.equal(a); + done(); + }); + + it('parses dates correctly', function (done) { + + var now = new Date(); + expect(Qs.parse({ a: now })).to.deep.equal({ a: now }); + done(); + }); + + it('parses regular expressions correctly', function (done) { + + var re = /^test$/; + expect(Qs.parse({ a: re })).to.deep.equal({ a: re }); + done(); + }); + + it('can allow overwriting prototype properties', function (done) { + + expect(Qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true })).to.deep.equal({ a: { hasOwnProperty: 'b' } }, { prototype: false }); + expect(Qs.parse('hasOwnProperty=b', { allowPrototypes: true })).to.deep.equal({ hasOwnProperty: 'b' }, { prototype: false }); + done(); + }); + + it('can return plain objects', function (done) { + + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + expect(Qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true })).to.deep.equal(expected); + expect(Qs.parse(null, { plainObjects: true })).to.deep.equal(Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a['0'] = 'b'; + expectedArray.a.c = 'd'; + expect(Qs.parse('a[]=b&a[c]=d', { plainObjects: true })).to.deep.equal(expectedArray); + done(); + }); +}); diff --git a/5-3/node_modules/body-parser/node_modules/qs/test/stringify.js b/5-3/node_modules/body-parser/node_modules/qs/test/stringify.js new file mode 100644 index 0000000..53139ff --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/test/stringify.js @@ -0,0 +1,293 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('stringify()', function () { + + it('stringifies a querystring object', function (done) { + + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 })).to.equal('a=1'); + expect(Qs.stringify({ a: 1, b: 2 })).to.equal('a=1&b=2'); + expect(Qs.stringify({ a: 'A_Z' })).to.equal('a=A_Z'); + expect(Qs.stringify({ a: '€' })).to.equal('a=%E2%82%AC'); + expect(Qs.stringify({ a: '' })).to.equal('a=%EE%80%80'); + expect(Qs.stringify({ a: 'א' })).to.equal('a=%D7%90'); + expect(Qs.stringify({ a: '𐐷' })).to.equal('a=%F0%90%90%B7'); + done(); + }); + + it('stringifies a nested object', function (done) { + + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + expect(Qs.stringify({ a: { b: { c: { d: 'e' } } } })).to.equal('a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + done(); + }); + + it('stringifies an array value', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d'); + done(); + }); + + it('omits nulls when asked', function (done) { + + expect(Qs.stringify({ a: 'b', c: null }, { skipNulls: true })).to.equal('a=b'); + done(); + }); + + + it('omits nested nulls when asked', function (done) { + + expect(Qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true })).to.equal('a%5Bb%5D=c'); + done(); + }); + + it('omits array indices when asked', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false })).to.equal('a=b&a=c&a=d'); + done(); + }); + + it('stringifies a nested array value', function (done) { + + expect(Qs.stringify({ a: { b: ['c', 'd'] } })).to.equal('a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + done(); + }); + + it('stringifies an object inside an array', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] })).to.equal('a%5B0%5D%5Bb%5D=c'); + expect(Qs.stringify({ a: [{ b: { c: [1] } }] })).to.equal('a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1'); + done(); + }); + + it('does not omit object keys when indices = false', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] }, { indices: false })).to.equal('a%5Bb%5D=c'); + 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'); + done(); + }); + + it('stringifies an empty value', function (done) { + + expect(Qs.stringify({ a: '' })).to.equal('a='); + expect(Qs.stringify({ a: null }, { strictNullHandling: true })).to.equal('a'); + + expect(Qs.stringify({ a: '', b: '' })).to.equal('a=&b='); + expect(Qs.stringify({ a: null, b: '' }, { strictNullHandling: true })).to.equal('a&b='); + + expect(Qs.stringify({ a: { b: '' } })).to.equal('a%5Bb%5D='); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: true })).to.equal('a%5Bb%5D'); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: false })).to.equal('a%5Bb%5D='); + + done(); + }); + + it('stringifies an empty object', function (done) { + + var obj = Object.create(null); + obj.a = 'b'; + expect(Qs.stringify(obj)).to.equal('a=b'); + done(); + }); + + it('returns an empty string for invalid input', function (done) { + + expect(Qs.stringify(undefined)).to.equal(''); + expect(Qs.stringify(false)).to.equal(''); + expect(Qs.stringify(null)).to.equal(''); + expect(Qs.stringify('')).to.equal(''); + done(); + }); + + it('stringifies an object with an empty object as a child', function (done) { + + var obj = { + a: Object.create(null) + }; + + obj.a.b = 'c'; + expect(Qs.stringify(obj)).to.equal('a%5Bb%5D=c'); + done(); + }); + + it('drops keys with a value of undefined', function (done) { + + expect(Qs.stringify({ a: undefined })).to.equal(''); + + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true })).to.equal('a%5Bc%5D'); + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false })).to.equal('a%5Bc%5D='); + expect(Qs.stringify({ a: { b: undefined, c: '' } })).to.equal('a%5Bc%5D='); + done(); + }); + + it('url encodes values', function (done) { + + expect(Qs.stringify({ a: 'b c' })).to.equal('a=b%20c'); + done(); + }); + + it('stringifies a date', function (done) { + + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + expect(Qs.stringify({ a: now })).to.equal(str); + done(); + }); + + it('stringifies the weird object from qs', function (done) { + + expect(Qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' })).to.equal('my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + done(); + }); + + it('skips properties that are part of the object prototype', function (done) { + + Object.prototype.crash = 'test'; + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + delete Object.prototype.crash; + done(); + }); + + it('stringifies boolean values', function (done) { + + expect(Qs.stringify({ a: true })).to.equal('a=true'); + expect(Qs.stringify({ a: { b: true } })).to.equal('a%5Bb%5D=true'); + expect(Qs.stringify({ b: false })).to.equal('b=false'); + expect(Qs.stringify({ b: { c: false } })).to.equal('b%5Bc%5D=false'); + done(); + }); + + it('stringifies buffer values', function (done) { + + expect(Qs.stringify({ a: new Buffer('test') })).to.equal('a=test'); + expect(Qs.stringify({ a: { b: new Buffer('test') } })).to.equal('a%5Bb%5D=test'); + done(); + }); + + it('stringifies an object using an alternative delimiter', function (done) { + + expect(Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' })).to.equal('a=b;c=d'); + done(); + }); + + it('doesn\'t blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = Qs.stringify({ a: 'b', c: 'd' }); + global.Buffer = tempBuffer; + expect(result).to.equal('a=b&c=d'); + done(); + }); + + it('selects properties when filter=array', function (done) { + + expect(Qs.stringify({ a: 'b' }, { filter: ['a'] })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 }, { filter: [] })).to.equal(''); + expect(Qs.stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] })).to.equal('a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3'); + done(); + + }); + + it('supports custom representations when filter=function', function (done) { + + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + + calls++; + if (calls === 1) { + expect(prefix).to.be.empty(); + expect(value).to.equal(obj); + } + else if (prefix === 'c') { + return; + } + else if (value instanceof Date) { + expect(prefix).to.equal('e[f]'); + return value.getTime(); + } + return value; + }; + + expect(Qs.stringify(obj, { filter: filterFunc })).to.equal('a=b&e%5Bf%5D=1257894000000'); + expect(calls).to.equal(5); + done(); + + }); + + it('can disable uri encoding', function (done) { + + expect(Qs.stringify({ a: 'b' }, { encode: false })).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } }, { encode: false })).to.equal('a[b]=c'); + expect(Qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false })).to.equal('a=b&c'); + done(); + }); + + it('can sort the keys', function (done) { + + var sort = function alphabeticalSort (a, b) { + + return a.localeCompare(b); + }; + + expect(Qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort : sort })).to.equal('a=c&b=f&z=y'); + expect(Qs.stringify({ a: 'c', z: { j: 'a', i:'b' }, b : 'f' }, { sort : sort })).to.equal('a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a'); + done(); + }); +}); diff --git a/5-3/node_modules/body-parser/node_modules/qs/test/utils.js b/5-3/node_modules/body-parser/node_modules/qs/test/utils.js new file mode 100644 index 0000000..a9a6b52 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/qs/test/utils.js @@ -0,0 +1,28 @@ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Utils = require('../lib/utils'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('merge()', function () { + + it('can merge two objects with the same key', function (done) { + + expect(Utils.merge({ a: 'b' }, { a: 'c' })).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); +}); diff --git a/5-3/node_modules/body-parser/node_modules/raw-body/HISTORY.md b/5-3/node_modules/body-parser/node_modules/raw-body/HISTORY.md new file mode 100644 index 0000000..afca001 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/raw-body/HISTORY.md @@ -0,0 +1,196 @@ +2.1.5 / 2015-11-30 +================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + +2.1.4 / 2015-09-27 +================== + + * Fix masking critical errors from `iconv-lite` + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + +2.1.3 / 2015-09-12 +================== + + * Fix sync callback when attaching data listener causes sync read + - Node.js 0.10 compatibility issue + +2.1.2 / 2015-07-05 +================== + + * Fix error stack traces to skip `makeError` + * deps: iconv-lite@0.4.11 + - Add encoding CESU-8 + +2.1.1 / 2015-06-14 +================== + + * Use `unpipe` module for unpiping requests + +2.1.0 / 2015-05-28 +================== + + * deps: iconv-lite@0.4.10 + - Improved UTF-16 endianness detection + - Leading BOM is now removed when decoding + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + +2.0.2 / 2015-05-21 +================== + + * deps: bytes@2.1.0 + - Slight optimizations + +2.0.1 / 2015-05-10 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + +2.0.0 / 2015-05-08 +================== + + * Return a promise without callback instead of thunk + * deps: bytes@2.0.1 + - units no longer case sensitive when parsing + +1.3.4 / 2015-04-15 +================== + + * Fix hanging callback if request aborts during read + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + +1.3.3 / 2015-02-08 +================== + + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + +1.3.2 / 2015-01-20 +================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + +1.3.1 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + +1.3.0 / 2014-07-20 +================== + + * Fully unpipe the stream on error + - Fixes `Cannot switch to old mode now` error on Node.js 0.10+ + +1.2.3 / 2014-07-20 +================== + + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + +1.2.2 / 2014-06-19 +================== + + * Send invalid encoding error to callback + +1.2.1 / 2014-06-15 +================== + + * deps: iconv-lite@0.4.3 + - Added encodings UTF-16BE and UTF-16 with BOM + +1.2.0 / 2014-06-13 +================== + + * Passing string as `options` interpreted as encoding + * Support all encodings from `iconv-lite` + +1.1.7 / 2014-06-12 +================== + + * use `string_decoder` module from npm + +1.1.6 / 2014-05-27 +================== + + * check encoding for old streams1 + * support node.js < 0.10.6 + +1.1.5 / 2014-05-14 +================== + + * bump bytes + +1.1.4 / 2014-04-19 +================== + + * allow true as an option + * bump bytes + +1.1.3 / 2014-03-02 +================== + + * fix case when length=null + +1.1.2 / 2013-12-01 +================== + + * be less strict on state.encoding check + +1.1.1 / 2013-11-27 +================== + + * add engines + +1.1.0 / 2013-11-27 +================== + + * add err.statusCode and err.type + * allow for encoding option to be true + * pause the stream instead of dumping on error + * throw if the stream's encoding is set + +1.0.1 / 2013-11-19 +================== + + * dont support streams1, throw if dev set encoding + +1.0.0 / 2013-11-17 +================== + + * rename `expected` option to `length` + +0.2.0 / 2013-11-15 +================== + + * republish + +0.1.1 / 2013-11-15 +================== + + * use bytes + +0.1.0 / 2013-11-11 +================== + + * generator support + +0.0.3 / 2013-10-10 +================== + + * update repo + +0.0.2 / 2013-09-14 +================== + + * dump stream on bad headers + * listen to events after defining received and buffers + +0.0.1 / 2013-09-14 +================== + + * Initial release diff --git a/5-3/node_modules/body-parser/node_modules/raw-body/LICENSE b/5-3/node_modules/body-parser/node_modules/raw-body/LICENSE new file mode 100644 index 0000000..86dc7b9 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/raw-body/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2013-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: + +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/5-3/node_modules/body-parser/node_modules/raw-body/README.md b/5-3/node_modules/body-parser/node_modules/raw-body/README.md new file mode 100644 index 0000000..c0e972a --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/raw-body/README.md @@ -0,0 +1,126 @@ +# raw-body + +[![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] + +Gets the entire buffer of a stream either as a `Buffer` or a string. +Validates the stream's length against an expected length and maximum limit. +Ideal for parsing request bodies. + +## API + +```js +var getRawBody = require('raw-body') +``` + +### getRawBody(stream, [options], [callback]) + +**Returns a promise if no callback specified and global `Promise` exists.** + +Options: + +- `length` - The length length of the stream. + If the contents of the stream do not add up to this length, + an `400` error code is returned. +- `limit` - The byte limit of the body. + If the body ends up being larger than this limit, + a `413` error code is returned. +- `encoding` - The requested encoding. + By default, a `Buffer` instance will be returned. + Most likely, you want `utf8`. + You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme). + +You can also pass a string in place of options to just specify the encoding. + +`callback(err, res)`: + +- `err` - the following attributes will be defined if applicable: + + - `limit` - the limit in bytes + - `length` and `expected` - the expected length of the stream + - `received` - the received bytes + - `encoding` - the invalid encoding + - `status` and `statusCode` - the corresponding status code for the error + - `type` - either `entity.too.large`, `request.aborted`, `request.size.invalid`, `stream.encoding.set`, or `encoding.unsupported` + +- `res` - the result, either as a `String` if an encoding was set or a `Buffer` otherwise. + +If an error occurs, the stream will be paused, everything unpiped, +and you are responsible for correctly disposing the stream. +For HTTP requests, no handling is required if you send a response. +For streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks. + +## Examples + +### Simple Express example + +```js +var getRawBody = require('raw-body') +var typer = require('media-typer') + +app.use(function (req, res, next) { + getRawBody(req, { + length: req.headers['content-length'], + limit: '1mb', + encoding: typer.parse(req.headers['content-type']).parameters.charset + }, function (err, string) { + if (err) return next(err) + req.text = string + next() + }) +}) +``` + +### Simple Koa example + +```js +app.use(function* (next) { + var string = yield getRawBody(this.req, { + length: this.length, + limit: '1mb', + encoding: this.charset + }) +}) +``` + +### Using as a promise + +To use this library as a promise, simply omit the `callback` and a promise is +returned, provided that a global `Promise` is defined. + +```js +var getRawBody = require('raw-body') +var http = require('http') + +var server = http.createServer(function (req, res) { + getRawBody(req) + .then(function (buf) { + res.statusCode = 200 + res.end(buf.length + ' bytes submitted') + }) + .catch(function (err) { + res.statusCode = 500 + res.end(err.message) + }) +}) + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/raw-body.svg +[npm-url]: https://npmjs.org/package/raw-body +[node-version-image]: https://img.shields.io/node/v/raw-body.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/raw-body/master.svg +[travis-url]: https://travis-ci.org/stream-utils/raw-body +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master +[downloads-image]: https://img.shields.io/npm/dm/raw-body.svg +[downloads-url]: https://npmjs.org/package/raw-body diff --git a/5-3/node_modules/body-parser/node_modules/raw-body/index.js b/5-3/node_modules/body-parser/node_modules/raw-body/index.js new file mode 100644 index 0000000..e0c85bb --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/raw-body/index.js @@ -0,0 +1,321 @@ +/*! + * raw-body + * Copyright(c) 2013-2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var iconv = require('iconv-lite') +var unpipe = require('unpipe') + +/** + * Module exports. + * @public + */ + +module.exports = getRawBody + +/** + * Module variables. + * @private + */ + +var iconvEncodingMessageRegExp = /^Encoding not recognized: / + +/** + * Get the decoder for a given encoding. + * + * @param {string} encoding + * @private + */ + +function getDecoder(encoding) { + if (!encoding) return null + + try { + return iconv.getDecoder(encoding) + } catch (e) { + // error getting decoder + if (!iconvEncodingMessageRegExp.test(e.message)) throw e + + // the encoding was not found + throw createError(415, 'specified encoding unsupported', 'encoding.unsupported', { + encoding: encoding + }) + } +} + +/** + * Get the raw body of a stream (typically HTTP). + * + * @param {object} stream + * @param {object|string|function} [options] + * @param {function} [callback] + * @public + */ + +function getRawBody(stream, options, callback) { + var done = callback + var opts = options || {} + + if (options === true || typeof options === 'string') { + // short cut for encoding + opts = { + encoding: options + } + } + + if (typeof options === 'function') { + done = options + opts = {} + } + + // validate callback is a function, if provided + if (done !== undefined && typeof done !== 'function') { + throw new TypeError('argument callback must be a function') + } + + // require the callback without promises + if (!done && !global.Promise) { + throw new TypeError('argument callback is required') + } + + // get encoding + var encoding = opts.encoding !== true + ? opts.encoding + : 'utf-8' + + // convert the limit to an integer + var limit = bytes.parse(opts.limit) + + // convert the expected length to an integer + var length = opts.length != null && !isNaN(opts.length) + ? parseInt(opts.length, 10) + : null + + if (done) { + // classic callback style + return readStream(stream, encoding, length, limit, done) + } + + return new Promise(function executor(resolve, reject) { + readStream(stream, encoding, length, limit, function onRead(err, buf) { + if (err) return reject(err) + resolve(buf) + }) + }) +} + +/** + * Halt a stream. + * + * @param {Object} stream + * @private + */ + +function halt(stream) { + // unpipe everything from the stream + unpipe(stream) + + // pause stream + if (typeof stream.pause === 'function') { + stream.pause() + } +} + +/** + * Make a serializable error object. + * + * To create serializable errors you must re-set message so + * that it is enumerable and you must re configure the type + * property so that is writable and enumerable. + * + * @param {number} status + * @param {string} message + * @param {string} type + * @param {object} props + * @private + */ + +function createError(status, message, type, props) { + var error = new Error() + + // capture stack trace + Error.captureStackTrace(error, createError) + + // set free-form properties + for (var prop in props) { + error[prop] = props[prop] + } + + // set message + error.message = message + + // set status + error.status = status + error.statusCode = status + + // set type + Object.defineProperty(error, 'type', { + value: type, + enumerable: true, + writable: true, + configurable: true + }) + + return error +} + +/** + * Read the data from the stream. + * + * @param {object} stream + * @param {string} encoding + * @param {number} length + * @param {number} limit + * @param {function} callback + * @public + */ + +function readStream(stream, encoding, length, limit, callback) { + var complete = false + var sync = true + + // check the length and limit options. + // note: we intentionally leave the stream paused, + // so users should handle the stream themselves. + if (limit !== null && length !== null && length > limit) { + return done(createError(413, 'request entity too large', 'entity.too.large', { + expected: length, + length: length, + limit: limit + })) + } + + // streams1: assert request encoding is buffer. + // streams2+: assert the stream encoding is buffer. + // stream._decoder: streams1 + // state.encoding: streams2 + // state.decoder: streams2, specifically < 0.10.6 + var state = stream._readableState + if (stream._decoder || (state && (state.encoding || state.decoder))) { + // developer error + return done(createError(500, 'stream encoding should not be set', 'stream.encoding.set')) + } + + var received = 0 + var decoder + + try { + decoder = getDecoder(encoding) + } catch (err) { + return done(err) + } + + var buffer = decoder + ? '' + : [] + + // attach listeners + stream.on('aborted', onAborted) + stream.on('close', cleanup) + stream.on('data', onData) + stream.on('end', onEnd) + stream.on('error', onEnd) + + // mark sync section complete + sync = false + + function done() { + var args = new Array(arguments.length) + + // copy arguments + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + // mark complete + complete = true + + if (sync) { + process.nextTick(invokeCallback) + } else { + invokeCallback() + } + + function invokeCallback() { + cleanup() + + if (args[0]) { + // halt the stream on error + halt(stream) + } + + callback.apply(null, args) + } + } + + function onAborted() { + if (complete) return + + done(createError(400, 'request aborted', 'request.aborted', { + code: 'ECONNABORTED', + expected: length, + length: length, + received: received + })) + } + + function onData(chunk) { + if (complete) return + + received += chunk.length + decoder + ? buffer += decoder.write(chunk) + : buffer.push(chunk) + + if (limit !== null && received > limit) { + done(createError(413, 'request entity too large', 'entity.too.large', { + limit: limit, + received: received + })) + } + } + + function onEnd(err) { + if (complete) return + if (err) return done(err) + + if (length !== null && received !== length) { + done(createError(400, 'request size did not match content length', 'request.size.invalid', { + expected: length, + length: length, + received: received + })) + } else { + var string = decoder + ? buffer + (decoder.end() || '') + : Buffer.concat(buffer) + cleanup() + done(null, string) + } + } + + function cleanup() { + buffer = null + + stream.removeListener('aborted', onAborted) + stream.removeListener('data', onData) + stream.removeListener('end', onEnd) + stream.removeListener('error', onEnd) + stream.removeListener('close', cleanup) + } +} diff --git a/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/HISTORY.md b/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/HISTORY.md new file mode 100644 index 0000000..85e0f8d --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/LICENSE b/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/LICENSE new file mode 100644 index 0000000..aed0138 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/README.md b/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/README.md new file mode 100644 index 0000000..e536ad2 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/index.js b/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/index.js new file mode 100644 index 0000000..15c3d97 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/package.json b/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/package.json new file mode 100644 index 0000000..5381079 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/raw-body/node_modules/unpipe/package.json @@ -0,0 +1,59 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/unpipe.git" + }, + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "d2df901c06487430e78dca62b6edb8bb2fc5e99d", + "bugs": { + "url": "https://github.com/stream-utils/unpipe/issues" + }, + "homepage": "https://github.com/stream-utils/unpipe", + "_id": "unpipe@1.0.0", + "_shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "_from": "unpipe@1.0.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "tarball": "http://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/raw-body/package.json b/5-3/node_modules/body-parser/node_modules/raw-body/package.json new file mode 100644 index 0000000..dc97a1a --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/raw-body/package.json @@ -0,0 +1,81 @@ +{ + "name": "raw-body", + "description": "Get and validate the raw body of a readable stream.", + "version": "2.1.5", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Raynos", + "email": "raynos2@gmail.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/raw-body.git" + }, + "dependencies": { + "bytes": "2.2.0", + "iconv-lite": "0.4.13", + "unpipe": "1.0.0" + }, + "devDependencies": { + "bluebird": "3.0.5", + "istanbul": "0.4.1", + "mocha": "2.3.4", + "readable-stream": "2.0.4", + "through2": "2.0.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "mocha --trace-deprecation --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --trace-deprecation --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --trace-deprecation --reporter spec --check-leaks test/" + }, + "gitHead": "0467d63d4e66c212ec08bfc826ba565be15c523a", + "bugs": { + "url": "https://github.com/stream-utils/raw-body/issues" + }, + "homepage": "https://github.com/stream-utils/raw-body", + "_id": "raw-body@2.1.5", + "_shasum": "8be8f09ddefd0d72ad99d883ab7f0cc350420956", + "_from": "raw-body@>=2.1.5 <2.2.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" + } + ], + "dist": { + "shasum": "8be8f09ddefd0d72ad99d883ab7f0cc350420956", + "tarball": "http://registry.npmjs.org/raw-body/-/raw-body-2.1.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.1.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/type-is/HISTORY.md b/5-3/node_modules/body-parser/node_modules/type-is/HISTORY.md new file mode 100644 index 0000000..e10b426 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/HISTORY.md @@ -0,0 +1,192 @@ +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/5-3/node_modules/body-parser/node_modules/type-is/LICENSE b/5-3/node_modules/body-parser/node_modules/type-is/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +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: + +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/5-3/node_modules/body-parser/node_modules/type-is/README.md b/5-3/node_modules/body-parser/node_modules/type-is/README.md new file mode 100644 index 0000000..7a754be --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/README.md @@ -0,0 +1,136 @@ +# type-is + +[![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] + +Infer the content-type of a request. + +### Install + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var is = require('type-is') + +http.createServer(function (req, res) { + var istext = is(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### type = is(request, types) + +`request` is the node HTTP request. `types` is an array of types. + +```js +// req.headers.content-type = 'application/json' + +is(req, ['json']) // 'json' +is(req, ['html', 'json']) // 'json' +is(req, ['application/*']) // 'application/json' +is(req, ['application/json']) // 'application/json' + +is(req, ['html']) // false +``` + +### is.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existance works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + +```js +if (is.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### type = is.is(mediaType, types) + +`mediaType` is the [media type](https://tools.ietf.org/html/rfc6838) string. `types` is an array of types. + +```js +var mediaType = 'application/json' + +is.is(mediaType, ['json']) // 'json' +is.is(mediaType, ['html', 'json']) // 'json' +is.is(mediaType, ['application/*']) // 'application/json' +is.is(mediaType, ['application/json']) // 'application/json' + +is.is(mediaType, ['html']) // false +``` + +### Each type can be: + +- An extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` 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 or the content type is invalid. + +`null` will be returned if the request does not have a body. + +## Examples + +#### Example body parser + +```js +var is = require('type-is'); + +function bodyParser(req, res, next) { + if (!is.hasBody(req)) { + return next() + } + + switch (is(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + break + case 'json': + // parse json body + throw new Error('implement json body parsing') + break + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + break + default: + // 415 error code + res.statusCode = 415 + res.end() + return + } +} +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: https://nodejs.org/en/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[downloads-image]: https://img.shields.io/npm/dm/type-is.svg +[downloads-url]: https://npmjs.org/package/type-is diff --git a/5-3/node_modules/body-parser/node_modules/type-is/index.js b/5-3/node_modules/body-parser/node_modules/type-is/index.js new file mode 100644 index 0000000..ca2962e --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/index.js @@ -0,0 +1,262 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var typer = require('media-typer') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis(value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody(req) { + return req.headers['transfer-encoding'] !== undefined + || !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +function typeofrequest(req, types_) { + var types = types_ + + // no body + if (!hasbody(req)) { + return null + } + + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @private + */ + +function normalize(type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @private + */ + +function mimeMatch(expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // 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) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +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 { + return normalizeType(value) + } catch (err) { + return null + } +} diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/HISTORY.md b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/HISTORY.md new file mode 100644 index 0000000..62c2003 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/HISTORY.md @@ -0,0 +1,22 @@ +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/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/LICENSE b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/README.md b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/README.md new file mode 100644 index 0000000..d8df623 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/README.md @@ -0,0 +1,81 @@ +# 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/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/index.js b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/index.js new file mode 100644 index 0000000..07f7295 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/index.js @@ -0,0 +1,270 @@ +/*! + * 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/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/package.json b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/package.json new file mode 100644 index 0000000..e0f796d --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/media-typer/package.json @@ -0,0 +1,58 @@ +{ + "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": "git+https://github.com/jshttp/media-typer.git" + }, + "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/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/HISTORY.md b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..61b54b4 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/HISTORY.md @@ -0,0 +1,183 @@ +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +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 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/LICENSE b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/README.md b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/README.md new file mode 100644 index 0000000..e26295d --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/README.md @@ -0,0 +1,103 @@ +# mime-types + +[![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] + +The ultimate javascript content-type utility. + +Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, + so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db) +- No `.define()` functionality + +Otherwise, the API is compatible. + +## Install + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://github.com/jshttp/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[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/node/v/mime-types.svg +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/index.js b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/index.js new file mode 100644 index 0000000..f7008b2 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/index.js @@ -0,0 +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 + +/** + * 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) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..41a667a --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -0,0 +1,306 @@ +1.21.0 / 2016-01-06 +=================== + + * Add `application/emergencycalldata.comment+xml` + * Add `application/emergencycalldata.deviceinfo+xml` + * Add `application/emergencycalldata.providerinfo+xml` + * Add `application/emergencycalldata.serviceinfo+xml` + * Add `application/emergencycalldata.subscriberinfo+xml` + * Add `application/vnd.filmit.zfc` + * Add `application/vnd.google-apps.document` + * Add `application/vnd.google-apps.presentation` + * Add `application/vnd.google-apps.spreadsheet` + * Add `application/vnd.mapbox-vector-tile` + * Add `application/vnd.ms-printdevicecapabilities+xml` + * Add `application/vnd.ms-windows.devicepairing` + * Add `application/vnd.ms-windows.nwprinting.oob` + * Add `application/vnd.tml` + * Add `audio/evs` + +1.20.0 / 2015-11-10 +=================== + + * Add `application/cdni` + * Add `application/csvm+json` + * Add `application/rfc+xml` + * Add `application/vnd.3gpp.access-transfer-events+xml` + * Add `application/vnd.3gpp.srvcc-ext+xml` + * Add `application/vnd.ms-windows.wsd.oob` + * Add `application/vnd.oxli.countgraph` + * Add `application/vnd.pagerduty+json` + * Add `text/x-suse-ymp` + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.3gpp-prose-pc3ch+xml` + * Add `application/vnd.3gpp.srvcc-info+xml` + * Add `application/vnd.apple.pkpass` + * Add `application/vnd.drive+json` + +1.18.0 / 2015-09-03 +=================== + + * Add `application/pkcs12` + * Add `application/vnd.3gpp-prose+xml` + * Add `application/vnd.3gpp.mid-call+xml` + * Add `application/vnd.3gpp.state-and-event-info+xml` + * Add `application/vnd.anki` + * Add `application/vnd.firemonkeys.cloudcell` + * Add `application/vnd.openblox.game+xml` + * Add `application/vnd.openblox.game-binary` + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +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 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md new file mode 100644 index 0000000..7662440 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md @@ -0,0 +1,82 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +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 + +```bash +npm install mime-db +``` + +### 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 +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + 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 can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +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 +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[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 +[node-url]: http://nodejs.org/download/ diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json new file mode 100644 index 0000000..412ba9e --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json @@ -0,0 +1,6552 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana" + }, + "application/3gpp-ims+xml": { + "source": "iana" + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana" + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana" + }, + "application/bacnet-xdd+zip": { + "source": "iana" + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana" + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana" + }, + "application/ccxml+xml": { + "source": "iana", + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana" + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana" + }, + "application/cellml+xml": { + "source": "iana" + }, + "application/cfw": { + "source": "iana" + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana" + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana" + }, + "application/cstadata+xml": { + "source": "iana" + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "extensions": ["mdp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana" + }, + "application/dicom": { + "source": "iana" + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana" + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/emergencycalldata.comment+xml": { + "source": "iana" + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana" + }, + "application/emma+xml": { + "source": "iana", + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana" + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana" + }, + "application/epub+zip": { + "source": "iana", + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana" + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false, + "extensions": ["woff"] + }, + "application/font-woff2": { + "compressible": false, + "extensions": ["woff2"] + }, + "application/framework-attributes+xml": { + "source": "iana" + }, + "application/gml+xml": { + "source": "apache", + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana" + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana" + }, + "application/ibe-pkg-reply+xml": { + "source": "iana" + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana" + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana" + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana" + }, + "application/kpml-response+xml": { + "source": "iana" + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana" + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana" + }, + "application/mathml-presentation+xml": { + "source": "iana" + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana" + }, + "application/mbms-deregister+xml": { + "source": "iana" + }, + "application/mbms-envelope+xml": { + "source": "iana" + }, + "application/mbms-msk+xml": { + "source": "iana" + }, + "application/mbms-msk-response+xml": { + "source": "iana" + }, + "application/mbms-protection-description+xml": { + "source": "iana" + }, + "application/mbms-reception-report+xml": { + "source": "iana" + }, + "application/mbms-register+xml": { + "source": "iana" + }, + "application/mbms-register-response+xml": { + "source": "iana" + }, + "application/mbms-schedule+xml": { + "source": "iana" + }, + "application/mbms-user-service-description+xml": { + "source": "iana" + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana" + }, + "application/media_control+xml": { + "source": "iana" + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mods+xml": { + "source": "iana", + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana" + }, + "application/mrb-publish+xml": { + "source": "iana" + }, + "application/msc-ivr+xml": { + "source": "iana" + }, + "application/msc-mixer+xml": { + "source": "iana" + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "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", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana" + }, + "application/parityfec": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana" + }, + "application/pidf-diff+xml": { + "source": "iana" + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana" + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/provenance+xml": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana" + }, + "application/pskc+xml": { + "source": "iana", + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf"] + }, + "application/reginfo+xml": { + "source": "iana", + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana" + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana" + }, + "application/rls-services+xml": { + "source": "iana", + "extensions": ["rs"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana" + }, + "application/samlmetadata+xml": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana" + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/sep+xml": { + "source": "iana" + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana" + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana" + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "extensions": ["ssml"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/ttml+xml": { + "source": "iana" + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana" + }, + "application/urc-ressheet+xml": { + "source": "iana" + }, + "application/urc-targetdesc+xml": { + "source": "iana" + }, + "application/urc-uisocketdesc+xml": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana" + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana" + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana" + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana" + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "extensions": ["mpkg"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avistar+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "extensions": ["cdxml"] + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana" + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana" + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana" + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume-movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana" + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana" + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana" + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana" + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana" + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana" + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana" + }, + "application/vnd.etsi.cug+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana" + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana" + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana" + }, + "application/vnd.etsi.sci+xml": { + "source": "iana" + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana" + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana" + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana" + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana" + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana" + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana" + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana" + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana" + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana" + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+xml": { + "source": "iana", + "extensions": ["lasxml"] + }, + "application/vnd.liberty-request+xml": { + "source": "iana" + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana" + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana" + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana" + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache" + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana" + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana" + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana" + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana" + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana" + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana" + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana" + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana" + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana" + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana" + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana" + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana" + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana" + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana" + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana" + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana" + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana" + }, + "application/vnd.omads-email+xml": { + "source": "iana" + }, + "application/vnd.omads-file+xml": { + "source": "iana" + }, + "application/vnd.omads-folder+xml": { + "source": "iana" + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana" + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "apache", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "apache", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "apache", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana" + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana" + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos+xml": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "apache" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana" + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana" + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana" + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana" + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana" + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana" + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana" + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana" + }, + "application/vnd.wv.ssp+xml": { + "source": "iana" + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana" + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "extensions": ["vxml"] + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/watcherinfo+xml": { + "source": "iana" + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-otf": { + "source": "apache", + "compressible": true, + "extensions": ["otf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-ttf": { + "source": "apache", + "compressible": true, + "extensions": ["ttf","ttc"] + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "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, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "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, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana" + }, + "application/xaml+xml": { + "source": "apache", + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana" + }, + "application/xcap-caps+xml": { + "source": "iana" + }, + "application/xcap-diff+xml": { + "source": "iana", + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana" + }, + "application/xcap-error+xml": { + "source": "iana" + }, + "application/xcap-ns+xml": { + "source": "iana" + }, + "application/xcon-conference-info+xml": { + "source": "iana" + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana" + }, + "application/xenc+xml": { + "source": "iana", + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache" + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana" + }, + "application/xmpp+xml": { + "source": "iana" + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yin+xml": { + "source": "iana", + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana" + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4a","m4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/opentype": { + "compressible": true, + "extensions": ["otf"] + }, + "image/bmp": { + "source": "apache", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/fits": { + "source": "iana" + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jp2": { + "source": "iana" + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana" + }, + "image/jpx": { + "source": "iana" + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana" + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana" + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tiff","tif"] + }, + "image/tiff-fx": { + "source": "iana" + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana" + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana" + }, + "image/vnd.valve.source.texture": { + "source": "iana" + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "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"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana" + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana" + }, + "message/global-delivery-status": { + "source": "iana" + }, + "message/global-disposition-notification": { + "source": "iana" + }, + "message/global-headers": { + "source": "iana" + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana" + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana" + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hjson": { + "extensions": ["hjson"] + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana" + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["markdown","md","mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "apache" + }, + "video/3gpp": { + "source": "apache", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "apache" + }, + "video/3gpp2": { + "source": "apache", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "apache" + }, + "video/bt656": { + "source": "apache" + }, + "video/celb": { + "source": "apache" + }, + "video/dv": { + "source": "apache" + }, + "video/h261": { + "source": "apache", + "extensions": ["h261"] + }, + "video/h263": { + "source": "apache", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "apache" + }, + "video/h263-2000": { + "source": "apache" + }, + "video/h264": { + "source": "apache", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "apache" + }, + "video/h264-svc": { + "source": "apache" + }, + "video/jpeg": { + "source": "apache", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "apache" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "apache", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "apache" + }, + "video/mp2p": { + "source": "apache" + }, + "video/mp2t": { + "source": "apache", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "apache", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "apache" + }, + "video/mpeg": { + "source": "apache", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "apache" + }, + "video/mpv": { + "source": "apache" + }, + "video/nv": { + "source": "apache" + }, + "video/ogg": { + "source": "apache", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "apache" + }, + "video/pointer": { + "source": "apache" + }, + "video/quicktime": { + "source": "apache", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raw": { + "source": "apache" + }, + "video/rtp-enc-aescm128": { + "source": "apache" + }, + "video/rtx": { + "source": "apache" + }, + "video/smpte292m": { + "source": "apache" + }, + "video/ulpfec": { + "source": "apache" + }, + "video/vc1": { + "source": "apache" + }, + "video/vnd.cctv": { + "source": "apache" + }, + "video/vnd.dece.hd": { + "source": "apache", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "apache", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "apache" + }, + "video/vnd.dece.pd": { + "source": "apache", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "apache", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "apache", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "apache" + }, + "video/vnd.directv.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dvb.file": { + "source": "apache", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "apache", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "apache" + }, + "video/vnd.motorola.video": { + "source": "apache" + }, + "video/vnd.motorola.videop": { + "source": "apache" + }, + "video/vnd.mpegurl": { + "source": "apache", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "apache", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "apache" + }, + "video/vnd.nokia.videovoip": { + "source": "apache" + }, + "video/vnd.objectvideo": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "apache" + }, + "video/vnd.sealed.mpeg4": { + "source": "apache" + }, + "video/vnd.sealed.swf": { + "source": "apache" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "apache" + }, + "video/vnd.uvvu.mp4": { + "source": "apache", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "apache", + "extensions": ["viv"] + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json new file mode 100644 index 0000000..e6c9732 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json @@ -0,0 +1,94 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.21.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "devDependencies": { + "bluebird": "3.1.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "1.0.1", + "gnode": "0.1.1", + "istanbul": "0.4.1", + "mocha": "1.21.5", + "raw-body": "2.1.5", + "stream-to-array": "2.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "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": "9ab92f0a912a602408a64db5741dfef6f82c597f", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "homepage": "https://github.com/jshttp/mime-db", + "_id": "mime-db@1.21.0", + "_shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "_from": "mime-db@>=1.21.0 <1.22.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" + } + ], + "dist": { + "shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/package.json b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/package.json new file mode 100644 index 0000000..d1a5ffa --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/node_modules/mime-types/package.json @@ -0,0 +1,84 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "dependencies": { + "mime-db": "~1.21.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec test/test.js", + "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": "329f1c77e1a77c8fac59b15038e3808e9e314d96", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "homepage": "https://github.com/jshttp/mime-types", + "_id": "mime-types@2.1.9", + "_shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "_from": "mime-types@>=2.1.6 <2.2.0", + "_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" + } + ], + "dist": { + "shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/node_modules/type-is/package.json b/5-3/node_modules/body-parser/node_modules/type-is/package.json new file mode 100644 index 0000000..cae6789 --- /dev/null +++ b/5-3/node_modules/body-parser/node_modules/type-is/package.json @@ -0,0 +1,81 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "1.6.11", + "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": "git+https://github.com/jshttp/type-is.git" + }, + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.9" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "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/" + }, + "keywords": [ + "content", + "type", + "checking" + ], + "gitHead": "8e60e3e78aef84928e0e6c09da950f6950adcdd2", + "bugs": { + "url": "https://github.com/jshttp/type-is/issues" + }, + "homepage": "https://github.com/jshttp/type-is", + "_id": "type-is@1.6.11", + "_shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "_from": "type-is@>=1.6.10 <1.7.0", + "_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": "ritch", + "email": "skawful@gmail.com" + } + ], + "dist": { + "shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "tarball": "http://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/body-parser/package.json b/5-3/node_modules/body-parser/package.json new file mode 100644 index 0000000..d9e0989 --- /dev/null +++ b/5-3/node_modules/body-parser/package.json @@ -0,0 +1,99 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "1.14.2", + "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": "git+https://github.com/expressjs/body-parser.git" + }, + "dependencies": { + "bytes": "2.2.0", + "content-type": "~1.0.1", + "debug": "~2.2.0", + "depd": "~1.1.0", + "http-errors": "~1.3.1", + "iconv-lite": "0.4.13", + "on-finished": "~2.3.0", + "qs": "5.2.0", + "raw-body": "~2.1.5", + "type-is": "~1.6.10" + }, + "devDependencies": { + "istanbul": "0.4.1", + "methods": "~1.1.1", + "mocha": "2.3.4", + "supertest": "1.1.0" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/" + }, + "gitHead": "ef5d85d8344f08b21f70a7d90082e7eea3ccdf99", + "bugs": { + "url": "https://github.com/expressjs/body-parser/issues" + }, + "homepage": "https://github.com/expressjs/body-parser", + "_id": "body-parser@1.14.2", + "_shasum": "1015cb1fe2c443858259581db53332f8d0cf50f9", + "_from": "body-parser@*", + "_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": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "1015cb1fe2c443858259581db53332f8d0cf50f9", + "tarball": "http://registry.npmjs.org/body-parser/-/body-parser-1.14.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.14.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/History.md b/5-3/node_modules/express/History.md new file mode 100644 index 0000000..c72241b --- /dev/null +++ b/5-3/node_modules/express/History.md @@ -0,0 +1,3062 @@ +4.13.4 / 2016-01-21 +=================== + + * deps: content-disposition@0.5.1 + - perf: enable strict mode + * deps: cookie@0.1.5 + - Throw on invalid values provided to `serialize` + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: finalhandler@0.4.1 + - deps: escape-html@~1.0.3 + * deps: merge-descriptors@1.0.1 + - perf: enable strict mode + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + * deps: proxy-addr@~1.0.10 + - deps: ipaddr.js@1.0.5 + - perf: enable strict mode + * deps: range-parser@~1.0.3 + - perf: enable strict mode + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + * deps: serve-static@~1.10.2 + - deps: escape-html@~1.0.3 + - deps: parseurl@~1.3.0 + - deps: send@0.13.1 + +4.13.3 / 2015-08-02 +=================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + +4.13.2 / 2015-07-31 +=================== + + * deps: accepts@~1.2.12 + - deps: mime-types@~2.1.4 + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +4.13.1 / 2015-07-05 +=================== + + * deps: accepts@~1.2.10 + - deps: mime-types@~2.1.2 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +4.13.0 / 2015-06-20 +=================== + + * Add settings to debug output + * Fix `res.format` error when only `default` provided + * Fix issue where `next('route')` in `app.param` would incorrectly skip values + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * Simplify `res.cookie` to call `res.append` + * Use `array-flatten` module for flattening arrays + * deps: accepts@~1.2.9 + - deps: mime-types@~2.1.1 + - perf: avoid argument reassignment & argument slice + - perf: avoid negotiator recursive construction + - perf: enable strict mode + - perf: remove unnecessary bitwise operator + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: finalhandler@0.4.0 + - Fix a false-positive when unpiping in Node.js 0.8 + - Support `statusCode` property on `Error` objects + - Use `unpipe` module for unpiping requests + - deps: escape-html@1.0.2 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: path-to-regexp@0.1.6 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * deps: serve-static@~1.10.0 + - Add `fallthrough` option + - Fix reading options from options prototype + - Improve the default redirect response headers + - Malformed URLs now `next()` instead of 400 + - deps: escape-html@1.0.2 + - deps: send@0.13.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: isolate `app.render` try block + * perf: remove argument reassignments in application + * perf: remove argument reassignments in request prototype + * perf: remove argument reassignments in response prototype + * perf: remove argument reassignments in routing + * perf: remove argument reassignments in `View` + * perf: skip attempting to decode zero length string + * perf: use saved reference to `http.STATUS_CODES` + +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 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * 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 + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * 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 + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw un-catchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.21.2 / 2015-07-31 +=================== + + * deps: connect@2.30.2 + - deps: body-parser@~1.13.3 + - deps: compression@~1.5.2 + - deps: errorhandler@~1.4.2 + - deps: method-override@~2.3.5 + - deps: serve-index@~1.7.2 + - deps: type-is@~1.6.6 + - deps: vhost@~3.0.1 + * deps: vary@~1.0.1 + - Fix setting empty header from empty `field` + - perf: enable strict mode + - perf: remove argument reassignments + +3.21.1 / 2015-07-05 +=================== + + * deps: basic-auth@~1.0.3 + * deps: connect@2.30.1 + - deps: body-parser@~1.13.2 + - deps: compression@~1.5.1 + - deps: errorhandler@~1.4.1 + - deps: morgan@~1.6.1 + - deps: pause@0.1.0 + - deps: qs@4.0.0 + - deps: serve-index@~1.7.1 + - deps: type-is@~1.6.4 + +3.21.0 / 2015-06-18 +=================== + + * deps: basic-auth@1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: connect@2.30.0 + - deps: body-parser@~1.13.1 + - deps: bytes@2.1.0 + - deps: compression@~1.5.0 + - deps: cookie@0.1.3 + - deps: cookie-parser@~1.3.5 + - deps: csurf@~1.8.3 + - deps: errorhandler@~1.4.0 + - deps: express-session@~1.11.3 + - deps: finalhandler@0.4.0 + - deps: fresh@0.3.0 + - deps: morgan@~1.6.0 + - deps: serve-favicon@~2.3.0 + - deps: serve-index@~1.7.0 + - deps: serve-static@~1.10.0 + - deps: type-is@~1.6.3 + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: mkdirp@0.5.1 + - Work in global strict mode + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + +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 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * 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 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes charset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Closes #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delimited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using using charset utf-8 + * Fixed show-exceptions page, now using using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie complation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'. + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error response support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independent specs for those who cant build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/5-3/node_modules/express/LICENSE b/5-3/node_modules/express/LICENSE new file mode 100644 index 0000000..aa927e4 --- /dev/null +++ b/5-3/node_modules/express/LICENSE @@ -0,0 +1,24 @@ +(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 +'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/5-3/node_modules/express/Readme.md b/5-3/node_modules/express/Readme.md new file mode 100644 index 0000000..6e08454 --- /dev/null +++ b/5-3/node_modules/express/Readme.md @@ -0,0 +1,138 @@ +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) + + Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). + + [![NPM Version][npm-image]][npm-url] + [![NPM Downloads][downloads-image]][downloads-url] + [![Linux Build][travis-image]][travis-url] + [![Windows Build][appveyor-image]][appveyor-url] + [![Test Coverage][coveralls-image]][coveralls-url] + +```js +var express = require('express') +var app = express() + +app.get('/', function (req, res) { + res.send('Hello World') +}) + +app.listen(3000) +``` + +## Installation + +```bash +$ npm install express +``` + +## Features + + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly + +## Docs & Community + + * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC + * [Github Organization](https://github.com/expressjs) for Official Middleware & Modules + * [Google Group](https://groups.google.com/group/express-js) for discussion + * [Gitter](https://gitter.im/expressjs/express) for support and discussion + * [Русскоязычная документация](http://jsman.ru/express/) + +###Security Issues + +If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). + +## Quick Start + + 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: + + Install the executable. The executable's major version will match Express's: + +```bash +$ npm install -g express-generator@4 +``` + + Create the app: + +```bash +$ express /tmp/foo && cd /tmp/foo +``` + + Install dependencies: + +```bash +$ npm install +``` + + Start the server: + +```bash +$ npm start +``` + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, web sites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), + you can quickly craft your perfect framework. + +## Examples + + To view the examples, clone the Express repo and install the dependencies: + +```bash +$ git clone git://github.com/expressjs/express.git --depth 1 +$ cd express +$ npm install +``` + + Then run whichever example you want: + +```bash +$ node examples/content-negotiation +``` + +## Tests + + To run the test suite, first install the dependencies, then run `npm test`: + +```bash +$ npm install +$ npm test +``` + +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) [![TJ's Gratipay][gratipay-image-visionmedia]][gratipay-url-visionmedia] + +The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) [![Doug's Gratipay][gratipay-image-dougwilson]][gratipay-url-dougwilson] + +[List of all contributors](https://github.com/expressjs/express/graphs/contributors) + +## License + + [MIT](LICENSE) + +[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 +[downloads-url]: https://npmjs.org/package/express +[travis-image]: https://img.shields.io/travis/expressjs/express/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/express +[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/expressjs/express/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master +[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 +[gratipay-url-dougwilson]: https://gratipay.com/dougwilson/ diff --git a/5-3/node_modules/express/index.js b/5-3/node_modules/express/index.js new file mode 100644 index 0000000..d219b0c --- /dev/null +++ b/5-3/node_modules/express/index.js @@ -0,0 +1,11 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +module.exports = require('./lib/express'); diff --git a/5-3/node_modules/express/lib/application.js b/5-3/node_modules/express/lib/application.js new file mode 100644 index 0000000..0ee4def --- /dev/null +++ b/5-3/node_modules/express/lib/application.js @@ -0,0 +1,643 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var finalhandler = require('finalhandler'); +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var merge = require('utils-merge'); +var resolve = require('path').resolve; +var slice = Array.prototype.slice; + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Variable for trust proxy inheritance back-compat + * @private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ + +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; + + this.defaultConfiguration(); +}; + +/** + * Initialize application configuration. + * @private + */ + +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + 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); + + 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; + this.settings.__proto__ = parent.settings; + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; + +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ + +app.handle = function handle(req, res, callback) { + var router = this._router; + + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ + +app.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires middleware functions'); + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + req.__proto__ = orig.request; + res.__proto__ = orig.response; + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } + + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; + + // store engine + this.engines[extension] = fn; + + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.param = function param(name, fn) { + this.lazyrouter(); + + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } + + return this; + } + + this._router.param(name, fn); + + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge app.locals + merge(renderOptions, this.locals); + + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } + + // merge options + merge(renderOptions, opts); + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} diff --git a/5-3/node_modules/express/lib/express.js b/5-3/node_modules/express/lib/express.js new file mode 100644 index 0000000..540c8be --- /dev/null +++ b/5-3/node_modules/express/lib/express.js @@ -0,0 +1,103 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + app.request = { __proto__: req, app: app }; + app.response = { __proto__: res, app: app }; + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.query = require('./middleware/query'); +exports.static = require('serve-static'); + +/** + * Replace removed middleware with an appropriate error message. + */ + +[ + 'json', + 'urlencoded', + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache', +].forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/5-3/node_modules/express/lib/middleware/init.js b/5-3/node_modules/express/lib/middleware/init.js new file mode 100644 index 0000000..f3119ed --- /dev/null +++ b/5-3/node_modules/express/lib/middleware/init.js @@ -0,0 +1,36 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ + +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; + + req.__proto__ = app.request; + res.__proto__ = app.response; + + res.locals = res.locals || Object.create(null); + + next(); + }; +}; + diff --git a/5-3/node_modules/express/lib/middleware/query.js b/5-3/node_modules/express/lib/middleware/query.js new file mode 100644 index 0000000..a665f3f --- /dev/null +++ b/5-3/node_modules/express/lib/middleware/query.js @@ -0,0 +1,51 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var parseUrl = require('parseurl'); +var qs = require('qs'); + +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = Object.create(options || null); + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + + if (opts !== undefined) { + if (opts.allowDots === undefined) { + opts.allowDots = false; + } + + if (opts.allowPrototypes === undefined) { + opts.allowPrototypes = true; + } + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; diff --git a/5-3/node_modules/express/lib/request.js b/5-3/node_modules/express/lib/request.js new file mode 100644 index 0000000..33cac18 --- /dev/null +++ b/5-3/node_modules/express/lib/request.js @@ -0,0 +1,489 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + */ + +var req = exports = module.exports = { + __proto__: http.IncomingMessage.prototype +}; + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ + +req.get = +req.header = function header(name) { + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", 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. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + +/** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param {Number} size + * @return {Array} + * @public + */ + +req.range = function(size){ + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ + +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; +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + proto = this.get('X-Forwarded-Proto') || proto; + return proto.split(/\s*,\s*/)[0]; +}); + +/** + * Short-hand for: + * + * req.protocol == 'https' + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + return addrs.slice(1).reverse(); +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +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, 0)) { + host = this.get('Host'); + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var s = this.res.statusCode; + + // GET or HEAD for weak freshness validation only + if ('GET' != method && 'HEAD' != method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((s >= 200 && s < 300) || 304 == s) { + return fresh(this.headers, (this.res._headers || {})); + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +}; diff --git a/5-3/node_modules/express/lib/response.js b/5-3/node_modules/express/lib/response.js new file mode 100644 index 0000000..641704b --- /dev/null +++ b/5-3/node_modules/express/lib/response.js @@ -0,0 +1,1053 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var contentDisposition = require('content-disposition'); +var deprecate = require('depd')('express'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var isAbsolute = require('./utils').isAbsolute; +var onFinished = require('on-finished'); +var path = require('path'); +var merge = require('utils-merge'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var statusCodes = http.STATUS_CODES; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = require('vary'); + +/** + * Response prototype. + */ + +var res = module.exports = { + __proto__: http.ServerResponse.prototype +}; + +/** + * Module variables. + * @private + */ + +var charsetRegExp = /;\s*charset\s*=/; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ + +res.status = function status(code) { + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ + +res.send = function send(body) { + var chunk = body; + var encoding; + var len; + var req = this.req; + var type; + + // settings + var app = this.app; + + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } + } + + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statusCodes[chunk]; + } + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + + // populate Content-Length + if (chunk !== undefined) { + if (!Buffer.isBuffer(chunk)) { + // convert chunk to Buffer; saves later double conversions + chunk = new Buffer(chunk, encoding); + encoding = undefined; + } + + len = chunk.length; + this.set('Content-Length', len); + } + + // 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); + } + } + + // freshness + if (req.fresh) this.statusCode = 304; + + // strip irrelevant headers + if (204 == this.statusCode || 304 == this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.json = function json(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = JSON.stringify(val, replacer, spaces); + + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.jsonp = function jsonp(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = JSON.stringify(val, replacer, spaces); + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.charset = 'utf-8'; + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = statusCodes[statusCode] || String(statusCode); + + this.statusCode = statusCode; + this.type('txt'); + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } + + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // create file stream + var file = send(req, path, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') { + next(err); + } + }); +}; + +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + * + * @public + */ + +res.download = function download(path, filename, callback) { + var done = callback; + var name = filename; + + // support function as second arg + if (typeof filename === 'function') { + done = filename; + name = null; + } + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // Resolve the full path for sendFile + var fullPath = resolve(path); + + return this.sendFile(fullPath, { headers: headers }, done); +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ + +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + + return this.set('Content-Type', ct); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

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

hey

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

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

'; + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ + +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } + + vary(this, field); + + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// 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() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + 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; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} diff --git a/5-3/node_modules/express/lib/router/index.js b/5-3/node_modules/express/lib/router/index.js new file mode 100644 index 0000000..504ed9c --- /dev/null +++ b/5-3/node_modules/express/lib/router/index.js @@ -0,0 +1,645 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Route = require('./route'); +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 flatten = require('array-flatten'); +var parseUrl = require('parseurl'); + +/** + * Module variables. + * @private + */ + +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} options + * @return {Router} which is an callable function + * @public + */ + +var proto = module.exports = function(options) { + var opts = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + router.__proto__ = proto; + + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; + + return router; +}; + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } + + // apply param functions + var params = this._params; + var len = params.length; + 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); + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } + + // ensure we end up with a + // middleware function + if ('function' != typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; + +/** + * Dispatch a req, res into the router. + * @private + */ + +proto.handle = function handle(req, res, out) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var search = 1 + req.url.indexOf('?'); + var pathlength = search ? search - 1 : req.url.length; + var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://'); + var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''; + var idx = 0; + var removed = ''; + var slashAdded = false; + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } + + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; + + // 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 = ''; + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } + + // 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); + } + + if (route) { + return layer.handle_request(req, res, next); + } + + trim_prefix(layer, layerError, layerPath, path); + }); + } + + function trim_prefix(layer, layerError, layerPath, path) { + var c = path[layerPath.length]; + if (c && '/' !== c && '.' !== c) return next(layerError); + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + if (layerPath.length !== 0) { + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); + + // Ensure leading slash + if (!fqdn && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Process any parameters for the layer. + * @private + */ + +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; + + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); + } + + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } + + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + + if (!key) { + return done(); + } + + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; + + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; + + // next param + return param(paramCalled.error); + } + + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } + + param(); +}; + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +proto.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var callbacks = flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires middleware functions'); + } + + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; + + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn)); + } + + // add the middleware + debug('use %s %s', path, fn.name || ''); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + } + + return this; +}; + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public + */ + +proto.route = function route(path) { + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; +}; + +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +// 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; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(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) { + return params; + } + + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } + + var i = 0; + var o = 0; + + // determine numeric gaps + while (i in params) { + i++; + } + + while (o in parent) { + o++; + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } + + return mixin(obj, params); +} + +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); + + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + + return function(err){ + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; +} + +// 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() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} diff --git a/5-3/node_modules/express/lib/router/layer.js b/5-3/node_modules/express/lib/router/layer.js new file mode 100644 index 0000000..fe9210c --- /dev/null +++ b/5-3/node_modules/express/lib/router/layer.js @@ -0,0 +1,176 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var pathRegexp = require('path-to-regexp'); +var debug = require('debug')('express:router:layer'); + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Module exports. + * @public + */ + +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %s', path); + var opts = options || {}; + + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); + + if (path === '/' && opts.end === false) { + this.regexp.fast_slash = true; + } +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; + + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } + + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); + } + + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match(path) { + if (path == null) { + // no path, nothing matches + this.params = undefined; + this.path = undefined; + return false; + } + + if (this.regexp.fast_slash) { + // fast path non-ending match for / (everything matches) + this.params = {}; + this.path = ''; + return true; + } + + var m = this.regexp.exec(path); + + if (!m) { + this.params = undefined; + this.path = undefined; + return false; + } + + // store values + this.params = {}; + this.path = m[0]; + + var keys = this.keys; + var params = this.params; + + for (var i = 1; i < m.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(m[i]); + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } + + return true; +}; + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } + + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } + + throw err; + } +} diff --git a/5-3/node_modules/express/lib/router/route.js b/5-3/node_modules/express/lib/router/route.js new file mode 100644 index 0000000..2788d7b --- /dev/null +++ b/5-3/node_modules/express/lib/router/route.js @@ -0,0 +1,210 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:router:route'); +var flatten = require('array-flatten'); +var Layer = require('./layer'); +var methods = require('methods'); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Module exports. + * @public + */ + +module.exports = Route; + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ + +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %s', path); + + // route handlers for various http methods + this.methods = {}; +} + +/** + * Determine if the route handles a given method. + * @private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } + + var name = method.toLowerCase(); + + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } + + return Boolean(this.methods[name]); +}; + +/** + * @return {Array} supported HTTP methods + * @private + */ + +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; +}; + +/** + * dispatch req, res into this route + * @private + */ + +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); + } + + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = this; + + next(); + + function next(err) { + if (err && err === 'route') { + return done(); + } + + var layer = stack[idx++]; + if (!layer) { + return done(err); + } + + if (layer.method && layer.method !== method) { + return next(err); + } + + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires callback functions but got a ' + type; + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); + } + + return this; +}; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires callback functions but got a ' + type; + throw new Error(msg); + } + + debug('%s %s', method, this.path); + + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + } + + return this; + }; +}); diff --git a/5-3/node_modules/express/lib/utils.js b/5-3/node_modules/express/lib/utils.js new file mode 100644 index 0000000..3d54247 --- /dev/null +++ b/5-3/node_modules/express/lib/utils.js @@ -0,0 +1,300 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @api private + */ + +var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var mime = require('send').mime; +var basename = require('path').basename; +var etag = require('etag'); +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); + +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = function (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? new Buffer(body, encoding) + : body; + + return etag(buf, {weak: false}); +}; + +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = function wetag(body, encoding){ + var buf = !Buffer.isBuffer(body) + ? new Buffer(body, encoding) + : body; + + return etag(buf, {weak: true}); +}; + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +exports.isAbsolute = function(path){ + if ('/' == path[0]) return true; + if (':' == path[1] && '\\' == path[2]) return true; + if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; + +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' == pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowDots: false, + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} diff --git a/5-3/node_modules/express/lib/view.js b/5-3/node_modules/express/lib/view.js new file mode 100644 index 0000000..52415d4 --- /dev/null +++ b/5-3/node_modules/express/lib/view.js @@ -0,0 +1,173 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:view'); +var path = require('path'); +var fs = require('fs'); +var utils = require('./utils'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ + +function View(name, options) { + var opts = options || {}; + + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; + } + + if (!opts.engines[this.ext]) { + // load engine + opts.engines[this.ext] = require(this.ext.substr(1)).__express; + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); + + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/5-3/node_modules/express/node_modules/accepts/HISTORY.md b/5-3/node_modules/express/node_modules/accepts/HISTORY.md new file mode 100644 index 0000000..397636e --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/HISTORY.md @@ -0,0 +1,170 @@ +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +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 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/5-3/node_modules/express/node_modules/accepts/LICENSE b/5-3/node_modules/express/node_modules/accepts/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-3/node_modules/express/node_modules/accepts/README.md b/5-3/node_modules/express/node_modules/accepts/README.md new file mode 100644 index 0000000..ae36676 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/README.md @@ -0,0 +1,135 @@ +# accepts + +[![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] + +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 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 `*` + +## Installation + +```sh +npm install accepts +``` + +## API + +```js +var accepts = require('accepts') +``` + +### 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) +``` + +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 +[npm-url]: https://npmjs.org/package/accepts +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/accepts +[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 +[downloads-url]: https://npmjs.org/package/accepts diff --git a/5-3/node_modules/express/node_modules/accepts/index.js b/5-3/node_modules/express/node_modules/accepts/index.js new file mode 100644 index 0000000..e80192a --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/index.js @@ -0,0 +1,231 @@ +/*! + * 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') + +/** + * 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 = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +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 = this.negotiator.mediaTypes(mimes.filter(validMime)); + var first = accepts[0]; + if (!first) return false; + return types[mimes.indexOf(first)]; +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +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 +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +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 +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +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 +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime(type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ + +function validMime(type) { + return typeof type === 'string'; +} diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..61b54b4 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/HISTORY.md @@ -0,0 +1,183 @@ +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +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 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md new file mode 100644 index 0000000..e26295d --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md @@ -0,0 +1,103 @@ +# mime-types + +[![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] + +The ultimate javascript content-type utility. + +Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, + so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db) +- No `.define()` functionality + +Otherwise, the API is compatible. + +## Install + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://github.com/jshttp/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[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/node/v/mime-types.svg +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js new file mode 100644 index 0000000..f7008b2 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js @@ -0,0 +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 + +/** + * 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) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..41a667a --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -0,0 +1,306 @@ +1.21.0 / 2016-01-06 +=================== + + * Add `application/emergencycalldata.comment+xml` + * Add `application/emergencycalldata.deviceinfo+xml` + * Add `application/emergencycalldata.providerinfo+xml` + * Add `application/emergencycalldata.serviceinfo+xml` + * Add `application/emergencycalldata.subscriberinfo+xml` + * Add `application/vnd.filmit.zfc` + * Add `application/vnd.google-apps.document` + * Add `application/vnd.google-apps.presentation` + * Add `application/vnd.google-apps.spreadsheet` + * Add `application/vnd.mapbox-vector-tile` + * Add `application/vnd.ms-printdevicecapabilities+xml` + * Add `application/vnd.ms-windows.devicepairing` + * Add `application/vnd.ms-windows.nwprinting.oob` + * Add `application/vnd.tml` + * Add `audio/evs` + +1.20.0 / 2015-11-10 +=================== + + * Add `application/cdni` + * Add `application/csvm+json` + * Add `application/rfc+xml` + * Add `application/vnd.3gpp.access-transfer-events+xml` + * Add `application/vnd.3gpp.srvcc-ext+xml` + * Add `application/vnd.ms-windows.wsd.oob` + * Add `application/vnd.oxli.countgraph` + * Add `application/vnd.pagerduty+json` + * Add `text/x-suse-ymp` + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.3gpp-prose-pc3ch+xml` + * Add `application/vnd.3gpp.srvcc-info+xml` + * Add `application/vnd.apple.pkpass` + * Add `application/vnd.drive+json` + +1.18.0 / 2015-09-03 +=================== + + * Add `application/pkcs12` + * Add `application/vnd.3gpp-prose+xml` + * Add `application/vnd.3gpp.mid-call+xml` + * Add `application/vnd.3gpp.state-and-event-info+xml` + * Add `application/vnd.anki` + * Add `application/vnd.firemonkeys.cloudcell` + * Add `application/vnd.openblox.game+xml` + * Add `application/vnd.openblox.game-binary` + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +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 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md new file mode 100644 index 0000000..7662440 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/README.md @@ -0,0 +1,82 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +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 + +```bash +npm install mime-db +``` + +### 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 +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + 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 can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +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 +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[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 +[node-url]: http://nodejs.org/download/ diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json new file mode 100644 index 0000000..412ba9e --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/db.json @@ -0,0 +1,6552 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana" + }, + "application/3gpp-ims+xml": { + "source": "iana" + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana" + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana" + }, + "application/bacnet-xdd+zip": { + "source": "iana" + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana" + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana" + }, + "application/ccxml+xml": { + "source": "iana", + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana" + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana" + }, + "application/cellml+xml": { + "source": "iana" + }, + "application/cfw": { + "source": "iana" + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana" + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana" + }, + "application/cstadata+xml": { + "source": "iana" + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "extensions": ["mdp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana" + }, + "application/dicom": { + "source": "iana" + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana" + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/emergencycalldata.comment+xml": { + "source": "iana" + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana" + }, + "application/emma+xml": { + "source": "iana", + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana" + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana" + }, + "application/epub+zip": { + "source": "iana", + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana" + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false, + "extensions": ["woff"] + }, + "application/font-woff2": { + "compressible": false, + "extensions": ["woff2"] + }, + "application/framework-attributes+xml": { + "source": "iana" + }, + "application/gml+xml": { + "source": "apache", + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana" + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana" + }, + "application/ibe-pkg-reply+xml": { + "source": "iana" + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana" + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana" + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana" + }, + "application/kpml-response+xml": { + "source": "iana" + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana" + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana" + }, + "application/mathml-presentation+xml": { + "source": "iana" + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana" + }, + "application/mbms-deregister+xml": { + "source": "iana" + }, + "application/mbms-envelope+xml": { + "source": "iana" + }, + "application/mbms-msk+xml": { + "source": "iana" + }, + "application/mbms-msk-response+xml": { + "source": "iana" + }, + "application/mbms-protection-description+xml": { + "source": "iana" + }, + "application/mbms-reception-report+xml": { + "source": "iana" + }, + "application/mbms-register+xml": { + "source": "iana" + }, + "application/mbms-register-response+xml": { + "source": "iana" + }, + "application/mbms-schedule+xml": { + "source": "iana" + }, + "application/mbms-user-service-description+xml": { + "source": "iana" + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana" + }, + "application/media_control+xml": { + "source": "iana" + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mods+xml": { + "source": "iana", + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana" + }, + "application/mrb-publish+xml": { + "source": "iana" + }, + "application/msc-ivr+xml": { + "source": "iana" + }, + "application/msc-mixer+xml": { + "source": "iana" + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "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", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana" + }, + "application/parityfec": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana" + }, + "application/pidf-diff+xml": { + "source": "iana" + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana" + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/provenance+xml": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana" + }, + "application/pskc+xml": { + "source": "iana", + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf"] + }, + "application/reginfo+xml": { + "source": "iana", + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana" + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana" + }, + "application/rls-services+xml": { + "source": "iana", + "extensions": ["rs"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana" + }, + "application/samlmetadata+xml": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana" + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/sep+xml": { + "source": "iana" + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana" + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana" + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "extensions": ["ssml"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/ttml+xml": { + "source": "iana" + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana" + }, + "application/urc-ressheet+xml": { + "source": "iana" + }, + "application/urc-targetdesc+xml": { + "source": "iana" + }, + "application/urc-uisocketdesc+xml": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana" + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana" + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana" + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana" + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "extensions": ["mpkg"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avistar+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "extensions": ["cdxml"] + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana" + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana" + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana" + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume-movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana" + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana" + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana" + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana" + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana" + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana" + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana" + }, + "application/vnd.etsi.cug+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana" + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana" + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana" + }, + "application/vnd.etsi.sci+xml": { + "source": "iana" + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana" + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana" + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana" + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana" + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana" + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana" + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana" + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana" + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana" + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+xml": { + "source": "iana", + "extensions": ["lasxml"] + }, + "application/vnd.liberty-request+xml": { + "source": "iana" + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana" + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana" + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana" + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache" + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana" + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana" + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana" + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana" + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana" + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana" + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana" + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana" + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana" + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana" + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana" + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana" + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana" + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana" + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana" + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana" + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana" + }, + "application/vnd.omads-email+xml": { + "source": "iana" + }, + "application/vnd.omads-file+xml": { + "source": "iana" + }, + "application/vnd.omads-folder+xml": { + "source": "iana" + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana" + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "apache", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "apache", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "apache", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana" + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana" + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos+xml": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "apache" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana" + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana" + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana" + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana" + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana" + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana" + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana" + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana" + }, + "application/vnd.wv.ssp+xml": { + "source": "iana" + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana" + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "extensions": ["vxml"] + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/watcherinfo+xml": { + "source": "iana" + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-otf": { + "source": "apache", + "compressible": true, + "extensions": ["otf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-ttf": { + "source": "apache", + "compressible": true, + "extensions": ["ttf","ttc"] + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "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, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "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, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana" + }, + "application/xaml+xml": { + "source": "apache", + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana" + }, + "application/xcap-caps+xml": { + "source": "iana" + }, + "application/xcap-diff+xml": { + "source": "iana", + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana" + }, + "application/xcap-error+xml": { + "source": "iana" + }, + "application/xcap-ns+xml": { + "source": "iana" + }, + "application/xcon-conference-info+xml": { + "source": "iana" + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana" + }, + "application/xenc+xml": { + "source": "iana", + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache" + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana" + }, + "application/xmpp+xml": { + "source": "iana" + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yin+xml": { + "source": "iana", + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana" + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4a","m4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/opentype": { + "compressible": true, + "extensions": ["otf"] + }, + "image/bmp": { + "source": "apache", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/fits": { + "source": "iana" + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jp2": { + "source": "iana" + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana" + }, + "image/jpx": { + "source": "iana" + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana" + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana" + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tiff","tif"] + }, + "image/tiff-fx": { + "source": "iana" + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana" + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana" + }, + "image/vnd.valve.source.texture": { + "source": "iana" + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "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"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana" + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana" + }, + "message/global-delivery-status": { + "source": "iana" + }, + "message/global-disposition-notification": { + "source": "iana" + }, + "message/global-headers": { + "source": "iana" + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana" + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana" + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hjson": { + "extensions": ["hjson"] + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana" + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["markdown","md","mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "apache" + }, + "video/3gpp": { + "source": "apache", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "apache" + }, + "video/3gpp2": { + "source": "apache", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "apache" + }, + "video/bt656": { + "source": "apache" + }, + "video/celb": { + "source": "apache" + }, + "video/dv": { + "source": "apache" + }, + "video/h261": { + "source": "apache", + "extensions": ["h261"] + }, + "video/h263": { + "source": "apache", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "apache" + }, + "video/h263-2000": { + "source": "apache" + }, + "video/h264": { + "source": "apache", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "apache" + }, + "video/h264-svc": { + "source": "apache" + }, + "video/jpeg": { + "source": "apache", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "apache" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "apache", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "apache" + }, + "video/mp2p": { + "source": "apache" + }, + "video/mp2t": { + "source": "apache", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "apache", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "apache" + }, + "video/mpeg": { + "source": "apache", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "apache" + }, + "video/mpv": { + "source": "apache" + }, + "video/nv": { + "source": "apache" + }, + "video/ogg": { + "source": "apache", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "apache" + }, + "video/pointer": { + "source": "apache" + }, + "video/quicktime": { + "source": "apache", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raw": { + "source": "apache" + }, + "video/rtp-enc-aescm128": { + "source": "apache" + }, + "video/rtx": { + "source": "apache" + }, + "video/smpte292m": { + "source": "apache" + }, + "video/ulpfec": { + "source": "apache" + }, + "video/vc1": { + "source": "apache" + }, + "video/vnd.cctv": { + "source": "apache" + }, + "video/vnd.dece.hd": { + "source": "apache", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "apache", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "apache" + }, + "video/vnd.dece.pd": { + "source": "apache", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "apache", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "apache", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "apache" + }, + "video/vnd.directv.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dvb.file": { + "source": "apache", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "apache", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "apache" + }, + "video/vnd.motorola.video": { + "source": "apache" + }, + "video/vnd.motorola.videop": { + "source": "apache" + }, + "video/vnd.mpegurl": { + "source": "apache", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "apache", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "apache" + }, + "video/vnd.nokia.videovoip": { + "source": "apache" + }, + "video/vnd.objectvideo": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "apache" + }, + "video/vnd.sealed.mpeg4": { + "source": "apache" + }, + "video/vnd.sealed.swf": { + "source": "apache" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "apache" + }, + "video/vnd.uvvu.mp4": { + "source": "apache", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "apache", + "extensions": ["viv"] + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json new file mode 100644 index 0000000..e6c9732 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/package.json @@ -0,0 +1,94 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.21.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "devDependencies": { + "bluebird": "3.1.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "1.0.1", + "gnode": "0.1.1", + "istanbul": "0.4.1", + "mocha": "1.21.5", + "raw-body": "2.1.5", + "stream-to-array": "2.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "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": "9ab92f0a912a602408a64db5741dfef6f82c597f", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "homepage": "https://github.com/jshttp/mime-db", + "_id": "mime-db@1.21.0", + "_shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "_from": "mime-db@>=1.21.0 <1.22.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" + } + ], + "dist": { + "shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json new file mode 100644 index 0000000..d1a5ffa --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json @@ -0,0 +1,84 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "dependencies": { + "mime-db": "~1.21.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec test/test.js", + "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": "329f1c77e1a77c8fac59b15038e3808e9e314d96", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "homepage": "https://github.com/jshttp/mime-types", + "_id": "mime-types@2.1.9", + "_shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "_from": "mime-types@>=2.1.6 <2.2.0", + "_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" + } + ], + "dist": { + "shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md new file mode 100644 index 0000000..aa2a7c4 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/HISTORY.md @@ -0,0 +1,76 @@ +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE new file mode 100644 index 0000000..ea6b9e2 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +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 +'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/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md new file mode 100644 index 0000000..ef507fa --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/README.md @@ -0,0 +1,203 @@ +# negotiator + +[![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] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +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 + +```js +negotiator = new Negotiator(request) + +availableLanguages = 'en', 'es', 'fr' + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +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 + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +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 + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +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 +[npm-url]: https://npmjs.org/package/negotiator +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/negotiator +[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 +[downloads-url]: https://npmjs.org/package/negotiator diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js new file mode 100644 index 0000000..edae9cf --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/index.js @@ -0,0 +1,62 @@ + +var preferredCharsets = require('./lib/charset'); +var preferredEncodings = require('./lib/encoding'); +var preferredLanguages = require('./lib/language'); +var preferredMediaTypes = require('./lib/mediaType'); + +module.exports = Negotiator; +Negotiator.Negotiator = Negotiator; + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available) { + var set = this.encodings(available); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available) { + return preferredEncodings(this.request.headers['accept-encoding'], available); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; diff --git a/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js new file mode 100644 index 0000000..7abd17c --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js @@ -0,0 +1,102 @@ +module.exports = preferredCharsets; +preferredCharsets.preferredCharsets = preferredCharsets; + +function parseAcceptCharset(accept) { + 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) { + var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +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; + } + } + + return priority; +} + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + 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/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js new file mode 100644 index 0000000..7fed673 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,118 @@ +module.exports = preferredEncodings; +preferredEncodings.preferredEncodings = preferredEncodings; + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + 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 (!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 + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +function parseEncoding(s, i) { + var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); + + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +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; + } + } + + return priority; +} + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +function preferredEncodings(accept, provided) { + 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/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js new file mode 100644 index 0000000..ed9e1ec --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js @@ -0,0 +1,112 @@ +module.exports = preferredLanguages; +preferredLanguages.preferredLanguages = preferredLanguages; + +function parseAcceptLanguage(accept) { + 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) { + var match = s.match(/^\s*(\S+?)(?:-(\S+?))?\s*(?:;(.*))?$/); + if (!match) return null; + + var prefix = match[1], + suffix = match[2], + full = prefix; + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +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; + } + } + + return priority; +} + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + 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/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 0000000..4170c25 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,179 @@ +/** + * 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) { + 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) { + var match = s.match(/\s*(\S+?)\/([^;\s]+)\s*(?:;(.*))?/); + if (!match) return null; + + var type = match[1], + subtype = match[2], + full = "" + type + "/" + subtype, + params = {}, + q = 1; + + if (match[3]) { + params = match[3].split(';').map(function(s) { + return s.trim().split('='); + }).reduce(function (set, p) { + 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) { + q = parseFloat(params.q); + delete params.q; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i, + full: full + }; +} + +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; + } + } + + return priority; +} + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } + +} + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + 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/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json new file mode 100644 index 0000000..66d2824 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json @@ -0,0 +1,86 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "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/" + } + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/negotiator.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "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": "cbb717b3f164f25820f90b160cda6d0166b9d922", + "bugs": { + "url": "https://github.com/jshttp/negotiator/issues" + }, + "homepage": "https://github.com/jshttp/negotiator", + "_id": "negotiator@0.5.3", + "_shasum": "269d5c476810ec92edbe7b6c2f28316384f9a7e8", + "_from": "negotiator@0.5.3", + "_npmVersion": "1.4.28", + "_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": "269d5c476810ec92edbe7b6c2f28316384f9a7e8", + "tarball": "http://registry.npmjs.org/negotiator/-/negotiator-0.5.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.5.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/accepts/package.json b/5-3/node_modules/express/node_modules/accepts/package.json new file mode 100644 index 0000000..6455e64 --- /dev/null +++ b/5-3/node_modules/express/node_modules/accepts/package.json @@ -0,0 +1,98 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "1.2.13", + "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": "git+https://github.com/jshttp/accepts.git" + }, + "dependencies": { + "mime-types": "~2.1.6", + "negotiator": "0.5.3" + }, + "devDependencies": { + "istanbul": "0.3.19", + "mocha": "~1.21.5" + }, + "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/" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ], + "gitHead": "b7e15ecb25dacc0b2133ed0553d64f8a79537e01", + "bugs": { + "url": "https://github.com/jshttp/accepts/issues" + }, + "homepage": "https://github.com/jshttp/accepts", + "_id": "accepts@1.2.13", + "_shasum": "e5f1f3928c6d95fd96558c36ec3d9d0de4a6ecea", + "_from": "accepts@>=1.2.12 <1.3.0", + "_npmVersion": "1.4.28", + "_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": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "e5f1f3928c6d95fd96558c36ec3d9d0de4a6ecea", + "tarball": "http://registry.npmjs.org/accepts/-/accepts-1.2.13.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.2.13.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/array-flatten/LICENSE b/5-3/node_modules/express/node_modules/array-flatten/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/5-3/node_modules/express/node_modules/array-flatten/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/5-3/node_modules/express/node_modules/array-flatten/README.md b/5-3/node_modules/express/node_modules/array-flatten/README.md new file mode 100644 index 0000000..91fa5b6 --- /dev/null +++ b/5-3/node_modules/express/node_modules/array-flatten/README.md @@ -0,0 +1,43 @@ +# Array Flatten + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +> Flatten an array of nested arrays into a single flat array. Accepts an optional depth. + +## Installation + +``` +npm install array-flatten --save +``` + +## Usage + +```javascript +var flatten = require('array-flatten') + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) +//=> [1, 2, 3, 4, 5, 6, 7, 8, 9] + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) +//=> [1, 2, 3, [4, [5], 6], 7, 8, 9] + +(function () { + flatten(arguments) //=> [1, 2, 3] +})(1, [2, 3]) +``` + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat +[npm-url]: https://npmjs.org/package/array-flatten +[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat +[downloads-url]: https://npmjs.org/package/array-flatten +[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat +[travis-url]: https://travis-ci.org/blakeembrey/array-flatten +[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat +[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master diff --git a/5-3/node_modules/express/node_modules/array-flatten/array-flatten.js b/5-3/node_modules/express/node_modules/array-flatten/array-flatten.js new file mode 100644 index 0000000..089117b --- /dev/null +++ b/5-3/node_modules/express/node_modules/array-flatten/array-flatten.js @@ -0,0 +1,64 @@ +'use strict' + +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result +} + +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result +} + +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) +} diff --git a/5-3/node_modules/express/node_modules/array-flatten/package.json b/5-3/node_modules/express/node_modules/array-flatten/package.json new file mode 100644 index 0000000..f80f937 --- /dev/null +++ b/5-3/node_modules/express/node_modules/array-flatten/package.json @@ -0,0 +1,62 @@ +{ + "name": "array-flatten", + "version": "1.1.1", + "description": "Flatten an array of nested arrays into a single flat array", + "main": "array-flatten.js", + "files": [ + "array-flatten.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/blakeembrey/array-flatten.git" + }, + "keywords": [ + "array", + "flatten", + "arguments", + "depth" + ], + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/blakeembrey/array-flatten/issues" + }, + "homepage": "https://github.com/blakeembrey/array-flatten", + "devDependencies": { + "istanbul": "^0.3.13", + "mocha": "^2.2.4", + "pre-commit": "^1.0.7", + "standard": "^3.7.3" + }, + "gitHead": "1963a9189229d408e1e8f585a00c8be9edbd1803", + "_id": "array-flatten@1.1.1", + "_shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2", + "_from": "array-flatten@1.1.1", + "_npmVersion": "2.11.3", + "_nodeVersion": "2.3.3", + "_npmUser": { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + }, + "maintainers": [ + { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + } + ], + "dist": { + "shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2", + "tarball": "http://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/content-disposition/HISTORY.md b/5-3/node_modules/express/node_modules/content-disposition/HISTORY.md new file mode 100644 index 0000000..76d494c --- /dev/null +++ b/5-3/node_modules/express/node_modules/content-disposition/HISTORY.md @@ -0,0 +1,45 @@ +0.5.1 / 2016-01-17 +================== + + * perf: enable strict mode + +0.5.0 / 2014-10-11 +================== + + * Add `parse` function + +0.4.0 / 2014-09-21 +================== + + * Expand non-Unicode `filename` to the full ISO-8859-1 charset + +0.3.0 / 2014-09-20 +================== + + * Add `fallback` option + * Add `type` option + +0.2.0 / 2014-09-19 +================== + + * Reduce ambiguity of file names with hex escape in buggy browsers + +0.1.2 / 2014-09-19 +================== + + * Fix periodic invalid Unicode filename header + +0.1.1 / 2014-09-19 +================== + + * Fix invalid characters appearing in `filename*` parameter + +0.1.0 / 2014-09-18 +================== + + * Make the `filename` argument optional + +0.0.0 / 2014-09-18 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/content-disposition/LICENSE b/5-3/node_modules/express/node_modules/content-disposition/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-3/node_modules/express/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/content-disposition/README.md b/5-3/node_modules/express/node_modules/content-disposition/README.md new file mode 100644 index 0000000..5cebce4 --- /dev/null +++ b/5-3/node_modules/express/node_modules/content-disposition/README.md @@ -0,0 +1,141 @@ +# content-disposition + +[![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] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + +```js +var contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + +```js +var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'); +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +var contentDisposition = require('content-disposition') +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +var filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest(req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + var stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://tools.ietf.org/html/rfc2616 +[rfc-5987]: https://tools.ietf.org/html/rfc5987 +[rfc-6266]: https://tools.ietf.org/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition.svg?style=flat +[npm-url]: https://npmjs.org/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/content-disposition +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg?style=flat +[downloads-url]: https://npmjs.org/package/content-disposition diff --git a/5-3/node_modules/express/node_modules/content-disposition/index.js b/5-3/node_modules/express/node_modules/content-disposition/index.js new file mode 100644 index 0000000..4a352dc --- /dev/null +++ b/5-3/node_modules/express/node_modules/content-disposition/index.js @@ -0,0 +1,445 @@ +/*! + * content-disposition + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * Module dependencies. + */ + +var basename = require('path').basename + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + */ + +var encodeUriAttrCharRegExp = /[\x00-\x20"'\(\)*,\/:;<=>?@\[\\\]\{\}\x7f]/g + +/** + * RegExp to match percent encoding escape. + */ + +var hexEscapeRegExp = /%[0-9A-Fa-f]{2}/ +var hexEscapeReplaceRegExp = /%([0-9A-Fa-f]{2})/g + +/** + * RegExp to match non-latin1 characters. + */ + +var nonLatin1RegExp = /[^\x20-\x7e\xa0-\xff]/g + +/** + * 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 for various RFC 2616 grammar + * + * 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 = + * HT = + * CTL = + * OCTET = + */ + +var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g +var textRegExp = /^[\x20-\x7e\x80-\xff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + */ + +var extValueRegExp = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+\-\.^_`|~])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + */ + +var dispositionTypeRegExp = /^([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *(?:$|;)/ + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @api public + */ + +function contentDisposition(filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @api private + */ + +function createparams(filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && nonLatin1RegExp.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = textRegExp.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || hexEscapeRegExp.test(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @api private + */ + +function format(obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !tokenRegExp.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // 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] + + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 6987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @api private + */ + +function decodefield(str) { + var match = extValueRegExp.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + + // to binary string + var binary = encoded.replace(hexEscapeReplaceRegExp, pdecode) + + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = new Buffer(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @api private + */ + +function getlatin1(val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(nonLatin1RegExp, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @api private + */ + +function parse(string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = dispositionTypeRegExp.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = paramRegExp.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + 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 (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + 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') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @api private + */ + +function pdecode(str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @api private + */ + +function pencode(char) { + var hex = String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() + return hex.length === 1 + ? '%0' + hex + : '%' + hex +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @api private + */ + +function qstring(val) { + var str = String(val) + + return '"' + str.replace(quoteRegExp, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @api private + */ + +function ustring(val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(encodeUriAttrCharRegExp, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + */ + +function ContentDisposition(type, parameters) { + this.type = type + this.parameters = parameters +} diff --git a/5-3/node_modules/express/node_modules/content-disposition/package.json b/5-3/node_modules/express/node_modules/content-disposition/package.json new file mode 100644 index 0000000..1b22eb9 --- /dev/null +++ b/5-3/node_modules/express/node_modules/content-disposition/package.json @@ -0,0 +1,66 @@ +{ + "name": "content-disposition", + "description": "Create and parse Content-Disposition header", + "version": "0.5.1", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-disposition.git" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "7b391db3af5629d4c698f1de21802940bb9f22a5", + "bugs": { + "url": "https://github.com/jshttp/content-disposition/issues" + }, + "homepage": "https://github.com/jshttp/content-disposition", + "_id": "content-disposition@0.5.1", + "_shasum": "87476c6a67c8daa87e32e87616df883ba7fb071b", + "_from": "content-disposition@0.5.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "87476c6a67c8daa87e32e87616df883ba7fb071b", + "tarball": "http://registry.npmjs.org/content-disposition/-/content-disposition-0.5.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/content-type/HISTORY.md b/5-3/node_modules/express/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..8a623a2 --- /dev/null +++ b/5-3/node_modules/express/node_modules/content-type/HISTORY.md @@ -0,0 +1,9 @@ +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/5-3/node_modules/express/node_modules/content-type/LICENSE b/5-3/node_modules/express/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/5-3/node_modules/express/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/5-3/node_modules/express/node_modules/content-type/README.md b/5-3/node_modules/express/node_modules/content-type/README.md new file mode 100644 index 0000000..3ed6741 --- /dev/null +++ b/5-3/node_modules/express/node_modules/content-type/README.md @@ -0,0 +1,92 @@ +# content-type + +[![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] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a content 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 media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({type: 'image/svg+xml'}) +``` + +Format an object into a content type string. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-type.svg +[npm-url]: https://npmjs.org/package/content-type +[node-version-image]: https://img.shields.io/node/v/content-type.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg +[travis-url]: https://travis-ci.org/jshttp/content-type +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-type +[downloads-image]: https://img.shields.io/npm/dm/content-type.svg +[downloads-url]: https://npmjs.org/package/content-type diff --git a/5-3/node_modules/express/node_modules/content-type/index.js b/5-3/node_modules/express/node_modules/content-type/index.js new file mode 100644 index 0000000..6a2ea9f --- /dev/null +++ b/5-3/node_modules/express/node_modules/content-type/index.js @@ -0,0 +1,214 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) */g +var textRegExp = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var qescRegExp = /\\([\u000b\u0020-\u00ff])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var quoteRegExp = /([\\"])/g + +/** + * RegExp to match type in RFC 6838 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+\/[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !typeRegExp.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // 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} + * @public + */ + +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } + + if (typeof string === 'object') { + // support req/res-like objects as argument + string = getcontenttype(string) + + if (typeof string !== 'string') { + throw new TypeError('content-type header is missing from object'); + } + } + + 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).trim() + : string.trim() + + if (!typeRegExp.test(type)) { + throw new TypeError('invalid media type') + } + + var key + var match + var obj = new ContentType(type.toLowerCase()) + 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') + } + + obj.parameters[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @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} + * @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') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType(type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/5-3/node_modules/express/node_modules/content-type/package.json b/5-3/node_modules/express/node_modules/content-type/package.json new file mode 100644 index 0000000..e23403c --- /dev/null +++ b/5-3/node_modules/express/node_modules/content-type/package.json @@ -0,0 +1,65 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-type.git" + }, + "devDependencies": { + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail 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": "3aa58f9c5a358a3634b8601602177888b4a477d8", + "bugs": { + "url": "https://github.com/jshttp/content-type/issues" + }, + "homepage": "https://github.com/jshttp/content-type", + "_id": "content-type@1.0.1", + "_shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "_from": "content-type@>=1.0.1 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "a19d2247327dc038050ce622b7a154ec59c5e600", + "tarball": "http://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/cookie-signature/.npmignore b/5-3/node_modules/express/node_modules/cookie-signature/.npmignore new file mode 100644 index 0000000..f1250e5 --- /dev/null +++ b/5-3/node_modules/express/node_modules/cookie-signature/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/5-3/node_modules/express/node_modules/cookie-signature/History.md b/5-3/node_modules/express/node_modules/cookie-signature/History.md new file mode 100644 index 0000000..78513cc --- /dev/null +++ b/5-3/node_modules/express/node_modules/cookie-signature/History.md @@ -0,0 +1,38 @@ +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 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/cookie-signature/Readme.md b/5-3/node_modules/express/node_modules/cookie-signature/Readme.md new file mode 100644 index 0000000..2559e84 --- /dev/null +++ b/5-3/node_modules/express/node_modules/cookie-signature/Readme.md @@ -0,0 +1,42 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +(The MIT License) + +Copyright (c) 2012 LearnBoost <tj@learnboost.com> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/5-3/node_modules/express/node_modules/cookie-signature/index.js b/5-3/node_modules/express/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..b8c9463 --- /dev/null +++ b/5-3/node_modules/express/node_modules/cookie-signature/index.js @@ -0,0 +1,51 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie 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) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("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); + + return sha1(mac) == sha1(val) ? str : false; +}; + +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} diff --git a/5-3/node_modules/express/node_modules/cookie-signature/package.json b/5-3/node_modules/express/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..28f87d0 --- /dev/null +++ b/5-3/node_modules/express/node_modules/cookie-signature/package.json @@ -0,0 +1,59 @@ +{ + "name": "cookie-signature", + "version": "1.0.6", + "description": "Sign and unsign cookies", + "keywords": [ + "cookie", + "sign", + "unsign" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@learnboost.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/visionmedia/node-cookie-signature.git" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, + "main": "index", + "gitHead": "391b56cf44d88c493491b7e3fc53208cfb976d2a", + "bugs": { + "url": "https://github.com/visionmedia/node-cookie-signature/issues" + }, + "homepage": "https://github.com/visionmedia/node-cookie-signature", + "_id": "cookie-signature@1.0.6", + "_shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c", + "_from": "cookie-signature@1.0.6", + "_npmVersion": "2.3.0", + "_nodeVersion": "0.10.36", + "_npmUser": { + "name": "natevw", + "email": "natevw@yahoo.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "natevw", + "email": "natevw@yahoo.com" + } + ], + "dist": { + "shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c", + "tarball": "http://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/cookie/HISTORY.md b/5-3/node_modules/express/node_modules/cookie/HISTORY.md new file mode 100644 index 0000000..c9803ce --- /dev/null +++ b/5-3/node_modules/express/node_modules/cookie/HISTORY.md @@ -0,0 +1,72 @@ +0.1.5 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.1.4 / 2015-09-17 +================== + + * Throw better error for invalid argument to parse + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.1.3 / 2015-05-19 +================== + + * Reduce the scope of try-catch deopt + * Remove argument reassignments + +0.1.2 / 2014-04-16 +================== + + * Remove unnecessary files from npm package + +0.1.1 / 2014-02-23 +================== + + * Fix bad parse when cookie value contained a comma + * Fix support for `maxAge` of `0` + +0.1.0 / 2013-05-01 +================== + + * Add `decode` option + * Add `encode` option + +0.0.6 / 2013-04-08 +================== + + * Ignore cookie parts missing `=` + +0.0.5 / 2012-10-29 +================== + + * Return raw cookie value if value unescape errors + +0.0.4 / 2012-06-21 +================== + + * Use encode/decodeURIComponent for cookie encoding/decoding + - Improve server/client interoperability + +0.0.3 / 2012-06-06 +================== + + * Only escape special characters per the cookie RFC + +0.0.2 / 2012-06-01 +================== + + * Fix `maxAge` option to not throw error + +0.0.1 / 2012-05-28 +================== + + * Add more tests + +0.0.0 / 2012-05-28 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/cookie/LICENSE b/5-3/node_modules/express/node_modules/cookie/LICENSE new file mode 100644 index 0000000..e849495 --- /dev/null +++ b/5-3/node_modules/express/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +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 +'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/5-3/node_modules/express/node_modules/cookie/README.md b/5-3/node_modules/express/node_modules/cookie/README.md new file mode 100644 index 0000000..acdb5c2 --- /dev/null +++ b/5-3/node_modules/express/node_modules/cookie/README.md @@ -0,0 +1,64 @@ +# cookie + +[![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] + +cookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers. + +See [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies. + +## how? + +``` +npm install cookie +``` + +```javascript +var cookie = require('cookie'); + +var hdr = cookie.serialize('foo', 'bar'); +// hdr = 'foo=bar'; + +var cookies = cookie.parse('foo=bar; cat=meow; dog=ruff'); +// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' }; +``` + +## more + +The serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values. + +### path +> cookie path + +### expires +> absolute expiration date for the cookie (Date object) + +### maxAge +> relative max age of the cookie from when the client receives it (seconds) + +### domain +> domain for the cookie + +### secure +> true or false + +### httpOnly +> true or false + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/cookie.svg +[npm-url]: https://npmjs.org/package/cookie +[node-version-image]: https://img.shields.io/node/v/cookie.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/cookie/master.svg +[travis-url]: https://travis-ci.org/jshttp/cookie +[coveralls-image]: https://img.shields.io/coveralls/jshttp/cookie/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[downloads-image]: https://img.shields.io/npm/dm/cookie.svg +[downloads-url]: https://npmjs.org/package/cookie diff --git a/5-3/node_modules/express/node_modules/cookie/index.js b/5-3/node_modules/express/node_modules/cookie/index.js new file mode 100644 index 0000000..b8389a1 --- /dev/null +++ b/5-3/node_modules/express/node_modules/cookie/index.js @@ -0,0 +1,156 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var decode = decodeURIComponent; +var encode = encodeURIComponent; + +/** + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF + */ + +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var pairs = str.split(/; */); + var dec = opt.decode || decode; + + pairs.forEach(function(pair) { + var eq_idx = pair.indexOf('=') + + // skip things that don't look like key=value + if (eq_idx < 0) { + return; + } + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + }); + + return obj; +} + +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var pairs = [name + '=' + value]; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + pairs.push('Max-Age=' + maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + + pairs.push('Domain=' + opt.domain); + } + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + pairs.push('Path=' + opt.path); + } + + if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString()); + if (opt.httpOnly) pairs.push('HttpOnly'); + if (opt.secure) pairs.push('Secure'); + + return pairs.join('; '); +} + +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ + +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} diff --git a/5-3/node_modules/express/node_modules/cookie/package.json b/5-3/node_modules/express/node_modules/cookie/package.json new file mode 100644 index 0000000..01399d0 --- /dev/null +++ b/5-3/node_modules/express/node_modules/cookie/package.json @@ -0,0 +1,76 @@ +{ + "name": "cookie", + "description": "cookie parsing and serialization", + "version": "0.1.5", + "author": { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "cookie", + "cookies" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/cookie.git" + }, + "devDependencies": { + "istanbul": "0.3.20", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --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": "0dfc4876575cef2609cdc1082fccf832743822c2", + "bugs": { + "url": "https://github.com/jshttp/cookie/issues" + }, + "homepage": "https://github.com/jshttp/cookie", + "_id": "cookie@0.1.5", + "_shasum": "6ab9948a4b1ae21952cd2588530a4722d4044d7c", + "_from": "cookie@0.1.5", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "6ab9948a4b1ae21952cd2588530a4722d4044d7c", + "tarball": "http://registry.npmjs.org/cookie/-/cookie-0.1.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/debug/.jshintrc b/5-3/node_modules/express/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/5-3/node_modules/express/node_modules/debug/.npmignore b/5-3/node_modules/express/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/5-3/node_modules/express/node_modules/debug/History.md b/5-3/node_modules/express/node_modules/debug/History.md new file mode 100644 index 0000000..854c971 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/History.md @@ -0,0 +1,195 @@ + +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 +================== + + * 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/5-3/node_modules/express/node_modules/debug/Makefile b/5-3/node_modules/express/node_modules/debug/Makefile new file mode 100644 index 0000000..5cf4a59 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/Makefile @@ -0,0 +1,36 @@ + +# 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 dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +distclean: clean + @rm -rf node_modules + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean distclean diff --git a/5-3/node_modules/express/node_modules/debug/Readme.md b/5-3/node_modules/express/node_modules/debug/Readme.md new file mode 100644 index 0000000..b4f45e3 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/Readme.md @@ -0,0 +1,188 @@ +# 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'); +``` + +### 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 + - 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/5-3/node_modules/express/node_modules/debug/bower.json b/5-3/node_modules/express/node_modules/debug/bower.json new file mode 100644 index 0000000..6af573f --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/bower.json @@ -0,0 +1,28 @@ +{ + "name": "visionmedia-debug", + "main": "dist/debug.js", + "version": "2.2.0", + "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/5-3/node_modules/express/node_modules/debug/browser.js b/5-3/node_modules/express/node_modules/debug/browser.js new file mode 100644 index 0000000..7c76452 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/browser.js @@ -0,0 +1,168 @@ + +/** + * 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; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : 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) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.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/5-3/node_modules/express/node_modules/debug/component.json b/5-3/node_modules/express/node_modules/debug/component.json new file mode 100644 index 0000000..ca10637 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.2.0", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/5-3/node_modules/express/node_modules/debug/debug.js b/5-3/node_modules/express/node_modules/debug/debug.js new file mode 100644 index 0000000..7571a86 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * 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/5-3/node_modules/express/node_modules/debug/node.js b/5-3/node_modules/express/node_modules/debug/node.js new file mode 100644 index 0000000..1d392a8 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/node.js @@ -0,0 +1,209 @@ + +/** + * 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/5-3/node_modules/express/node_modules/debug/node_modules/ms/.npmignore b/5-3/node_modules/express/node_modules/debug/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/5-3/node_modules/express/node_modules/debug/node_modules/ms/History.md b/5-3/node_modules/express/node_modules/debug/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/debug/node_modules/ms/LICENSE b/5-3/node_modules/express/node_modules/debug/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/5-3/node_modules/express/node_modules/debug/node_modules/ms/README.md b/5-3/node_modules/express/node_modules/debug/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/5-3/node_modules/express/node_modules/debug/node_modules/ms/index.js b/5-3/node_modules/express/node_modules/debug/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/5-3/node_modules/express/node_modules/debug/node_modules/ms/package.json b/5-3/node_modules/express/node_modules/debug/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/debug/package.json b/5-3/node_modules/express/node_modules/debug/package.json new file mode 100644 index 0000000..24bb9c9 --- /dev/null +++ b/5-3/node_modules/express/node_modules/debug/package.json @@ -0,0 +1,73 @@ +{ + "name": "debug", + "version": "2.2.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "license": "MIT", + "dependencies": { + "ms": "0.7.1" + }, + "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": "b38458422b5aa8aa6d286b10dfe427e8a67e2b35", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@2.2.0", + "scripts": {}, + "_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "_from": "debug@>=2.2.0 <2.3.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "tarball": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/depd/History.md b/5-3/node_modules/express/node_modules/depd/History.md new file mode 100644 index 0000000..ace1171 --- /dev/null +++ b/5-3/node_modules/express/node_modules/depd/History.md @@ -0,0 +1,84 @@ +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/5-3/node_modules/express/node_modules/depd/LICENSE b/5-3/node_modules/express/node_modules/depd/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-3/node_modules/express/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-3/node_modules/express/node_modules/depd/Readme.md b/5-3/node_modules/express/node_modules/depd/Readme.md new file mode 100644 index 0000000..09bb979 --- /dev/null +++ b/5-3/node_modules/express/node_modules/depd/Readme.md @@ -0,0 +1,281 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction() { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: http://nodejs.org/download/ +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/5-3/node_modules/express/node_modules/depd/index.js b/5-3/node_modules/express/node_modules/depd/index.js new file mode 100644 index 0000000..fddcae8 --- /dev/null +++ b/5-3/node_modules/express/node_modules/depd/index.js @@ -0,0 +1,521 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace(str, namespace) { + var val = str.split(/[ ,]+/) + + namespace = String(namespace).toLowerCase() + + for (var i = 0 ; i < val.length; i++) { + if (!(str = val[i])) continue; + + // namespace contained + if (str === '*' || str.toLowerCase() === namespace) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor(obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter() { return value } + + if (descriptor.writable) { + descriptor.set = function setter(val) { return value = val } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString(arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString(stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate(message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced(namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log(message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + callSite = callSiteLocation(stack[1]) + callSite.name = site.name + file = callSite[0] + } else { + // get call site + i = 2 + site = callSiteLocation(stack[i]) + callSite = site + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? site.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + if (!message) { + message = callSite === site || !callSite.name + ? defaultMessage(site) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, message, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var msg = format.call(this, message, caller, stack.slice(i)) + process.stderr.write(msg + '\n', 'utf8') + + return +} + +/** + * Get call site location as array. + */ + +function callSiteLocation(callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage(site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain(msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor(msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' // bold cyan + + ' \x1b[33;1mdeprecated\x1b[22;39m' // bold yellow + + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation(callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace(obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter() { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter() { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError(namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return stackString = createStackString.call(this, stack) + }, + set: function setter(val) { + stackString = val + } + }) + + return error +} diff --git a/5-3/node_modules/express/node_modules/depd/lib/browser/index.js b/5-3/node_modules/express/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..f464e05 --- /dev/null +++ b/5-3/node_modules/express/node_modules/depd/lib/browser/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd(namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate(message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction(fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty(obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + return +} diff --git a/5-3/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js b/5-3/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js new file mode 100644 index 0000000..4b73381 --- /dev/null +++ b/5-3/node_modules/express/node_modules/depd/lib/compat/buffer-concat.js @@ -0,0 +1,35 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = bufferConcat + +/** + * Concatenate an array of Buffers. + */ + +function bufferConcat(bufs) { + var length = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + length += bufs[i].length + } + + var buf = new Buffer(length) + var pos = 0 + + for (var i = 0, len = bufs.length; i < len; i++) { + bufs[i].copy(buf, pos) + pos += bufs[i].length + } + + return buf +} diff --git a/5-3/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js b/5-3/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 0000000..9ecef34 --- /dev/null +++ b/5-3/node_modules/express/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation(callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString(callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName(obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/5-3/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js b/5-3/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 0000000..a05fceb --- /dev/null +++ b/5-3/node_modules/express/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount(emitter, type) { + return emitter.listeners(type).length +} diff --git a/5-3/node_modules/express/node_modules/depd/lib/compat/index.js b/5-3/node_modules/express/node_modules/depd/lib/compat/index.js new file mode 100644 index 0000000..aa3c1de --- /dev/null +++ b/5-3/node_modules/express/node_modules/depd/lib/compat/index.js @@ -0,0 +1,84 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('buffer') +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'bufferConcat', function bufferConcat() { + return Buffer.concat || require('./buffer-concat') +}) + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString() { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace(obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount() { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty(obj, prop, getter) { + function get() { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString(obj) { + return obj.toString() +} diff --git a/5-3/node_modules/express/node_modules/depd/package.json b/5-3/node_modules/express/node_modules/depd/package.json new file mode 100644 index 0000000..9da460a --- /dev/null +++ b/5-3/node_modules/express/node_modules/depd/package.json @@ -0,0 +1,67 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "1.1.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/dougwilson/nodejs-depd.git" + }, + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.3.5", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail test/", + "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": "78c659de20283e3a6bee92bda455e6daff01686a", + "bugs": { + "url": "https://github.com/dougwilson/nodejs-depd/issues" + }, + "homepage": "https://github.com/dougwilson/nodejs-depd", + "_id": "depd@1.1.0", + "_shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "_from": "depd@>=1.1.0 <1.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "e1bd82c6aab6ced965b97b88b17ed3e528ca18c3", + "tarball": "http://registry.npmjs.org/depd/-/depd-1.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/depd/-/depd-1.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/escape-html/LICENSE b/5-3/node_modules/express/node_modules/escape-html/LICENSE new file mode 100644 index 0000000..2e70de9 --- /dev/null +++ b/5-3/node_modules/express/node_modules/escape-html/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2013 TJ Holowaychuk +Copyright (c) 2015 Andreas Lubbe +Copyright (c) 2015 Tiancheng "Timothy" Gu + +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/5-3/node_modules/express/node_modules/escape-html/Readme.md b/5-3/node_modules/express/node_modules/escape-html/Readme.md new file mode 100644 index 0000000..653d9ea --- /dev/null +++ b/5-3/node_modules/express/node_modules/escape-html/Readme.md @@ -0,0 +1,43 @@ + +# escape-html + + Escape string for use in HTML + +## Example + +```js +var escape = require('escape-html'); +var html = escape('foo & bar'); +// -> foo & bar +``` + +## Benchmark + +``` +$ npm run-script bench + +> escape-html@1.0.3 bench nodejs-escape-html +> 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 + + 1 test completed. + 2 tests completed. + 3 tests completed. + + no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) + single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) + many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) +``` + +## License + + MIT \ No newline at end of file diff --git a/5-3/node_modules/express/node_modules/escape-html/index.js b/5-3/node_modules/express/node_modules/escape-html/index.js new file mode 100644 index 0000000..bf9e226 --- /dev/null +++ b/5-3/node_modules/express/node_modules/escape-html/index.js @@ -0,0 +1,78 @@ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} diff --git a/5-3/node_modules/express/node_modules/escape-html/package.json b/5-3/node_modules/express/node_modules/escape-html/package.json new file mode 100644 index 0000000..eb73427 --- /dev/null +++ b/5-3/node_modules/express/node_modules/escape-html/package.json @@ -0,0 +1,57 @@ +{ + "name": "escape-html", + "description": "Escape string for use in HTML", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "escape", + "html", + "utility" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/component/escape-html.git" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4" + }, + "files": [ + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "bench": "node benchmark/index.js" + }, + "gitHead": "7ac2ea3977fcac3d4c5be8d2a037812820c65f28", + "bugs": { + "url": "https://github.com/component/escape-html/issues" + }, + "homepage": "https://github.com/component/escape-html", + "_id": "escape-html@1.0.3", + "_shasum": "0258eae4d3d0c0974de1c169188ef0051d1d1988", + "_from": "escape-html@>=1.0.3 <1.1.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "0258eae4d3d0c0974de1c169188ef0051d1d1988", + "tarball": "http://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/etag/HISTORY.md b/5-3/node_modules/express/node_modules/etag/HISTORY.md new file mode 100644 index 0000000..bd0f26d --- /dev/null +++ b/5-3/node_modules/express/node_modules/etag/HISTORY.md @@ -0,0 +1,71 @@ +1.7.0 / 2015-06-08 +================== + + * Always include entity length in ETags for hash length extensions + * Generate non-Stats ETags using MD5 only (no longer CRC32) + * Improve stat performance by removing hashing + * Remove base64 padding in ETags to shorten + * Use MD5 instead of MD4 in weak ETags over 1KB + +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 +================== + + * deps: crc@3.2.1 + - Minor fixes + +1.5.0 / 2014-10-14 +================== + + * Improve string performance + * Slightly improve speed for weak ETags over 1KB + +1.4.0 / 2014-09-21 +================== + + * Support "fake" stats objects + * Support Node.js 0.6 + +1.3.1 / 2014-09-14 +================== + + * Use the (new and improved) `crc` for crc32 + +1.3.0 / 2014-08-29 +================== + + * Default strings to strong ETags + * Improve speed for weak ETags over 1KB + +1.2.1 / 2014-08-29 +================== + + * Use the (much faster) `buffer-crc32` for crc32 + +1.2.0 / 2014-08-24 +================== + + * Add support for file stat objects + +1.1.0 / 2014-08-24 +================== + + * Add fast-path for empty entity + * Add weak ETag generation + * Shrink size of generated ETags + +1.0.1 / 2014-08-24 +================== + + * Fix behavior of string containing Unicode + +1.0.0 / 2014-05-18 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/etag/LICENSE b/5-3/node_modules/express/node_modules/etag/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-3/node_modules/express/node_modules/etag/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-3/node_modules/express/node_modules/etag/README.md b/5-3/node_modules/express/node_modules/etag/README.md new file mode 100644 index 0000000..8da9e05 --- /dev/null +++ b/5-3/node_modules/express/node_modules/etag/README.md @@ -0,0 +1,165 @@ +# etag + +[![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] + +Create simple ETags + +## Installation + +```sh +$ npm install etag +``` + +## API + +```js +var etag = require('etag') +``` + +### etag(entity, [options]) + +Generate a strong ETag for the given entity. This should be the complete +body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By +default, a strong ETag is generated except for `fs.Stats`, which will +generate a weak ETag (this can be overwritten by `options.weak`). + +```js +res.setHeader('ETag', etag(body)) +``` + +#### Options + +`etag` accepts these properties in the options object. + +##### weak + +Specifies if the generated ETag will include the weak validator mark (that +is, the leading `W/`). The actual entity tag is the same. The default value +is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +```bash +$ npm run-script bench + +> 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 + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 289,198 ops/sec ±1.09% (190 runs sampled) +* buffer - weak x 287,838 ops/sec ±0.91% (189 runs sampled) +* string - strong x 284,586 ops/sec ±1.05% (192 runs sampled) +* string - weak x 287,439 ops/sec ±0.82% (192 runs sampled) + +> node benchmark/body1-1kb.js + + 1KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 212,423 ops/sec ±0.75% (193 runs sampled) +* buffer - weak x 211,871 ops/sec ±0.74% (194 runs sampled) + string - strong x 205,291 ops/sec ±0.86% (194 runs sampled) + string - weak x 208,463 ops/sec ±0.79% (192 runs sampled) + +> node benchmark/body2-5kb.js + + 5KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 92,901 ops/sec ±0.58% (195 runs sampled) +* buffer - weak x 93,045 ops/sec ±0.65% (192 runs sampled) + string - strong x 89,621 ops/sec ±0.68% (194 runs sampled) + string - weak x 90,070 ops/sec ±0.70% (196 runs sampled) + +> node benchmark/body3-10kb.js + + 10KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 54,220 ops/sec ±0.85% (192 runs sampled) +* buffer - weak x 54,069 ops/sec ±0.83% (191 runs sampled) + string - strong x 53,078 ops/sec ±0.53% (194 runs sampled) + string - weak x 53,849 ops/sec ±0.47% (197 runs sampled) + +> node benchmark/body4-100kb.js + + 100KB body + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* buffer - strong x 6,673 ops/sec ±0.15% (197 runs sampled) +* buffer - weak x 6,716 ops/sec ±0.12% (198 runs sampled) + string - strong x 6,357 ops/sec ±0.14% (197 runs sampled) + string - weak x 6,344 ops/sec ±0.21% (197 runs sampled) + +> node benchmark/stats.js + + stats + + 1 test completed. + 2 tests completed. + 3 tests completed. + 4 tests completed. + +* real - strong x 1,671,989 ops/sec ±0.13% (197 runs sampled) +* real - weak x 1,681,297 ops/sec ±0.12% (198 runs sampled) + fake - strong x 927,063 ops/sec ±0.14% (198 runs sampled) + fake - weak x 914,461 ops/sec ±0.41% (191 runs sampled) +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master +[downloads-image]: https://img.shields.io/npm/dm/etag.svg +[downloads-url]: https://npmjs.org/package/etag diff --git a/5-3/node_modules/express/node_modules/etag/index.js b/5-3/node_modules/express/node_modules/etag/index.js new file mode 100644 index 0000000..b582c84 --- /dev/null +++ b/5-3/node_modules/express/node_modules/etag/index.js @@ -0,0 +1,132 @@ +/*! + * etag + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = etag + +/** + * Module dependencies. + * @private + */ + +var crypto = require('crypto') +var Stats = require('fs').Stats + +/** + * Module variables. + * @private + */ + +var base64PadCharRegExp = /=+$/ +var toString = Object.prototype.toString + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag(entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-1B2M2Y8AsgTpgAmY7PhCfg"' + } + + // compute hash of entity + var hash = crypto + .createHash('md5') + .update(entity, 'utf8') + .digest('base64') + .replace(base64PadCharRegExp, '') + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag(entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats(obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + 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' + && 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag(stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} diff --git a/5-3/node_modules/express/node_modules/etag/package.json b/5-3/node_modules/express/node_modules/etag/package.json new file mode 100644 index 0000000..8dc110c --- /dev/null +++ b/5-3/node_modules/express/node_modules/etag/package.json @@ -0,0 +1,73 @@ +{ + "name": "etag", + "description": "Create simple ETags", + "version": "1.7.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "David Björklund", + "email": "david.bjorklund@gmail.com" + } + ], + "license": "MIT", + "keywords": [ + "etag", + "http", + "res" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/etag.git" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.3.14", + "mocha": "~1.21.4", + "seedrandom": "2.3.11" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "a511f5c8c930fd9546dbd88acb080f96bc788cfc", + "bugs": { + "url": "https://github.com/jshttp/etag/issues" + }, + "homepage": "https://github.com/jshttp/etag", + "_id": "etag@1.7.0", + "_shasum": "03d30b5f67dd6e632d2945d30d6652731a34d5d8", + "_from": "etag@>=1.7.0 <1.8.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "03d30b5f67dd6e632d2945d30d6652731a34d5d8", + "tarball": "http://registry.npmjs.org/etag/-/etag-1.7.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/etag/-/etag-1.7.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/finalhandler/HISTORY.md b/5-3/node_modules/express/node_modules/finalhandler/HISTORY.md new file mode 100644 index 0000000..78dddc0 --- /dev/null +++ b/5-3/node_modules/express/node_modules/finalhandler/HISTORY.md @@ -0,0 +1,98 @@ +0.4.1 / 2015-12-02 +================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + +0.4.0 / 2015-06-14 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + * Support `statusCode` property on `Error` objects + * Use `unpipe` module for unpiping requests + * deps: escape-html@1.0.2 + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.3.1 / 2014-10-16 +================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + +0.3.0 / 2014-09-17 +================== + + * Terminate in progress response only on error + * Use `on-finished` to determine request status + +0.2.0 / 2014-09-03 +================== + + * Set `X-Content-Type-Options: nosniff` header + * deps: debug@~2.0.0 + +0.1.0 / 2014-07-16 +================== + + * Respond after request fully read + - prevents hung responses and socket hang ups + * deps: debug@1.0.4 + +0.0.3 / 2014-07-11 +================== + + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.0.2 / 2014-06-19 +================== + + * Handle invalid status codes + +0.0.1 / 2014-06-05 +================== + + * deps: debug@1.0.2 + +0.0.0 / 2014-06-05 +================== + + * Extracted from connect/express diff --git a/5-3/node_modules/express/node_modules/finalhandler/LICENSE b/5-3/node_modules/express/node_modules/finalhandler/LICENSE new file mode 100644 index 0000000..b60a5ad --- /dev/null +++ b/5-3/node_modules/express/node_modules/finalhandler/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-3/node_modules/express/node_modules/finalhandler/README.md b/5-3/node_modules/express/node_modules/finalhandler/README.md new file mode 100644 index 0000000..6b171d4 --- /dev/null +++ b/5-3/node_modules/express/node_modules/finalhandler/README.md @@ -0,0 +1,133 @@ +# finalhandler + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js function to invoke as the final step to respond to HTTP request. + +## Installation + +```sh +$ npm install finalhandler +``` + +## API + +```js +var finalhandler = require('finalhandler') +``` + +### finalhandler(req, res, [options]) + +Returns function to be invoked as the final step for the given `req` and `res`. +This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will +write out a 404 response to the `res`. If it is truthy, an error response will +be written out to the `res`, and `res.statusCode` is set from `err.status`. + +The final handler will also unpipe anything from `req` when it is invoked. + +#### options.env + +By default, the environment is determined by `NODE_ENV` variable, but it can be +overridden by this option. + +#### options.onerror + +Provide a function to be called with the `err` when it exists. Can be used for +writing errors to a central location without excessive function generation. Called +as `onerror(err, req, res)`. + +## Examples + +### always 404 + +```js +var finalhandler = require('finalhandler') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + done() +}) + +server.listen(3000) +``` + +### perform simple action + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) +``` + +### use with middleware-style functions + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +var serve = serveStatic('public') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + serve(req, res, done) +}) + +server.listen(3000) +``` + +### keep log of all errors + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res, {onerror: logerror}) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) + +function logerror(err) { + console.error(err.stack || err.toString()) +} +``` + +## License + +[MIT](LICENSE) + +[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 +[node-url]: http://nodejs.org/download/ +[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 +[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg +[downloads-url]: https://npmjs.org/package/finalhandler diff --git a/5-3/node_modules/express/node_modules/finalhandler/index.js b/5-3/node_modules/express/node_modules/finalhandler/index.js new file mode 100644 index 0000000..0de7c6b --- /dev/null +++ b/5-3/node_modules/express/node_modules/finalhandler/index.js @@ -0,0 +1,151 @@ +/*! + * finalhandler + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('finalhandler') +var escapeHtml = require('escape-html') +var http = require('http') +var onFinished = require('on-finished') +var unpipe = require('unpipe') + +/** + * Module variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished + +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler(req, res, options) { + var opts = options || {} + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + + return function (err) { + var status = res.statusCode + + // ignore 404 on in-flight response + if (!err && res._header) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect err.statusCode + if (err.statusCode) { + status = err.statusCode + } + + // respect err.status + if (err.status) { + status = err.status + } + + // default status code to 500 + if (!status || status < 400) { + status = 500 + } + + // production gets a basic error message + var msg = env === 'production' + ? http.STATUS_CODES[status] + : err.stack || err.toString() + msg = escapeHtml(msg) + .replace(/\n/g, '
') + .replace(/ /g, '  ') + '\n' + } else { + status = 404 + msg = 'Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl || req.url) + '\n' + } + + debug('default %s', status) + + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } + + // cannot actually respond + if (res._header) { + return req.socket.destroy() + } + + send(req, res, status, msg) + } +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {string} body + * @private + */ + +function send(req, res, status, body) { + function write() { + res.statusCode = status + + // security header for content sniffing + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() +} diff --git a/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md b/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md new file mode 100644 index 0000000..85e0f8d --- /dev/null +++ b/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE b/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE new file mode 100644 index 0000000..aed0138 --- /dev/null +++ b/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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 +'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/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md b/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md new file mode 100644 index 0000000..e536ad2 --- /dev/null +++ b/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js b/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js new file mode 100644 index 0000000..15c3d97 --- /dev/null +++ b/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json b/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json new file mode 100644 index 0000000..5381079 --- /dev/null +++ b/5-3/node_modules/express/node_modules/finalhandler/node_modules/unpipe/package.json @@ -0,0 +1,59 @@ +{ + "name": "unpipe", + "description": "Unpipe a stream from all destinations", + "version": "1.0.0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/unpipe.git" + }, + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "d2df901c06487430e78dca62b6edb8bb2fc5e99d", + "bugs": { + "url": "https://github.com/stream-utils/unpipe/issues" + }, + "homepage": "https://github.com/stream-utils/unpipe", + "_id": "unpipe@1.0.0", + "_shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "_from": "unpipe@1.0.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "tarball": "http://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/finalhandler/package.json b/5-3/node_modules/express/node_modules/finalhandler/package.json new file mode 100644 index 0000000..0afe7fc --- /dev/null +++ b/5-3/node_modules/express/node_modules/finalhandler/package.json @@ -0,0 +1,81 @@ +{ + "name": "finalhandler", + "description": "Node.js final http responder", + "version": "0.4.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/finalhandler.git" + }, + "dependencies": { + "debug": "~2.2.0", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "unpipe": "~1.0.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "2.3.4", + "readable-stream": "2.0.4", + "supertest": "1.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "ac2036774059eb93dbac8475580e52433204d4d4", + "bugs": { + "url": "https://github.com/pillarjs/finalhandler/issues" + }, + "homepage": "https://github.com/pillarjs/finalhandler", + "_id": "finalhandler@0.4.1", + "_shasum": "85a17c6c59a94717d262d61230d4b0ebe3d4a14d", + "_from": "finalhandler@0.4.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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "85a17c6c59a94717d262d61230d4b0ebe3d4a14d", + "tarball": "http://registry.npmjs.org/finalhandler/-/finalhandler-0.4.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-0.4.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/fresh/HISTORY.md b/5-3/node_modules/express/node_modules/fresh/HISTORY.md new file mode 100644 index 0000000..3c95fbb --- /dev/null +++ b/5-3/node_modules/express/node_modules/fresh/HISTORY.md @@ -0,0 +1,38 @@ +0.3.0 / 2015-05-12 +================== + + * Add weak `ETag` matching support + +0.2.4 / 2014-09-07 +================== + + * Support Node.js 0.6 + +0.2.3 / 2014-09-07 +================== + + * Move repository to jshttp + +0.2.2 / 2014-02-19 +================== + + * Revert "Fix for blank page on Safari reload" + +0.2.1 / 2014-01-29 +================== + + * Fix for blank page on Safari reload + +0.2.0 / 2013-08-11 +================== + + * Return stale for `Cache-Control: no-cache` + +0.1.0 / 2012-06-15 +================== + * Add `If-None-Match: *` support + +0.0.1 / 2012-06-10 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/fresh/LICENSE b/5-3/node_modules/express/node_modules/fresh/LICENSE new file mode 100644 index 0000000..f527394 --- /dev/null +++ b/5-3/node_modules/express/node_modules/fresh/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/fresh/README.md b/5-3/node_modules/express/node_modules/fresh/README.md new file mode 100644 index 0000000..0813e30 --- /dev/null +++ b/5-3/node_modules/express/node_modules/fresh/README.md @@ -0,0 +1,58 @@ +# fresh + +[![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] + +HTTP response freshness testing + +## Installation + +``` +$ npm install fresh +``` + +## API + +```js +var fresh = require('fresh') +``` + +### fresh(req, res) + + Check freshness of `req` and `res` headers. + + When the cache is "fresh" __true__ is returned, + otherwise __false__ is returned to indicate that + the cache is now stale. + +## Example + +```js +var req = { 'if-none-match': 'tobi' }; +var res = { 'etag': 'luna' }; +fresh(req, res); +// => false + +var req = { 'if-none-match': 'tobi' }; +var res = { 'etag': 'tobi' }; +fresh(req, res); +// => true +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/fresh.svg +[npm-url]: https://npmjs.org/package/fresh +[node-version-image]: https://img.shields.io/node/v/fresh.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg +[travis-url]: https://travis-ci.org/jshttp/fresh +[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master +[downloads-image]: https://img.shields.io/npm/dm/fresh.svg +[downloads-url]: https://npmjs.org/package/fresh diff --git a/5-3/node_modules/express/node_modules/fresh/index.js b/5-3/node_modules/express/node_modules/fresh/index.js new file mode 100644 index 0000000..a900873 --- /dev/null +++ b/5-3/node_modules/express/node_modules/fresh/index.js @@ -0,0 +1,57 @@ + +/** + * Expose `fresh()`. + */ + +module.exports = fresh; + +/** + * Check freshness of `req` and `res` headers. + * + * When the cache is "fresh" __true__ is returned, + * otherwise __false__ is returned to indicate that + * the cache is now stale. + * + * @param {Object} req + * @param {Object} res + * @return {Boolean} + * @api public + */ + +function fresh(req, res) { + // defaults + var etagMatches = true; + var notModified = true; + + // fields + var modifiedSince = req['if-modified-since']; + var noneMatch = req['if-none-match']; + var lastModified = res['last-modified']; + var etag = res['etag']; + var cc = req['cache-control']; + + // unconditional request + if (!modifiedSince && !noneMatch) return false; + + // check for no-cache cache request directive + if (cc && cc.indexOf('no-cache') !== -1) return false; + + // parse if-none-match + if (noneMatch) noneMatch = noneMatch.split(/ *, */); + + // if-none-match + if (noneMatch) { + etagMatches = noneMatch.some(function (match) { + return match === '*' || match === etag || match === 'W/' + etag; + }); + } + + // if-modified-since + if (modifiedSince) { + modifiedSince = new Date(modifiedSince); + lastModified = new Date(lastModified); + notModified = lastModified <= modifiedSince; + } + + return !! (etagMatches && notModified); +} diff --git a/5-3/node_modules/express/node_modules/fresh/package.json b/5-3/node_modules/express/node_modules/fresh/package.json new file mode 100644 index 0000000..74332c4 --- /dev/null +++ b/5-3/node_modules/express/node_modules/fresh/package.json @@ -0,0 +1,87 @@ +{ + "name": "fresh", + "description": "HTTP response freshness testing", + "version": "0.3.0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "fresh", + "http", + "conditional", + "cache" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/fresh.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "14616c9748368ca08cd6a955dd88ab659b778634", + "bugs": { + "url": "https://github.com/jshttp/fresh/issues" + }, + "homepage": "https://github.com/jshttp/fresh", + "_id": "fresh@0.3.0", + "_shasum": "651f838e22424e7566de161d8358caa199f83d4f", + "_from": "fresh@0.3.0", + "_npmVersion": "1.4.28", + "_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": "651f838e22424e7566de161d8358caa199f83d4f", + "tarball": "http://registry.npmjs.org/fresh/-/fresh-0.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/merge-descriptors/HISTORY.md b/5-3/node_modules/express/node_modules/merge-descriptors/HISTORY.md new file mode 100644 index 0000000..486771f --- /dev/null +++ b/5-3/node_modules/express/node_modules/merge-descriptors/HISTORY.md @@ -0,0 +1,21 @@ +1.0.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.0.0 / 2015-03-01 +================== + + * Add option to only add new descriptors + * Add simple argument validation + * Add jsdoc to source file + +0.0.2 / 2013-12-14 +================== + + * Move repository to `component` organization + +0.0.1 / 2013-10-29 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/merge-descriptors/LICENSE b/5-3/node_modules/express/node_modules/merge-descriptors/LICENSE new file mode 100644 index 0000000..274bfd8 --- /dev/null +++ b/5-3/node_modules/express/node_modules/merge-descriptors/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 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 +'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/5-3/node_modules/express/node_modules/merge-descriptors/README.md b/5-3/node_modules/express/node_modules/merge-descriptors/README.md new file mode 100644 index 0000000..d593c0e --- /dev/null +++ b/5-3/node_modules/express/node_modules/merge-descriptors/README.md @@ -0,0 +1,48 @@ +# Merge Descriptors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Merge objects using descriptors. + +```js +var thing = { + get name() { + return 'jon' + } +} + +var animal = { + +} + +merge(animal, thing) + +animal.name === 'jon' +``` + +## API + +### merge(destination, source) + +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 + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/merge-descriptors.svg +[npm-url]: https://npmjs.org/package/merge-descriptors +[travis-image]: https://img.shields.io/travis/component/merge-descriptors/master.svg +[travis-url]: https://travis-ci.org/component/merge-descriptors +[coveralls-image]: https://img.shields.io/coveralls/component/merge-descriptors/master.svg +[coveralls-url]: https://coveralls.io/r/component/merge-descriptors?branch=master +[downloads-image]: https://img.shields.io/npm/dm/merge-descriptors.svg +[downloads-url]: https://npmjs.org/package/merge-descriptors diff --git a/5-3/node_modules/express/node_modules/merge-descriptors/index.js b/5-3/node_modules/express/node_modules/merge-descriptors/index.js new file mode 100644 index 0000000..573b132 --- /dev/null +++ b/5-3/node_modules/express/node_modules/merge-descriptors/index.js @@ -0,0 +1,60 @@ +/*! + * merge-descriptors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * 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 +} diff --git a/5-3/node_modules/express/node_modules/merge-descriptors/package.json b/5-3/node_modules/express/node_modules/merge-descriptors/package.json new file mode 100644 index 0000000..a65d2e8 --- /dev/null +++ b/5-3/node_modules/express/node_modules/merge-descriptors/package.json @@ -0,0 +1,138 @@ +{ + "name": "merge-descriptors", + "description": "Merge objects using descriptors", + "version": "1.0.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Mike Grabowski", + "email": "grabbou@gmail.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/component/merge-descriptors.git" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --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": "f26c49c3b423b0b2ac31f6e32a84e1632f2d7ac2", + "bugs": { + "url": "https://github.com/component/merge-descriptors/issues" + }, + "homepage": "https://github.com/component/merge-descriptors", + "_id": "merge-descriptors@1.0.1", + "_shasum": "b00aaa556dd8b44568150ec9d1b953f3f90cbb61", + "_from": "merge-descriptors@1.0.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "anthonyshort", + "email": "antshort@gmail.com" + }, + { + "name": "clintwood", + "email": "clint@anotherway.co.za" + }, + { + "name": "dfcreative", + "email": "df.creative@gmail.com" + }, + { + "name": "dominicbarnes", + "email": "dominic@dbarnes.info" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "ianstormtaylor", + "email": "ian@ianstormtaylor.com" + }, + { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + { + "name": "mattmueller", + "email": "mattmuelle@gmail.com" + }, + { + "name": "queckezz", + "email": "fabian.eichenberger@gmail.com" + }, + { + "name": "stephenmathieson", + "email": "me@stephenmathieson.com" + }, + { + "name": "thehydroimpulse", + "email": "dnfagnan@gmail.com" + }, + { + "name": "timaschew", + "email": "timaschew@gmail.com" + }, + { + "name": "timoxley", + "email": "secoif@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + { + "name": "trevorgerhardt", + "email": "trevorgerhardt@gmail.com" + }, + { + "name": "yields", + "email": "yields@icloud.com" + } + ], + "dist": { + "shasum": "b00aaa556dd8b44568150ec9d1b953f3f90cbb61", + "tarball": "http://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/methods/HISTORY.md b/5-3/node_modules/express/node_modules/methods/HISTORY.md new file mode 100644 index 0000000..c0ecf07 --- /dev/null +++ b/5-3/node_modules/express/node_modules/methods/HISTORY.md @@ -0,0 +1,29 @@ +1.1.2 / 2016-01-17 +================== + + * perf: enable strict mode + +1.1.1 / 2014-12-30 +================== + + * Improve `browserify` support + +1.1.0 / 2014-07-05 +================== + + * Add `CONNECT` method + +1.0.1 / 2014-06-02 +================== + + * Fix module to work with harmony transform + +1.0.0 / 2014-05-08 +================== + + * Add `PURGE` method + +0.1.0 / 2013-10-28 +================== + + * Add `http.METHODS` support diff --git a/5-3/node_modules/express/node_modules/methods/LICENSE b/5-3/node_modules/express/node_modules/methods/LICENSE new file mode 100644 index 0000000..220dc1a --- /dev/null +++ b/5-3/node_modules/express/node_modules/methods/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013-2014 TJ Holowaychuk +Copyright (c) 2015-2016 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/5-3/node_modules/express/node_modules/methods/README.md b/5-3/node_modules/express/node_modules/methods/README.md new file mode 100644 index 0000000..672a32b --- /dev/null +++ b/5-3/node_modules/express/node_modules/methods/README.md @@ -0,0 +1,51 @@ +# Methods + +[![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] + +HTTP verbs that Node.js core's HTTP parser supports. + +This module provides an export that is just like `http.METHODS` from Node.js core, +with the following differences: + + * All method names are lower-cased. + * Contains a fallback list of methods for Node.js versions that do not have a + `http.METHODS` export (0.10 and lower). + * Provides the fallback list when using tools like `browserify` without pulling + in the `http` shim module. + +## Install + +```bash +$ npm install methods +``` + +## API + +```js +var methods = require('methods') +``` + +### methods + +This is an array of lower-cased method names that Node.js supports. If Node.js +provides the `http.METHODS` export, then this is the same array lower-cased, +otherwise it is a snapshot of the verbs from Node.js 0.10. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat +[npm-url]: https://npmjs.org/package/methods +[node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/methods +[coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master +[downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat +[downloads-url]: https://npmjs.org/package/methods diff --git a/5-3/node_modules/express/node_modules/methods/index.js b/5-3/node_modules/express/node_modules/methods/index.js new file mode 100644 index 0000000..667a50b --- /dev/null +++ b/5-3/node_modules/express/node_modules/methods/index.js @@ -0,0 +1,69 @@ +/*! + * methods + * Copyright(c) 2013-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var http = require('http'); + +/** + * Module exports. + * @public + */ + +module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); + +/** + * Get the current Node.js methods. + * @private + */ + +function getCurrentNodeMethods() { + return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { + return method.toLowerCase(); + }); +} + +/** + * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * @private + */ + +function getBasicNodeMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect' + ]; +} diff --git a/5-3/node_modules/express/node_modules/methods/package.json b/5-3/node_modules/express/node_modules/methods/package.json new file mode 100644 index 0000000..fd072fc --- /dev/null +++ b/5-3/node_modules/express/node_modules/methods/package.json @@ -0,0 +1,88 @@ +{ + "name": "methods", + "description": "HTTP methods that node supports", + "version": "1.1.2", + "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+https://github.com/jshttp/methods.git" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE" + ], + "engines": { + "node": ">= 0.6" + }, + "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/" + }, + "browser": { + "http": false + }, + "keywords": [ + "http", + "methods" + ], + "gitHead": "25d257d913f1b94bd2d73581521ff72c81469140", + "bugs": { + "url": "https://github.com/jshttp/methods/issues" + }, + "homepage": "https://github.com/jshttp/methods", + "_id": "methods@1.1.2", + "_shasum": "5529a4d67654134edcc5266656835b0f851afcee", + "_from": "methods@>=1.1.2 <1.2.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "5529a4d67654134edcc5266656835b0f851afcee", + "tarball": "http://registry.npmjs.org/methods/-/methods-1.1.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/on-finished/HISTORY.md b/5-3/node_modules/express/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000..98ff0e9 --- /dev/null +++ b/5-3/node_modules/express/node_modules/on-finished/HISTORY.md @@ -0,0 +1,88 @@ +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +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 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/on-finished/LICENSE b/5-3/node_modules/express/node_modules/on-finished/LICENSE new file mode 100644 index 0000000..5931fd2 --- /dev/null +++ b/5-3/node_modules/express/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/on-finished/README.md b/5-3/node_modules/express/node_modules/on-finished/README.md new file mode 100644 index 0000000..a0e1157 --- /dev/null +++ b/5-3/node_modules/express/node_modules/on-finished/README.md @@ -0,0 +1,154 @@ +# on-finished + +[![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] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to 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, res) { + // clean up open fds, etc. + // err contains the error is request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to 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 = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg +[downloads-url]: https://npmjs.org/package/on-finished diff --git a/5-3/node_modules/express/node_modules/on-finished/index.js b/5-3/node_modules/express/node_modules/on-finished/index.js new file mode 100644 index 0000000..9abd98f --- /dev/null +++ b/5-3/node_modules/express/node_modules/on-finished/index.js @@ -0,0 +1,196 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener(msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish(error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket) + callback(socket) + } +} diff --git a/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE b/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md b/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js b/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json b/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json new file mode 100644 index 0000000..1d223fb --- /dev/null +++ b/5-3/node_modules/express/node_modules/on-finished/node_modules/ee-first/package.json @@ -0,0 +1,64 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jonathanong/ee-first.git" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "512e0ce4cc3643f603708f965a97b61b1a9c0441", + "bugs": { + "url": "https://github.com/jonathanong/ee-first/issues" + }, + "homepage": "https://github.com/jonathanong/ee-first", + "_id": "ee-first@1.1.1", + "_shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "_from": "ee-first@1.1.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", + "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/on-finished/package.json b/5-3/node_modules/express/node_modules/on-finished/package.json new file mode 100644 index 0000000..7b2ebdd --- /dev/null +++ b/5-3/node_modules/express/node_modules/on-finished/package.json @@ -0,0 +1,71 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.3.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/on-finished.git" + }, + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "34babcb58126a416fcf5205768204f2e12699dda", + "bugs": { + "url": "https://github.com/jshttp/on-finished/issues" + }, + "homepage": "https://github.com/jshttp/on-finished", + "_id": "on-finished@2.3.0", + "_shasum": "20f1336481b083cd75337992a16971aa2d906947", + "_from": "on-finished@>=2.3.0 <2.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "dist": { + "shasum": "20f1336481b083cd75337992a16971aa2d906947", + "tarball": "http://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/parseurl/HISTORY.md b/5-3/node_modules/express/node_modules/parseurl/HISTORY.md new file mode 100644 index 0000000..395041e --- /dev/null +++ b/5-3/node_modules/express/node_modules/parseurl/HISTORY.md @@ -0,0 +1,47 @@ +1.3.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.3.0 / 2014-08-09 +================== + + * Add `parseurl.original` for parsing `req.originalUrl` with fallback + * Return `undefined` if `req.url` is `undefined` + +1.2.0 / 2014-07-21 +================== + + * Cache URLs based on original value + * Remove no-longer-needed URL mis-parse work-around + * Simplify the "fast-path" `RegExp` + +1.1.3 / 2014-07-08 +================== + + * Fix typo + +1.1.2 / 2014-07-08 +================== + + * Seriously fix Node.js 0.8 compatibility + +1.1.1 / 2014-07-08 +================== + + * Fix Node.js 0.8 compatibility + +1.1.0 / 2014-07-08 +================== + + * Incorporate URL href-only parse fast-path + +1.0.1 / 2014-03-08 +================== + + * Add missing `require` + +1.0.0 / 2014-03-08 +================== + + * Genesis from `connect` diff --git a/5-3/node_modules/express/node_modules/parseurl/LICENSE b/5-3/node_modules/express/node_modules/parseurl/LICENSE new file mode 100644 index 0000000..ec7dfe7 --- /dev/null +++ b/5-3/node_modules/express/node_modules/parseurl/LICENSE @@ -0,0 +1,24 @@ + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/parseurl/README.md b/5-3/node_modules/express/node_modules/parseurl/README.md new file mode 100644 index 0000000..f4796eb --- /dev/null +++ b/5-3/node_modules/express/node_modules/parseurl/README.md @@ -0,0 +1,120 @@ +# parseurl + +[![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] + +Parse a URL with memoization. + +## Install + +```bash +$ npm install parseurl +``` + +## API + +```js +var parseurl = require('parseurl') +``` + +### parseurl(req) + +Parse the URL of the given request object (looks at the `req.url` property) +and return the result. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.url` does +not change will return a cached parsed object, rather than parsing again. + +### parseurl.original(req) + +Parse the original URL of the given request object and return the result. +This works by trying to parse `req.originalUrl` if it is a string, otherwise +parses `req.url`. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.originalUrl` +does not change will return a cached parsed object, rather than parsing again. + +## Benchmark + +```bash +$ npm run-script bench + +> parseurl@1.3.1 bench nodejs-parseurl +> node benchmark/index.js + +> node benchmark/fullurl.js + + Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 1,290,780 ops/sec ±0.46% (195 runs sampled) + nativeurl x 56,401 ops/sec ±0.22% (196 runs sampled) + parseurl x 55,231 ops/sec ±0.22% (194 runs sampled) + +> node benchmark/pathquery.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 1,986,668 ops/sec ±0.27% (190 runs sampled) + nativeurl x 98,740 ops/sec ±0.21% (195 runs sampled) + parseurl x 2,628,171 ops/sec ±0.36% (195 runs sampled) + +> node benchmark/samerequest.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 2,184,468 ops/sec ±0.40% (194 runs sampled) + nativeurl x 99,437 ops/sec ±0.71% (194 runs sampled) + parseurl x 10,498,005 ops/sec ±0.61% (186 runs sampled) + +> node benchmark/simplepath.js + + Parsing URL "/foo/bar" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 4,535,825 ops/sec ±0.27% (191 runs sampled) + nativeurl x 98,769 ops/sec ±0.54% (191 runs sampled) + parseurl x 4,164,865 ops/sec ±0.34% (192 runs sampled) + +> node benchmark/slash.js + + Parsing URL "/" + + 1 test completed. + 2 tests completed. + 3 tests completed. + + fasturl x 4,908,405 ops/sec ±0.42% (191 runs sampled) + nativeurl x 100,945 ops/sec ±0.59% (188 runs sampled) + parseurl x 4,333,208 ops/sec ±0.27% (194 runs sampled) +``` + +## License + + [MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/parseurl.svg +[npm-url]: https://npmjs.org/package/parseurl +[node-version-image]: https://img.shields.io/node/v/parseurl.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/pillarjs/parseurl/master.svg +[travis-url]: https://travis-ci.org/pillarjs/parseurl +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/parseurl/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master +[downloads-image]: https://img.shields.io/npm/dm/parseurl.svg +[downloads-url]: https://npmjs.org/package/parseurl diff --git a/5-3/node_modules/express/node_modules/parseurl/index.js b/5-3/node_modules/express/node_modules/parseurl/index.js new file mode 100644 index 0000000..56cc6ec --- /dev/null +++ b/5-3/node_modules/express/node_modules/parseurl/index.js @@ -0,0 +1,138 @@ +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var url = require('url') +var parse = url.parse +var Url = url.Url + +/** + * Pattern for a simple path case. + * See: https://github.com/joyent/node/pull/7878 + */ + +var simplePathRegExp = /^(\/\/?(?!\/)[^\?#\s]*)(\?[^#\s]*)?$/ + +/** + * Exports. + */ + +module.exports = parseurl +module.exports.original = originalurl + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @api public + */ + +function parseurl(req) { + var url = req.url + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return req._parsedUrl = parsed +}; + +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @api public + */ + +function originalurl(req) { + var url = req.originalUrl + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return req._parsedOriginalUrl = parsed +}; + +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @api private + */ + +function fastparse(str) { + // Try fast path regexp + // See: https://github.com/joyent/node/pull/7878 + var simplePath = typeof str === 'string' && simplePathRegExp.exec(str) + + // Construct simple URL + if (simplePath) { + var pathname = simplePath[1] + var search = simplePath[2] || null + var url = Url !== undefined + ? new Url() + : {} + url.path = str + url.href = str + url.pathname = pathname + url.search = search + url.query = search && search.substr(1) + + return url + } + + return parse(str) +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @api private + */ + +function fresh(url, parsedUrl) { + return typeof parsedUrl === 'object' + && parsedUrl !== null + && (Url === undefined || parsedUrl instanceof Url) + && parsedUrl._raw === url +} diff --git a/5-3/node_modules/express/node_modules/parseurl/package.json b/5-3/node_modules/express/node_modules/parseurl/package.json new file mode 100644 index 0000000..7ba6287 --- /dev/null +++ b/5-3/node_modules/express/node_modules/parseurl/package.json @@ -0,0 +1,89 @@ +{ + "name": "parseurl", + "description": "parse a url with memoization", + "version": "1.3.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/parseurl.git" + }, + "license": "MIT", + "devDependencies": { + "benchmark": "2.0.0", + "beautify-benchmark": "0.2.4", + "fast-url-parser": "1.1.3", + "istanbul": "0.4.2", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --check-leaks --bail --reporter spec test/", + "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": "6d22d376d75b927ab2b5347ce3a1d6735133dd43", + "bugs": { + "url": "https://github.com/pillarjs/parseurl/issues" + }, + "homepage": "https://github.com/pillarjs/parseurl", + "_id": "parseurl@1.3.1", + "_shasum": "c8ab8c9223ba34888aa64a297b28853bec18da56", + "_from": "parseurl@>=1.3.1 <1.4.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" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "c8ab8c9223ba34888aa64a297b28853bec18da56", + "tarball": "http://registry.npmjs.org/parseurl/-/parseurl-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/path-to-regexp/History.md b/5-3/node_modules/express/node_modules/path-to-regexp/History.md new file mode 100644 index 0000000..7f65878 --- /dev/null +++ b/5-3/node_modules/express/node_modules/path-to-regexp/History.md @@ -0,0 +1,36 @@ +0.1.7 / 2015-07-28 +================== + + * Fixed regression with escaped round brackets and matching groups. + +0.1.6 / 2015-06-19 +================== + + * Replace `index` feature by outputting all parameters, unnamed and named. + +0.1.5 / 2015-05-08 +================== + + * Add an index property for position in match result. + +0.1.4 / 2015-03-05 +================== + + * Add license information + +0.1.3 / 2014-07-06 +================== + + * Better array support + * Improved support for trailing slash in non-ending mode + +0.1.0 / 2014-03-06 +================== + + * add options.end + +0.0.2 / 2013-02-10 +================== + + * Update to match current express + * add .license property to component.json diff --git a/5-3/node_modules/express/node_modules/path-to-regexp/LICENSE b/5-3/node_modules/express/node_modules/path-to-regexp/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/5-3/node_modules/express/node_modules/path-to-regexp/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/5-3/node_modules/express/node_modules/path-to-regexp/Readme.md b/5-3/node_modules/express/node_modules/path-to-regexp/Readme.md new file mode 100644 index 0000000..95452a6 --- /dev/null +++ b/5-3/node_modules/express/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,35 @@ +# Path-to-RegExp + +Turn an Express-style path string such as `/user/:name` into a regular expression. + +**Note:** This is a legacy branch. You should upgrade to `1.x`. + +## Usage + +```javascript +var pathToRegexp = require('path-to-regexp'); +``` + +### pathToRegexp(path, keys, options) + + - **path** A string in the express format, an array of such strings, or a regular expression + - **keys** An array to be populated with the keys present in the url. Once the function completes, this will be an array of strings. + - **options** + - **options.sensitive** Defaults to false, set this to true to make routes case sensitive + - **options.strict** Defaults to false, set this to true to make the trailing slash matter. + - **options.end** Defaults to true, set this to false to only match the prefix of the URL. + +```javascript +var keys = []; +var exp = pathToRegexp('/foo/:bar', keys); +//keys = ['bar'] +//exp = /^\/foo\/(?:([^\/]+?))\/?$/i +``` + +## Live Demo + +You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/). + +## License + + MIT diff --git a/5-3/node_modules/express/node_modules/path-to-regexp/index.js b/5-3/node_modules/express/node_modules/path-to-regexp/index.js new file mode 100644 index 0000000..500d1da --- /dev/null +++ b/5-3/node_modules/express/node_modules/path-to-regexp/index.js @@ -0,0 +1,129 @@ +/** + * Expose `pathtoRegexp`. + */ + +module.exports = pathtoRegexp; + +/** + * Match matching groups in a regular expression. + */ +var MATCHING_GROUP_REGEXP = /\((?!\?)/g; + +/** + * Normalize the given path string, + * returning a regular expression. + * + * An empty array should be passed, + * which will contain the placeholder + * key names. For example "/user/:id" will + * then contain ["id"]. + * + * @param {String|RegExp|Array} path + * @param {Array} keys + * @param {Object} options + * @return {RegExp} + * @api private + */ + +function pathtoRegexp(path, keys, options) { + options = options || {}; + keys = keys || []; + var strict = options.strict; + var end = options.end !== false; + var flags = options.sensitive ? '' : 'i'; + var extraOffset = 0; + var keysOffset = keys.length; + var i = 0; + var name = 0; + var m; + + if (path instanceof RegExp) { + while (m = MATCHING_GROUP_REGEXP.exec(path.source)) { + keys.push({ + name: name++, + optional: false, + offset: m.index + }); + } + + return path; + } + + if (Array.isArray(path)) { + // Map array parts into regexps and return their source. We also pass + // the same keys and options instance into every generation to get + // consistent matching groups before we join the sources together. + path = path.map(function (value) { + return pathtoRegexp(value, keys, options).source; + }); + + return new RegExp('(?:' + path.join('|') + ')', flags); + } + + path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) + .replace(/\/\(/g, '/(?:') + .replace(/([\/\.])/g, '\\$1') + .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) { + slash = slash || ''; + format = format || ''; + capture = capture || '([^\\/' + format + ']+?)'; + optional = optional || ''; + + keys.push({ + name: key, + optional: !!optional, + offset: offset + extraOffset + }); + + var result = '' + + (optional ? '' : slash) + + '(?:' + + format + (optional ? slash : '') + capture + + (star ? '((?:[\\/' + format + '].+?)?)' : '') + + ')' + + optional; + + extraOffset += result.length - match.length; + + return result; + }) + .replace(/\*/g, function (star, index) { + var len = keys.length + + while (len-- > keysOffset && keys[len].offset > index) { + keys[len].offset += 3; // Replacement length minus asterisk length. + } + + return '(.*)'; + }); + + // This is a workaround for handling unnamed matching groups. + while (m = MATCHING_GROUP_REGEXP.exec(path)) { + var escapeCount = 0; + var index = m.index; + + while (path.charAt(--index) === '\\') { + escapeCount++; + } + + // It's possible to escape the bracket. + if (escapeCount % 2 === 1) { + continue; + } + + if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) { + keys.splice(keysOffset + i, 0, { + name: name++, // Unnamed matching groups must be consistently linear. + optional: false, + offset: m.index + }); + } + + i++; + } + + // If the path is non-ending, match until the end or a slash. + path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)')); + + return new RegExp(path, flags); +}; diff --git a/5-3/node_modules/express/node_modules/path-to-regexp/package.json b/5-3/node_modules/express/node_modules/path-to-regexp/package.json new file mode 100644 index 0000000..118b1e6 --- /dev/null +++ b/5-3/node_modules/express/node_modules/path-to-regexp/package.json @@ -0,0 +1,185 @@ +{ + "name": "path-to-regexp", + "description": "Express style path to RegExp utility", + "version": "0.1.7", + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "keywords": [ + "express", + "regexp" + ], + "component": { + "scripts": { + "path-to-regexp": "index.js" + } + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/component/path-to-regexp.git" + }, + "devDependencies": { + "mocha": "^1.17.1", + "istanbul": "^0.2.6" + }, + "gitHead": "039118d6c3c186d3f176c73935ca887a32a33d93", + "bugs": { + "url": "https://github.com/component/path-to-regexp/issues" + }, + "homepage": "https://github.com/component/path-to-regexp#readme", + "_id": "path-to-regexp@0.1.7", + "_shasum": "df604178005f522f15eb4490e7247a1bfaa67f8c", + "_from": "path-to-regexp@0.1.7", + "_npmVersion": "2.13.2", + "_nodeVersion": "2.3.3", + "_npmUser": { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "hughsk", + "email": "hughskennedy@gmail.com" + }, + { + "name": "timaschew", + "email": "timaschew@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "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": "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" + }, + { + "name": "dfcreative", + "email": "df.creative@gmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "df604178005f522f15eb4490e7247a1bfaa67f8c", + "tarball": "http://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/proxy-addr/HISTORY.md b/5-3/node_modules/express/node_modules/proxy-addr/HISTORY.md new file mode 100644 index 0000000..84f11aa --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/HISTORY.md @@ -0,0 +1,80 @@ +1.0.10 / 2015-12-09 +=================== + + * deps: ipaddr.js@1.0.5 + - Fix regression in `isValid` with non-string arguments + +1.0.9 / 2015-12-01 +================== + + * deps: ipaddr.js@1.0.4 + - Fix accepting some invalid IPv6 addresses + - Reject CIDRs with negative or overlong masks + * perf: enable strict mode + +1.0.8 / 2015-05-10 +================== + + * deps: ipaddr.js@1.0.1 + +1.0.7 / 2015-03-16 +================== + + * deps: ipaddr.js@0.1.9 + - Fix OOM on certain inputs to `isValid` + +1.0.6 / 2015-02-01 +================== + + * deps: ipaddr.js@0.1.8 + +1.0.5 / 2015-01-08 +================== + + * deps: ipaddr.js@0.1.6 + +1.0.4 / 2014-11-23 +================== + + * deps: ipaddr.js@0.1.5 + - Fix edge cases with `isValid` + +1.0.3 / 2014-09-21 +================== + + * Use `forwarded` npm module + +1.0.2 / 2014-09-18 +================== + + * Fix a global leak when multiple subnets are trusted + * Support Node.js 0.6 + * deps: ipaddr.js@0.1.3 + +1.0.1 / 2014-06-03 +================== + + * Fix links in npm package + +1.0.0 / 2014-05-08 +================== + + * Add `trust` argument to determine proxy trust on + * Accepts custom function + * Accepts IPv4/IPv6 address(es) + * Accepts subnets + * Accepts pre-defined names + * Add optional `trust` argument to `proxyaddr.all` to + stop at first untrusted + * Add `proxyaddr.compile` to pre-compile `trust` function + to make subsequent calls faster + +0.0.1 / 2014-05-04 +================== + + * Fix bad npm publish + +0.0.0 / 2014-05-04 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/proxy-addr/LICENSE b/5-3/node_modules/express/node_modules/proxy-addr/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/proxy-addr/README.md b/5-3/node_modules/express/node_modules/proxy-addr/README.md new file mode 100644 index 0000000..26f7fc0 --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/README.md @@ -0,0 +1,137 @@ +# proxy-addr + +[![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] + +Determine address of proxied request + +## Install + +```sh +$ npm install proxy-addr +``` + +## API + +```js +var proxyaddr = require('proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + +```js +proxyaddr(req, function(addr){ return addr === '127.0.0.1' }) +proxyaddr(req, function(addr, i){ return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +proxyaddr(req, ['fe80::/ffc0::']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + +```js +var trust = proxyaddr.compile('localhost') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master +[downloads-image]: https://img.shields.io/npm/dm/proxy-addr.svg +[downloads-url]: https://npmjs.org/package/proxy-addr diff --git a/5-3/node_modules/express/node_modules/proxy-addr/index.js b/5-3/node_modules/express/node_modules/proxy-addr/index.js new file mode 100644 index 0000000..3200efb --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/index.js @@ -0,0 +1,347 @@ +/*! + * proxy-addr + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = proxyaddr; +module.exports.all = alladdrs; +module.exports.compile = compile; + +/** + * Module dependencies. + */ + +var forwarded = require('forwarded'); +var ipaddr = require('ipaddr.js'); + +/** + * Variables. + */ + +var digitre = /^[0-9]+$/; +var isip = ipaddr.isValid; +var parseip = ipaddr.parse; + +/** + * Pre-defined IP ranges. + */ + +var ipranges = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +}; + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @api public + */ + +function alladdrs(req, trust) { + // get addresses + var addrs = forwarded(req); + + if (!trust) { + // Return all addresses + return addrs; + } + + if (typeof trust !== 'function') { + trust = compile(trust); + } + + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue; + + addrs.length = i + 1; + } + + return addrs; +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @api private + */ + +function compile(val) { + if (!val) { + throw new TypeError('argument is required'); + } + + var trust = typeof val === 'string' + ? [val] + : val; + + if (!Array.isArray(trust)) { + throw new TypeError('unsupported trust argument'); + } + + for (var i = 0; i < trust.length; i++) { + val = trust[i]; + + if (!ipranges.hasOwnProperty(val)) { + continue; + } + + // Splice in pre-defined range + val = ipranges[val]; + trust.splice.apply(trust, [i, 1].concat(val)); + i += val.length - 1; + } + + return compileTrust(compileRangeSubnets(trust)); +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @api private + */ + +function compileRangeSubnets(arr) { + var rangeSubnets = new Array(arr.length); + + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]); + } + + return rangeSubnets; +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @api private + */ + +function compileTrust(rangeSubnets) { + // Return optimized function based on length + var len = rangeSubnets.length; + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets); +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @api private + */ + +function parseipNotation(note) { + var ip; + var kind; + var max; + var pos = note.lastIndexOf('/'); + var range; + + ip = pos !== -1 + ? note.substring(0, pos) + : note; + + if (!isip(ip)) { + throw new TypeError('invalid IP address: ' + ip); + } + + ip = parseip(ip); + + kind = ip.kind(); + max = kind === 'ipv6' + ? 128 + : 32; + + range = pos !== -1 + ? note.substring(pos + 1, note.length) + : max; + + if (typeof range !== 'number') { + range = digitre.test(range) + ? parseInt(range, 10) + : isip(range) + ? parseNetmask(range) + : 0; + } + + if (ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address(); + range = range <= max + ? range - 96 + : range; + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note); + } + + return [ip, range]; +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} note + * @api private + */ + +function parseNetmask(netmask) { + var ip = parseip(netmask); + var parts; + var size; + + switch (ip.kind()) { + case 'ipv4': + parts = ip.octets; + size = 8; + break; + case 'ipv6': + parts = ip.parts; + size = 16; + break; + } + + var max = Math.pow(2, size) - 1; + var part; + var range = 0; + + for (var i = 0; i < parts.length; i++) { + part = parts[i] & max; + + if (part === max) { + range += size; + continue; + } + + while (part) { + part = (part << 1) & max; + range += 1; + } + + break; + } + + return range; +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @api public + */ + +function proxyaddr(req, trust) { + if (!req) { + throw new TypeError('req argument is required'); + } + + if (!trust) { + throw new TypeError('trust argument is required'); + } + + var addrs = alladdrs(req, trust); + var addr = addrs[addrs.length - 1]; + + return addr; +} + +/** + * Static trust function to trust nothing. + * + * @api private + */ + +function trustNone() { + return false; +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @api private + */ + +function trustMulti(subnets) { + return function trust(addr) { + if (!isip(addr)) return false; + + var ip = parseip(addr); + var ipv4; + var kind = ip.kind(); + var subnet; + var subnetip; + var subnetkind; + var subnetrange; + var trusted; + + for (var i = 0; i < subnets.length; i++) { + subnet = subnets[i]; + subnetip = subnet[0]; + subnetkind = subnetip.kind(); + subnetrange = subnet[1]; + trusted = ip; + + if (kind !== subnetkind) { + if (kind !== 'ipv6' || subnetkind !== 'ipv4' || !ip.isIPv4MappedAddress()) { + continue; + } + + // Store addr as IPv4 + ipv4 = ipv4 || ip.toIPv4Address(); + trusted = ipv4; + } + + if (trusted.match(subnetip, subnetrange)) return true; + } + + return false; + }; +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @api private + */ + +function trustSingle(subnet) { + var subnetip = subnet[0]; + var subnetkind = subnetip.kind(); + var subnetisipv4 = subnetkind === 'ipv4'; + var subnetrange = subnet[1]; + + return function trust(addr) { + if (!isip(addr)) return false; + + var ip = parseip(addr); + var kind = ip.kind(); + + return kind === subnetkind + ? ip.match(subnetip, subnetrange) + : subnetisipv4 && kind === 'ipv6' && ip.isIPv4MappedAddress() + ? ip.toIPv4Address().match(subnetip, subnetrange) + : false; + }; +} diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md new file mode 100644 index 0000000..97fa1d1 --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/HISTORY.md @@ -0,0 +1,4 @@ +0.1.0 / 2014-09-21 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md new file mode 100644 index 0000000..2b4988f --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/README.md @@ -0,0 +1,53 @@ +# forwarded + +[![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] + +Parse HTTP X-Forwarded-For header + +## Installation + +```sh +$ npm install forwarded +``` + +## API + +```js +var forwarded = require('forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`. In reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/forwarded.svg?style=flat +[npm-url]: https://npmjs.org/package/forwarded +[node-version-image]: https://img.shields.io/node/v/forwarded.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/forwarded.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/forwarded +[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master +[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg?style=flat +[downloads-url]: https://npmjs.org/package/forwarded diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js new file mode 100644 index 0000000..2f5c340 --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js @@ -0,0 +1,35 @@ +/*! + * forwarded + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {Object} req + * @api public + */ + +function forwarded(req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = (req.headers['x-forwarded-for'] || '') + .split(/ *, */) + .filter(Boolean) + .reverse() + var socketAddr = req.connection.remoteAddress + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json new file mode 100644 index 0000000..7d24004 --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/package.json @@ -0,0 +1,65 @@ +{ + "name": "forwarded", + "description": "Parse HTTP X-Forwarded-For header", + "version": "0.1.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "keywords": [ + "x-forwarded-for", + "http", + "req" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/forwarded.git" + }, + "devDependencies": { + "istanbul": "0.3.2", + "mocha": "~1.21.4" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "e9a9faeb3cfaadf40eb57d144fff26bca9b818e8", + "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 <0.2.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", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore new file mode 100644 index 0000000..7a1537b --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore @@ -0,0 +1,2 @@ +.idea +node_modules diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml new file mode 100644 index 0000000..aa3d14a --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.travis.yml @@ -0,0 +1,10 @@ +language: node_js + +node_js: + - "0.10" + - "0.11" + - "0.12" + - "4.0" + - "4.1" + - "4.2" + - "5" diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile new file mode 100644 index 0000000..7fd355a --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile @@ -0,0 +1,18 @@ +fs = require 'fs' +CoffeeScript = require 'coffee-script' +nodeunit = require 'nodeunit' +UglifyJS = require 'uglify-js' + +task 'build', 'build the JavaScript files from CoffeeScript source', build = (cb) -> + source = fs.readFileSync 'src/ipaddr.coffee' + fs.writeFileSync 'lib/ipaddr.js', CoffeeScript.compile source.toString() + + invoke 'test' + invoke 'compress' + +task 'test', 'run the bundled tests', (cb) -> + nodeunit.reporters.default.run ['test'] + +task 'compress', 'uglify the resulting javascript', (cb) -> + result = UglifyJS.minify('lib/ipaddr.js') + fs.writeFileSync('ipaddr.min.js', result.code) diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE new file mode 100644 index 0000000..3493f0d --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011 Peter Zotov + +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/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md new file mode 100644 index 0000000..f4f8776 --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md @@ -0,0 +1,161 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +var ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and +`ipaddr.process`. All of them receive a string as a single parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 couterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. +Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); +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"` +(the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with both +IPv6 and IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +var rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "he.net" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. +(Actually, JavaScript mostly does not know about byte buffers. They are emulated with +arrays of numbers, each in range of 0..255.) + +```js +var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them +have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address +for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with +the `::` substitution); the `toNormalizedString()` method will return an address where +all zeroes are explicit. + +For example: + +```js +var addr = ipaddr.parse("2001:0db8::0001"); +addr.toString(); // => "2001:db8::1" +addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +var addr = ipaddr.parse("192.168.1.1"); +addr.octets // => [192, 168, 1, 1] +``` diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json new file mode 100644 index 0000000..bc04ffe --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/bower.json @@ -0,0 +1,29 @@ +{ + "name": "ipaddr.js", + "version": "1.0.5", + "homepage": "https://github.com/whitequark/ipaddr.js", + "authors": [ + "whitequark " + ], + "description": "IP address manipulation library in JavaScript (CoffeeScript, actually)", + "main": "lib/ipaddr.js", + "moduleType": [ + "globals", + "node" + ], + "keywords": [ + "javscript", + "ip", + "address", + "ipv4", + "ipv6" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 0000000..ee5179d --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.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),r[i]>>o!==t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(e in t)for(i=t[e],!i[0]||i[0]instanceof Array||(i=[i]),a=0,s=i.length;s>a;a++)if(o=i[a],r.match.apply(r,o))return e;return n},t.IPv4=function(){function r(r){var t,n,e;if(4!==r.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(n=0,e=r.length;e>n;n++)if(t=r[n],!(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 n;if(void 0===t&&(n=r,r=n[0],t=n[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}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(o=t.slice(1,6),a=[],r=0,e=o.length;e>r;r++)i=o[r],a.push(n(i));return a}();if(t=r.match(e.longValue)){if(a=n(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,n,e;if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8");for(n=0,e=r.length;e>n;n++)if(t=r[n],!(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,n,e,i,o,a;for(i=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),r=[],n=function(t){return r.push(t)},e=0,o=0,a=i.length;a>o;o++)switch(t=i[o],e){case 0:n("0"===t?"":t),e=1;break;case 1:"0"===t?e=2:n(t);break;case 2:"0"!==t&&(n(""),n(t),e=3);break;case 3:n(t)}return 2===e&&(n(""),n("")),r.join(":")},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],i=this.parts,n=0,e=i.length;e>n;n++)t=i[n],r.push(t>>8),r.push(255&t);return r},r.prototype.toNormalizedString=function(){var r;return 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).join(":")},r.prototype.match=function(r,t){var n;if(void 0===t&&(n=r,r=n[0],t=n[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,n,e;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=this.parts.slice(-2),r=e[0],n=e[1],new t.IPv4([r>>8,255&r,n>>8,255&n])},r}(),i="(?:[0-9a-f]+::?)+",o={"native":new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+(""+n+"\\."+n+"\\."+n+"\\."+n+"$"),"i")},r=function(r,t){var n,e,i,o,a;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for(n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(a=t-n,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,n,e,o;for(e=r.split(":"),o=[],t=0,n=e.length;n>t;t++)i=e[t],o.push(parseInt(i,16));return o}()},t.IPv6.parser=function(t){var n,e;return t.match(o["native"])?r(t,8):(n=t.match(o.transitional))&&(e=r(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},t.IPv4.isIPv4=t.IPv6.isIPv6=function(r){return null!==this.parser(r)},t.IPv4.isValid=function(r){var t;try{return new this(this.parser(r)),!0}catch(n){return t=n,!1}},t.IPv6.isValid=function(r){var t;if("string"==typeof r&&-1===r.indexOf(":"))return!1;try{return new this(this.parser(r)),!0}catch(n){return t=n,!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=function(r){var t,n;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&32>=t))return[this.parse(n[1]),t];throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv6.parseCIDR=function(r){var t,n;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&128>=t))return[this.parse(n[1]),t];throw new Error("ipaddr: string is not formatted like an IPv6 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 n;try{return t.IPv6.parseCIDR(r)}catch(e){n=e;try{return t.IPv4.parseCIDR(r)}catch(e){throw n=e,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/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js new file mode 100644 index 0000000..ef179b4 --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js @@ -0,0 +1,467 @@ +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root; + + ipaddr = {}; + + root = this; + + if ((typeof module !== "undefined" && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } + + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var rangeName, rangeSubnets, subnet, _i, _len; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (_i = 0, _len = rangeSubnets.length; _i < _len; _i++) { + subnet = rangeSubnets[_i]; + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + return defaultName; + }; + + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var octet, _i, _len; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (_i = 0, _len = octets.length; _i < _len; _i++) { + octet = octets[_i]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet is a byte"); + } + } + this.octets = octets; + } + + IPv4.prototype.kind = function() { + return 'ipv4'; + }; + + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + + 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"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; + + return IPv4; + + })(); + + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; + + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var _i, _len, _ref, _results; + _ref = match.slice(1, 6); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(parseIntAuto(part)); + } + return _results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var _i, _results; + _results = []; + for (shift = _i = 0; _i <= 24; shift = _i += 8) { + _results.push((value >> shift) & 0xff); + } + return _results; + })()).reverse(); + } else { + return null; + } + }; + + ipaddr.IPv6 = (function() { + function IPv6(parts) { + var part, _i, _len; + if (parts.length !== 8) { + throw new Error("ipaddr: ipv6 part count should be 8"); + } + for (_i = 0, _len = parts.length; _i < _len; _i++) { + part = parts[_i]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit to two octets"); + } + } + this.parts = parts; + } + + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + + IPv6.prototype.toString = function() { + var compactStringParts, part, pushPart, state, stringParts, _i, _len; + stringParts = (function() { + var _i, _len, _ref, _results; + _ref = this.parts; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(part.toString(16)); + } + return _results; + }).call(this); + compactStringParts = []; + pushPart = function(part) { + return compactStringParts.push(part); + }; + state = 0; + for (_i = 0, _len = stringParts.length; _i < _len; _i++) { + part = stringParts[_i]; + switch (state) { + case 0: + if (part === '0') { + pushPart(''); + } else { + pushPart(part); + } + state = 1; + break; + case 1: + if (part === '0') { + state = 2; + } else { + pushPart(part); + } + break; + case 2: + if (part !== '0') { + pushPart(''); + pushPart(part); + state = 3; + } + break; + case 3: + pushPart(part); + } + } + if (state === 2) { + pushPart(''); + pushPart(''); + } + return compactStringParts.join(":"); + }; + + IPv6.prototype.toByteArray = function() { + var bytes, part, _i, _len, _ref; + bytes = []; + _ref = this.parts; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; + + IPv6.prototype.toNormalizedString = function() { + var part; + return ((function() { + var _i, _len, _ref, _results; + _ref = this.parts; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(part.toString(16)); + } + return _results; + }).call(this)).join(":"); + }; + + 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"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; + + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; + + IPv6.prototype.toIPv4Address = function() { + var high, low, _ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + _ref = this.parts.slice(-2), high = _ref[0], low = _ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + return IPv6; + + })(); + + ipv6Part = "(?:[0-9a-f]+::?)+"; + + ipv6Regexes = { + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + ("" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$"), 'i') + }; + + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + return (function() { + var _i, _len, _ref, _results; + _ref = string.split(":"); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + part = _ref[_i]; + _results.push(parseInt(part, 16)); + } + return _results; + })(); + }; + + ipaddr.IPv6.parser = function(string) { + var match, parts; + if (string.match(ipv6Regexes['native'])) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + parts = expandIPv6(match[1].slice(0, -1), 6); + if (parts) { + parts.push(parseInt(match[2]) << 8 | parseInt(match[3])); + parts.push(parseInt(match[4]) << 8 | parseInt(match[5])); + return parts; + } + } + return null; + }; + + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (_error) { + e = _error; + return false; + } + }; + + ipaddr.IPv6.isValid = function(string) { + var e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + new this(this.parser(string)); + return true; + } catch (_error) { + e = _error; + return false; + } + }; + + ipaddr.IPv4.parse = ipaddr.IPv6.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + return [this.parse(match[1]), maskLength]; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + return [this.parse(match[1]), maskLength]; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + + 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); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + +}).call(this); diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json new file mode 100644 index 0000000..6b61f32 --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json @@ -0,0 +1,60 @@ +{ + "name": "ipaddr.js", + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "version": "1.0.5", + "author": { + "name": "whitequark", + "email": "whitequark@whitequark.org" + }, + "directories": { + "lib": "./lib" + }, + "dependencies": {}, + "devDependencies": { + "coffee-script": "~1.6", + "nodeunit": ">=0.8.2 <0.8.7", + "uglify-js": "latest" + }, + "scripts": { + "test": "cake build test" + }, + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "repository": { + "type": "git", + "url": "git://github.com/whitequark/ipaddr.js.git" + }, + "main": "./lib/ipaddr", + "engines": { + "node": ">= 0.10" + }, + "license": "MIT", + "gitHead": "46438c8bfa187505b7007a277f09a4a9e73d5686", + "bugs": { + "url": "https://github.com/whitequark/ipaddr.js/issues" + }, + "_id": "ipaddr.js@1.0.5", + "_shasum": "5fa78cf301b825c78abc3042d812723049ea23c7", + "_from": "ipaddr.js@1.0.5", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "whitequark", + "email": "whitequark@whitequark.org" + }, + "maintainers": [ + { + "name": "whitequark", + "email": "whitequark@whitequark.org" + } + ], + "dist": { + "shasum": "5fa78cf301b825c78abc3042d812723049ea23c7", + "tarball": "http://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.0.5.tgz" + }, + "_resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.0.5.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/whitequark/ipaddr.js#readme" +} diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee new file mode 100644 index 0000000..550174f --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee @@ -0,0 +1,396 @@ +# Define the main object +ipaddr = {} + +root = this + +# Export for both the CommonJS and browser-like environment +if module? && module.exports + module.exports = ipaddr +else + root['ipaddr'] = ipaddr + +# A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher. +matchCIDR = (first, second, partSize, cidrBits) -> + if first.length != second.length + throw new Error "ipaddr: cannot match CIDR for objects with different lengths" + + part = 0 + while cidrBits > 0 + shift = partSize - cidrBits + shift = 0 if shift < 0 + + if first[part] >> shift != second[part] >> shift + return false + + cidrBits -= partSize + part += 1 + + return true + +# An utility function to ease named range matching. See examples below. +ipaddr.subnetMatch = (address, rangeList, defaultName='unicast') -> + for rangeName, rangeSubnets of rangeList + # ECMA5 Array.isArray isn't available everywhere + if rangeSubnets[0] && !(rangeSubnets[0] instanceof Array) + rangeSubnets = [ rangeSubnets ] + + for subnet in rangeSubnets + return rangeName if address.match.apply(address, subnet) + + return defaultName + +# An IPv4 address (RFC791). +class ipaddr.IPv4 + # Constructs a new IPv4 address from an array of four octets. + # Verifies the input. + constructor: (octets) -> + if octets.length != 4 + throw new Error "ipaddr: ipv4 octet count should be 4" + + for octet in octets + if !(0 <= octet <= 255) + throw new Error "ipaddr: ipv4 octet is a byte" + + @octets = octets + + # The 'kind' method exists on both IPv4 and IPv6 classes. + kind: -> + return 'ipv4' + + # Returns the address in convenient, decimal-dotted format. + toString: -> + return @octets.join "." + + # Returns an array of byte-sized values in network order + toByteArray: -> + return @octets.slice(0) # octets.clone + + # 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" + + return matchCIDR(this.octets, other.octets, 8, cidrRange) + + # Special IPv4 address ranges. + SpecialRanges: + unspecified: [ + [ new IPv4([0, 0, 0, 0]), 8 ] + ] + broadcast: [ + [ new IPv4([255, 255, 255, 255]), 32 ] + ] + multicast: [ # RFC3171 + [ new IPv4([224, 0, 0, 0]), 4 ] + ] + linkLocal: [ # RFC3927 + [ new IPv4([169, 254, 0, 0]), 16 ] + ] + loopback: [ # RFC5735 + [ new IPv4([127, 0, 0, 0]), 8 ] + ] + private: [ # RFC1918 + [ new IPv4([10, 0, 0, 0]), 8 ] + [ new IPv4([172, 16, 0, 0]), 12 ] + [ new IPv4([192, 168, 0, 0]), 16 ] + ] + reserved: [ # Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700 + [ new IPv4([192, 0, 0, 0]), 24 ] + [ new IPv4([192, 0, 2, 0]), 24 ] + [ new IPv4([192, 88, 99, 0]), 24 ] + [ new IPv4([198, 51, 100, 0]), 24 ] + [ new IPv4([203, 0, 113, 0]), 24 ] + [ new IPv4([240, 0, 0, 0]), 4 ] + ] + + # Checks if the address corresponds to one of the special ranges. + range: -> + return ipaddr.subnetMatch(this, @SpecialRanges) + + # Convrets this IPv4 address to an IPv4-mapped IPv6 address. + toIPv4MappedAddress: -> + return ipaddr.IPv6.parse "::ffff:#{@toString()}" + +# A list of regular expressions that match arbitrary IPv4 addresses, +# for which a number of weird notations exist. +# Note that an address like 0010.0xa5.1.1 is considered legal. +ipv4Part = "(0?\\d+|0x[a-f0-9]+)" +ipv4Regexes = + fourOctet: new RegExp "^#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' + longValue: new RegExp "^#{ipv4Part}$", 'i' + +# Classful variants (like a.b, where a is an octet, and b is a 24-bit +# value representing last three octets; this corresponds to a class C +# address) are omitted due to classless nature of modern Internet. +ipaddr.IPv4.parser = (string) -> + parseIntAuto = (string) -> + if string[0] == "0" && string[1] != "x" + parseInt(string, 8) + else + parseInt(string) + + # parseInt recognizes all that octal & hexadecimal weirdness for us + if match = string.match(ipv4Regexes.fourOctet) + return (parseIntAuto(part) for part in match[1..5]) + else if match = string.match(ipv4Regexes.longValue) + value = parseIntAuto(match[1]) + if value > 0xffffffff || value < 0 + throw new Error "ipaddr: address outside defined range" + return ((value >> shift) & 0xff for shift in [0..24] by 8).reverse() + else + return null + +# An IPv6 address (RFC2460) +class ipaddr.IPv6 + # Constructs an IPv6 address from an array of eight 16-bit parts. + # Throws an error if the input is invalid. + constructor: (parts) -> + if parts.length != 8 + throw new Error "ipaddr: ipv6 part count should be 8" + + for part in parts + if !(0 <= part <= 0xffff) + throw new Error "ipaddr: ipv6 part should fit to two octets" + + @parts = parts + + # The 'kind' method exists on both IPv4 and IPv6 classes. + kind: -> + return 'ipv6' + + # Returns the address in compact, human-readable format like + # 2001:db8:8:66::1 + toString: -> + stringParts = (part.toString(16) for part in @parts) + + compactStringParts = [] + pushPart = (part) -> compactStringParts.push part + + state = 0 + for part in stringParts + switch state + when 0 + if part == '0' + pushPart('') + else + pushPart(part) + + state = 1 + when 1 + if part == '0' + state = 2 + else + pushPart(part) + when 2 + unless part == '0' + pushPart('') + pushPart(part) + state = 3 + when 3 + pushPart(part) + + if state == 2 + pushPart('') + pushPart('') + + return compactStringParts.join ":" + + # Returns an array of byte-sized values in network order + toByteArray: -> + bytes = [] + for part in @parts + bytes.push(part >> 8) + bytes.push(part & 0xff) + + return bytes + + # Returns the address in expanded format with all zeroes included, like + # 2001:db8:8:66:0:0:0:1 + toNormalizedString: -> + return (part.toString(16) for part in @parts).join ":" + + # 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" + + return matchCIDR(this.parts, other.parts, 16, cidrRange) + + # Special IPv6 ranges + SpecialRanges: + unspecified: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128 ] # RFC4291, here and after + linkLocal: [ new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10 ] + multicast: [ new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8 ] + loopback: [ new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128 ] + uniqueLocal: [ new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7 ] + ipv4Mapped: [ new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96 ] + rfc6145: [ new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96 ] # RFC6145 + rfc6052: [ new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96 ] # RFC6052 + '6to4': [ new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16 ] # RFC3056 + teredo: [ new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32 ] # RFC6052, RFC6146 + reserved: [ + [ new IPv6([ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32 ] # RFC4291 + ] + + # Checks if the address corresponds to one of the special ranges. + range: -> + return ipaddr.subnetMatch(this, @SpecialRanges) + + # Checks if this address is an IPv4-mapped IPv6 address. + isIPv4MappedAddress: -> + return @range() == 'ipv4Mapped' + + # Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address. + # Throws an error otherwise. + toIPv4Address: -> + unless @isIPv4MappedAddress() + throw new Error "ipaddr: trying to convert a generic ipv6 address to ipv4" + + [high, low] = @parts[-2..-1] + + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]) + +# IPv6-matching regular expressions. +# For IPv6, the task is simpler: it is enough to match the colon-delimited +# hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at +# the end. +ipv6Part = "(?:[0-9a-f]+::?)+" +ipv6Regexes = + native: new RegExp "^(::)?(#{ipv6Part})?([0-9a-f]+)?(::)?$", 'i' + transitional: new RegExp "^((?:#{ipv6Part})|(?:::)(?:#{ipv6Part})?)" + + "#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}\\.#{ipv4Part}$", 'i' + +# Expand :: in an IPv6 address or address part consisting of `parts` groups. +expandIPv6 = (string, parts) -> + # More than one '::' means invalid adddress + if string.indexOf('::') != string.lastIndexOf('::') + return null + + # How many parts do we already have? + colonCount = 0 + lastColon = -1 + while (lastColon = string.indexOf(':', lastColon + 1)) >= 0 + colonCount++ + + # 0::0 is two parts more than :: + colonCount-- if string.substr(0, 2) == '::' + colonCount-- if string.substr(-2, 2) == '::' + + # The following loop would hang if colonCount > parts + if colonCount > parts + return null + + # replacement = ':' + '0:' * (parts - colonCount) + replacementCount = parts - colonCount + replacement = ':' + while replacementCount-- + replacement += '0:' + + # Insert the missing zeroes + string = string.replace('::', replacement) + + # Trim any garbage which may be hanging around if :: was at the edge in + # the source string + string = string[1..-1] if string[0] == ':' + string = string[0..-2] if string[string.length-1] == ':' + + return (parseInt(part, 16) for part in string.split(":")) + +# Parse an IPv6 address. +ipaddr.IPv6.parser = (string) -> + if string.match(ipv6Regexes['native']) + return expandIPv6(string, 8) + + else if match = string.match(ipv6Regexes['transitional']) + parts = expandIPv6(match[1][0..-2], 6) + if parts + parts.push(parseInt(match[2]) << 8 | parseInt(match[3])) + parts.push(parseInt(match[4]) << 8 | parseInt(match[5])) + return parts + + return null + +# Checks if a given string is formatted like IPv4/IPv6 address. +ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = (string) -> + return @parser(string) != null + +# Checks if a given string is a valid IPv4/IPv6 address. +ipaddr.IPv4.isValid = (string) -> + try + new this(@parser(string)) + return true + catch e + return false + +ipaddr.IPv6.isValid = (string) -> + # Since IPv6.isValid is always called first, this shortcut + # provides a substantial performance gain. + if typeof string == "string" and string.indexOf(":") == -1 + return false + + try + new this(@parser(string)) + return true + catch e + return false + +# Tries to parse and validate a string with IPv4/IPv6 address. +# Throws an error if it fails. +ipaddr.IPv4.parse = ipaddr.IPv6.parse = (string) -> + parts = @parser(string) + if parts == null + throw new Error "ipaddr: string is not formatted like ip address" + + return new this(parts) + +ipaddr.IPv4.parseCIDR = (string) -> + if match = string.match(/^(.+)\/(\d+)$/) + maskLength = parseInt(match[2]) + if maskLength >= 0 and maskLength <= 32 + return [@parse(match[1]), maskLength] + + throw new Error "ipaddr: string is not formatted like an IPv4 CIDR range" + +ipaddr.IPv6.parseCIDR = (string) -> + if match = string.match(/^(.+)\/(\d+)$/) + maskLength = parseInt(match[2]) + if maskLength >= 0 and maskLength <= 128 + return [@parse(match[1]), maskLength] + + throw new Error "ipaddr: string is not formatted like an IPv6 CIDR range" + +# Checks if the address is valid IP address +ipaddr.isValid = (string) -> + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string) + +# Try to parse an address and throw an error if it is impossible +ipaddr.parse = (string) -> + if ipaddr.IPv6.isValid(string) + return ipaddr.IPv6.parse(string) + else if ipaddr.IPv4.isValid(string) + return ipaddr.IPv4.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) + if addr.kind() == 'ipv6' && addr.isIPv4MappedAddress() + return addr.toIPv4Address() + else + return addr diff --git a/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee new file mode 100644 index 0000000..17739e2 --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee @@ -0,0 +1,282 @@ +ipaddr = require '../lib/ipaddr' + +module.exports = + 'should define main classes': (test) -> + test.ok(ipaddr.IPv4?, 'defines IPv4 class') + test.ok(ipaddr.IPv6?, 'defines IPv6 class') + test.done() + + 'can construct IPv4 from octets': (test) -> + test.doesNotThrow -> + new ipaddr.IPv4([192, 168, 1, 2]) + test.done() + + 'refuses to construct invalid IPv4': (test) -> + test.throws -> + new ipaddr.IPv4([300, 1, 2, 3]) + test.throws -> + new ipaddr.IPv4([8, 8, 8]) + test.done() + + 'converts IPv4 to string correctly': (test) -> + addr = new ipaddr.IPv4([192, 168, 1, 1]) + test.equal(addr.toString(), '192.168.1.1') + test.done() + + 'returns correct kind for IPv4': (test) -> + addr = new ipaddr.IPv4([1, 2, 3, 4]) + test.equal(addr.kind(), 'ipv4') + test.done() + + 'allows to access IPv4 octets': (test) -> + addr = new ipaddr.IPv4([42, 0, 0, 0]) + test.equal(addr.octets[0], 42) + test.done() + + 'checks IPv4 address format': (test) -> + test.equal(ipaddr.IPv4.isIPv4('192.168.007.0xa'), true) + test.equal(ipaddr.IPv4.isIPv4('1024.0.0.1'), true) + test.equal(ipaddr.IPv4.isIPv4('8.0xa.wtf.6'), false) + test.done() + + 'validates IPv4 addresses': (test) -> + test.equal(ipaddr.IPv4.isValid('192.168.007.0xa'), true) + test.equal(ipaddr.IPv4.isValid('1024.0.0.1'), false) + test.equal(ipaddr.IPv4.isValid('8.0xa.wtf.6'), false) + test.done() + + 'parses IPv4 in several weird formats': (test) -> + test.deepEqual(ipaddr.IPv4.parse('192.168.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('0xc0.168.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('192.0250.1.1').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('0xc0a80101').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('030052000401').octets, [192, 168, 1, 1]) + test.deepEqual(ipaddr.IPv4.parse('3232235777').octets, [192, 168, 1, 1]) + test.done() + + 'barfs at invalid IPv4': (test) -> + test.throws -> + ipaddr.IPv4.parse('10.0.0.wtf') + test.done() + + 'matches IPv4 CIDR correctly': (test) -> + addr = new ipaddr.IPv4([10, 5, 0, 1]) + test.equal(addr.match(ipaddr.IPv4.parse('0.0.0.0'), 0), true) + test.equal(addr.match(ipaddr.IPv4.parse('11.0.0.0'), 8), false) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.0'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.1'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.0.0.10'), 8), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.5.5.0'), 16), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 16), false) + test.equal(addr.match(ipaddr.IPv4.parse('10.4.5.0'), 15), true) + test.equal(addr.match(ipaddr.IPv4.parse('10.5.0.2'), 32), false) + 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.throws -> + ipaddr.IPv4.parseCIDR('0.0.0.0/-1') + test.throws -> + ipaddr.IPv4.parseCIDR('0.0.0.0/33') + 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') + test.equal(ipaddr.IPv4.parse('10.1.0.1').range(), 'private') + test.equal(ipaddr.IPv4.parse('192.168.2.1').range(), 'private') + test.equal(ipaddr.IPv4.parse('224.100.0.1').range(), 'multicast') + test.equal(ipaddr.IPv4.parse('169.254.15.0').range(), 'linkLocal') + test.equal(ipaddr.IPv4.parse('127.1.1.1').range(), 'loopback') + test.equal(ipaddr.IPv4.parse('255.255.255.255').range(), 'broadcast') + test.equal(ipaddr.IPv4.parse('240.1.2.3').range(), 'reserved') + test.equal(ipaddr.IPv4.parse('8.8.8.8').range(), 'unicast') + test.done() + + 'can construct IPv6 from parts': (test) -> + test.doesNotThrow -> + new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.done() + + 'refuses to construct invalid IPv6': (test) -> + test.throws -> + new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 0, 1]) + test.throws -> + new ipaddr.IPv6([0xfffff, 0, 0, 0, 0, 0, 1]) + test.done() + + 'converts IPv6 to string correctly': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.equal(addr.toNormalizedString(), '2001:db8:f53a:0:0:0:0:1') + test.equal(addr.toString(), '2001:db8:f53a::1') + test.equal(new ipaddr.IPv6([0, 0, 0, 0, 0, 0, 0, 1]).toString(), '::1') + test.equal(new ipaddr.IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]).toString(), '2001:db8::') + test.done() + + 'returns correct kind for IPv6': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.equal(addr.kind(), 'ipv6') + test.done() + + 'allows to access IPv6 address parts': (test) -> + addr = new ipaddr.IPv6([0x2001, 0xdb8, 0xf53a, 0, 0, 42, 0, 1]) + test.equal(addr.parts[5], 42) + test.done() + + 'checks IPv6 address format': (test) -> + test.equal(ipaddr.IPv6.isIPv6('2001:db8:F53A::1'), true) + test.equal(ipaddr.IPv6.isIPv6('200001::1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:192.168.1.1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1'), true) + test.equal(ipaddr.IPv6.isIPv6('::ffff:300.168.1.1:0'), false) + test.equal(ipaddr.IPv6.isIPv6('fe80::wtf'), false) + test.done() + + 'validates IPv6 addresses': (test) -> + test.equal(ipaddr.IPv6.isValid('2001:db8:F53A::1'), true) + test.equal(ipaddr.IPv6.isValid('200001::1'), false) + test.equal(ipaddr.IPv6.isValid('::ffff:192.168.1.1'), true) + test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1'), false) + test.equal(ipaddr.IPv6.isValid('::ffff:300.168.1.1:0'), false) + test.equal(ipaddr.IPv6.isValid('2001:db8::F53A::1'), false) + test.equal(ipaddr.IPv6.isValid('fe80::wtf'), false) + test.equal(ipaddr.IPv6.isValid('2002::2:'), false) + test.equal(ipaddr.IPv6.isValid(undefined), false) + test.done() + + 'parses IPv6 in different formats': (test) -> + test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A:0:0:0:0:1').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 1]) + test.deepEqual(ipaddr.IPv6.parse('fe80::10').parts, [0xfe80, 0, 0, 0, 0, 0, 0, 0x10]) + test.deepEqual(ipaddr.IPv6.parse('2001:db8:F53A::').parts, [0x2001, 0xdb8, 0xf53a, 0, 0, 0, 0, 0]) + test.deepEqual(ipaddr.IPv6.parse('::1').parts, [0, 0, 0, 0, 0, 0, 0, 1]) + test.deepEqual(ipaddr.IPv6.parse('::').parts, [0, 0, 0, 0, 0, 0, 0, 0]) + test.done() + + 'barfs at invalid IPv6': (test) -> + test.throws -> + ipaddr.IPv6.parse('fe80::0::1') + test.done() + + 'matches IPv6 CIDR correctly': (test) -> + addr = ipaddr.IPv6.parse('2001:db8:f53a::1') + test.equal(addr.match(ipaddr.IPv6.parse('::'), 0), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53a::1:1'), 64), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f53b::1:1'), 48), false) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f531::1:1'), 44), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db8:f500::1'), 40), true) + test.equal(addr.match(ipaddr.IPv6.parse('2001:db9:f500::1'), 40), false) + 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.throws -> + ipaddr.IPv6.parseCIDR('2001:db8:f53a::1/-1') + test.throws -> + ipaddr.IPv6.parseCIDR('2001:db8:f53a::1/129') + test.done() + + 'converts between IPv4-mapped IPv6 addresses and IPv4 addresses': (test) -> + addr = ipaddr.IPv4.parse('77.88.21.11') + mapped = addr.toIPv4MappedAddress() + test.deepEqual(mapped.parts, [0, 0, 0, 0, 0, 0xffff, 0x4d58, 0x150b]) + test.deepEqual(mapped.toIPv4Address().octets, addr.octets) + test.done() + + 'refuses to convert non-IPv4-mapped IPv6 address to IPv4 address': (test) -> + test.throws -> + ipaddr.IPv6.parse('2001:db8::1').toIPv4Address() + test.done() + + 'detects reserved IPv6 networks': (test) -> + test.equal(ipaddr.IPv6.parse('::').range(), 'unspecified') + test.equal(ipaddr.IPv6.parse('fe80::1234:5678:abcd:0123').range(), 'linkLocal') + test.equal(ipaddr.IPv6.parse('ff00::1234').range(), 'multicast') + test.equal(ipaddr.IPv6.parse('::1').range(), 'loopback') + test.equal(ipaddr.IPv6.parse('fc00::').range(), 'uniqueLocal') + test.equal(ipaddr.IPv6.parse('::ffff:192.168.1.10').range(), 'ipv4Mapped') + test.equal(ipaddr.IPv6.parse('::ffff:0:192.168.1.10').range(), 'rfc6145') + test.equal(ipaddr.IPv6.parse('64:ff9b::1234').range(), 'rfc6052') + test.equal(ipaddr.IPv6.parse('2002:1f63:45e8::1').range(), '6to4') + test.equal(ipaddr.IPv6.parse('2001::4242').range(), 'teredo') + test.equal(ipaddr.IPv6.parse('2001:db8::3210').range(), 'reserved') + test.equal(ipaddr.IPv6.parse('2001:470:8:66::1').range(), 'unicast') + test.done() + + 'is able to determine IP address type': (test) -> + test.equal(ipaddr.parse('8.8.8.8').kind(), 'ipv4') + test.equal(ipaddr.parse('2001:db8:3312::1').kind(), 'ipv6') + test.done() + + 'throws an error if tried to parse an invalid address': (test) -> + test.throws -> + ipaddr.parse('::some.nonsense') + test.done() + + 'correctly processes IPv4-mapped addresses': (test) -> + test.equal(ipaddr.process('8.8.8.8').kind(), 'ipv4') + test.equal(ipaddr.process('2001:db8:3312::1').kind(), 'ipv6') + test.equal(ipaddr.process('::ffff:192.168.1.1').kind(), 'ipv4') + test.done() + + 'correctly converts IPv6 and IPv4 addresses to byte arrays': (test) -> + test.deepEqual(ipaddr.parse('1.2.3.4').toByteArray(), + [0x1, 0x2, 0x3, 0x4]); + # Fuck yeah. The first byte of Google's IPv6 address is 42. 42! + test.deepEqual(ipaddr.parse('2a00:1450:8007::68').toByteArray(), + [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68 ]) + test.done() + + 'correctly parses 1 as an IPv4 address': (test) -> + test.equal(ipaddr.IPv6.isValid('1'), false) + test.equal(ipaddr.IPv4.isValid('1'), true) + 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) + test.done() + + 'does not hang on ::8:8:8:8:8:8:8:8:8': (test) -> + test.equal(ipaddr.IPv6.isValid('::8:8:8:8:8:8:8:8:8'), false) + test.done() + + 'subnetMatch does not fail on empty range': (test) -> + ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {}, false) + ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {subnet: []}, false) + test.done() + + 'subnetMatch returns default subnet on empty range': (test) -> + test.equal(ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {}, false), false) + test.equal(ipaddr.subnetMatch(new ipaddr.IPv4([1,2,3,4]), {subnet: []}, false), false) + test.done() diff --git a/5-3/node_modules/express/node_modules/proxy-addr/package.json b/5-3/node_modules/express/node_modules/proxy-addr/package.json new file mode 100644 index 0000000..04af756 --- /dev/null +++ b/5-3/node_modules/express/node_modules/proxy-addr/package.json @@ -0,0 +1,90 @@ +{ + "name": "proxy-addr", + "description": "Determine address of proxied request", + "version": "1.0.10", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/proxy-addr.git" + }, + "dependencies": { + "forwarded": "~0.1.0", + "ipaddr.js": "1.0.5" + }, + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4", + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "0cdb6444100a7930285ed2555d0c3c687690a7a5", + "bugs": { + "url": "https://github.com/jshttp/proxy-addr/issues" + }, + "homepage": "https://github.com/jshttp/proxy-addr", + "_id": "proxy-addr@1.0.10", + "_shasum": "0d40a82f801fc355567d2ecb65efe3f077f121c5", + "_from": "proxy-addr@>=1.0.10 <1.1.0", + "_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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "0d40a82f801fc355567d2ecb65efe3f077f121c5", + "tarball": "http://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.10.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.10.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/qs/.eslintignore b/5-3/node_modules/express/node_modules/qs/.eslintignore new file mode 100644 index 0000000..1521c8b --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/.eslintignore @@ -0,0 +1 @@ +dist diff --git a/5-3/node_modules/express/node_modules/qs/.npmignore b/5-3/node_modules/express/node_modules/qs/.npmignore new file mode 100644 index 0000000..2abba8d --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/.npmignore @@ -0,0 +1,19 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov +complexity.md +dist diff --git a/5-3/node_modules/express/node_modules/qs/.travis.yml b/5-3/node_modules/express/node_modules/qs/.travis.yml new file mode 100644 index 0000000..f502178 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/.travis.yml @@ -0,0 +1,6 @@ +language: node_js + +node_js: + - 0.10 + - 0.12 + - iojs diff --git a/5-3/node_modules/express/node_modules/qs/CHANGELOG.md b/5-3/node_modules/express/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000..1fadc78 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/CHANGELOG.md @@ -0,0 +1,88 @@ + +## [**3.1.0**](https://github.com/hapijs/qs/issues?milestone=24&state=open) +- [**#89**](https://github.com/hapijs/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/hapijs/qs/issues?milestone=23&state=closed) +- [**#77**](https://github.com/hapijs/qs/issues/77) Perf boost +- [**#60**](https://github.com/hapijs/qs/issues/60) Add explicit option to disable array parsing +- [**#80**](https://github.com/hapijs/qs/issues/80) qs.parse silently drops properties +- [**#74**](https://github.com/hapijs/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/hapijs/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/hapijs/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/hapijs/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/hapijs/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/hapijs/qs/issues/85) No equal sign +- [**#84**](https://github.com/hapijs/qs/issues/84) update license attribute + +## [**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". + +## [**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 + +## [**2.2.5**](https://github.com/hapijs/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/hapijs/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/hapijs/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/hapijs/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/hapijs/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/hapijs/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/hapijs/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/hapijs/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/hapijs/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/hapijs/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/hapijs/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/hapijs/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/hapijs/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/hapijs/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/hapijs/qs/issues/32) account for circular references properly, closes #31 +- [**#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 +- [**#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 +- [**#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) +- [**#22**](https://github.com/hapijs/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/hapijs/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/hapijs/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/hapijs/qs/issues/20) Configurable parametersLimit +- [**#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 + +## [**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 +- [**#15**](https://github.com/hapijs/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/hapijs/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/hapijs/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/hapijs/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/hapijs/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/hapijs/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/hapijs/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/hapijs/qs/issues/6) Minor grammar fix in README + +## [**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/5-3/node_modules/express/node_modules/qs/CONTRIBUTING.md b/5-3/node_modules/express/node_modules/qs/CONTRIBUTING.md new file mode 100644 index 0000000..8928361 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/CONTRIBUTING.md @@ -0,0 +1 @@ +Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md). diff --git a/5-3/node_modules/express/node_modules/qs/LICENSE b/5-3/node_modules/express/node_modules/qs/LICENSE new file mode 100644 index 0000000..d456948 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/5-3/node_modules/express/node_modules/qs/README.md b/5-3/node_modules/express/node_modules/qs/README.md new file mode 100644 index 0000000..48a0de9 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/README.md @@ -0,0 +1,317 @@ +# qs + +A querystring parsing and stringifying library with some added security. + +[![Build Status](https://secure.travis-ci.org/hapijs/qs.svg)](http://travis-ci.org/hapijs/qs) + +Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var Qs = require('qs'); + +var obj = Qs.parse('a=c'); // { a: 'c' } +var str = Qs.stringify(obj); // 'a=c' +``` + +### Parsing Objects + +```javascript +Qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`, or prefixing the sub-key with a dot `.`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +{ + foo: { + bar: 'baz' + } +} +``` + +When using the `plainObjects` option the parsed value is returned as a plain object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +Qs.parse('a.hasOwnProperty=b', { plainObjects: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. + +```javascript +Qs.parse('a.hasOwnProperty=b', { allowPrototypes: true }); +// { a: { hasOwnProperty: 'b' } } +``` + +URI encoded strings work too: + +```javascript +Qs.parse('a%5Bb%5D=c'); +// { a: { b: 'c' } } +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +{ + foo: { + bar: { + baz: 'foobarbaz' + } + } +} +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +{ + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +} +``` + +This depth can be overridden by passing a `depth` option to `Qs.parse(string, [options])`: + +```javascript +Qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +// { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } } +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +Qs.parse('a=b&c=d', { parameterLimit: 1 }); +// { a: 'b' } +``` + +An optional delimiter can also be passed: + +```javascript +Qs.parse('a=b;c=d', { delimiter: ';' }); +// { a: 'b', c: 'd' } +``` + +Delimiters can be a regular expression too: + +```javascript +Qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +// { a: 'b', c: 'd', e: 'f' } +``` + +Option `allowDots` can be used to disable dot notation: + +```javascript +Qs.parse('a.b=c', { allowDots: false }); +// { 'a.b': 'c' } } +``` + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +Qs.parse('a[]=b&a[]=c'); +// { a: ['b', 'c'] } +``` + +You may specify an index as well: + +```javascript +Qs.parse('a[1]=c&a[0]=b'); +// { a: ['b', 'c'] } +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +Qs.parse('a[1]=b&a[15]=c'); +// { a: ['b', 'c'] } +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +Qs.parse('a[]=&a[]=b'); +// { a: ['', 'b'] } +Qs.parse('a[0]=b&a[1]=&a[2]=c'); +// { a: ['b', '', 'c'] } +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key: + +```javascript +Qs.parse('a[100]=b'); +// { a: { '100': 'b' } } +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +Qs.parse('a[1]=b', { arrayLimit: 0 }); +// { a: { '1': 'b' } } +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +Qs.parse('a[]=b', { parseArrays: false }); +// { a: { '0': 'b' } } +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +Qs.parse('a[0]=b&a[b]=c'); +// { a: { '0': 'b', b: 'c' } } +``` + +You can also create arrays of objects: + +```javascript +Qs.parse('a[][b]=c'); +// { a: [{ b: 'c' }] } +``` + +### Stringifying + +```javascript +Qs.stringify(object, [options]); +``` + +When stringifying, **qs** always URI encodes output. Objects are stringified as you would expect: + +```javascript +Qs.stringify({ a: 'b' }); +// 'a=b' +Qs.stringify({ a: { b: 'c' } }); +// 'a%5Bb%5D=c' +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +Qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +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 +Qs.stringify({ a: '' }); +// 'a=' +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +Qs.stringify({ a: null, b: undefined }); +// 'a=' +``` + +The delimiter may be overridden with stringify as well: + +```javascript +Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }); +// 'a=b;c=d' +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +Qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }) +// 'a=b&c=d&e[f]=123&e[g][0]=4' +Qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }) +// 'a=b&e=f' +Qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }) +// 'a[0]=b&a[2]=d' +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +Qs.stringify({ a: null, b: '' }); +// 'a=&b=' +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +Qs.parse('a&b=') +// { a: '', b: '' } +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +Qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +// 'a&b=' +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +Qs.parse('a&b=', { strictNullHandling: true }); +// { a: null, b: '' } + +``` diff --git a/5-3/node_modules/express/node_modules/qs/bower.json b/5-3/node_modules/express/node_modules/qs/bower.json new file mode 100644 index 0000000..ffd0641 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/bower.json @@ -0,0 +1,22 @@ +{ + "name": "qs", + "main": "dist/qs.js", + "version": "3.0.0", + "homepage": "https://github.com/hapijs/qs", + "authors": [ + "Nathan LaFreniere " + ], + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/5-3/node_modules/express/node_modules/qs/lib/index.js b/5-3/node_modules/express/node_modules/qs/lib/index.js new file mode 100644 index 0000000..0e09493 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/lib/index.js @@ -0,0 +1,15 @@ +// Load modules + +var Stringify = require('./stringify'); +var Parse = require('./parse'); + + +// Declare internals + +var internals = {}; + + +module.exports = { + stringify: Stringify, + parse: Parse +}; diff --git a/5-3/node_modules/express/node_modules/qs/lib/parse.js b/5-3/node_modules/express/node_modules/qs/lib/parse.js new file mode 100644 index 0000000..e7c56c5 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/lib/parse.js @@ -0,0 +1,186 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + depth: 5, + arrayLimit: 20, + parameterLimit: 1000, + strictNullHandling: false, + plainObjects: false, + allowPrototypes: false +}; + + +internals.parseValues = function (str, options) { + + var obj = {}; + var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); + + for (var i = 0, il = parts.length; i < il; ++i) { + var part = parts[i]; + var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; + + if (pos === -1) { + obj[Utils.decode(part)] = ''; + + if (options.strictNullHandling) { + obj[Utils.decode(part)] = null; + } + } + else { + var key = Utils.decode(part.slice(0, pos)); + var val = Utils.decode(part.slice(pos + 1)); + + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + obj[key] = val; + } + else { + obj[key] = [].concat(obj[key]).concat(val); + } + } + } + + return obj; +}; + + +internals.parseObject = function (chain, val, options) { + + if (!chain.length) { + return val; + } + + var root = chain.shift(); + + var obj; + if (root === '[]') { + obj = []; + obj = obj.concat(internals.parseObject(chain, val, options)); + } + else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; + var index = parseInt(cleanRoot, 10); + var indexString = '' + index; + if (!isNaN(index) && + root !== cleanRoot && + indexString === cleanRoot && + index >= 0 && + (options.parseArrays && + index <= options.arrayLimit)) { + + obj = []; + obj[index] = internals.parseObject(chain, val, options); + } + else { + obj[cleanRoot] = internals.parseObject(chain, val, options); + } + } + + return obj; +}; + + +internals.parseKeys = function (key, val, options) { + + if (!key) { + return; + } + + // Transform dot notation to bracket notation + + if (options.allowDots) { + key = key.replace(/\.([^\.\[]+)/g, '[$1]'); + } + + // The regex chunks + + var parent = /^([^\[\]]*)/; + var child = /(\[[^\[\]]*\])/g; + + // Get the parent + + var segment = parent.exec(key); + + // Stash the parent if it exists + + var keys = []; + if (segment[1]) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1])) { + + if (!options.allowPrototypes) { + return; + } + } + + keys.push(segment[1]); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + + ++i; + if (!options.plainObjects && + Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { + + if (!options.allowPrototypes) { + continue; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return internals.parseObject(keys, val, options); +}; + + +module.exports = function (str, options) { + + options = options || {}; + options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.allowDots = options.allowDots !== false; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : internals.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : internals.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + + if (str === '' || + str === null || + typeof str === 'undefined') { + + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var newObj = internals.parseKeys(key, tempObj[key], options); + obj = Utils.merge(obj, newObj, options); + } + + return Utils.compact(obj); +}; diff --git a/5-3/node_modules/express/node_modules/qs/lib/stringify.js b/5-3/node_modules/express/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000..7414284 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/lib/stringify.js @@ -0,0 +1,121 @@ +// Load modules + +var Utils = require('./utils'); + + +// Declare internals + +var internals = { + delimiter: '&', + arrayPrefixGenerators: { + brackets: function (prefix, key) { + + return prefix + '[]'; + }, + indices: function (prefix, key) { + + return prefix + '[' + key + ']'; + }, + repeat: function (prefix, key) { + + return prefix; + } + }, + strictNullHandling: false +}; + + +internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, filter) { + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } + else if (Utils.isBuffer(obj)) { + obj = obj.toString(); + } + else if (obj instanceof Date) { + obj = obj.toISOString(); + } + else if (obj === null) { + if (strictNullHandling) { + return Utils.encode(prefix); + } + + obj = ''; + } + + if (typeof obj === 'string' || + typeof obj === 'number' || + typeof obj === 'boolean') { + + return [Utils.encode(prefix) + '=' + Utils.encode(obj)]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys = Array.isArray(filter) ? filter : Object.keys(obj); + for (var i = 0, il = objKeys.length; i < il; ++i) { + var key = objKeys[i]; + + if (Array.isArray(obj)) { + values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, filter)); + } + else { + values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, filter)); + } + } + + return values; +}; + + +module.exports = function (obj, options) { + + options = options || {}; + var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; + var objKeys; + var filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } + else if (Array.isArray(options.filter)) { + objKeys = filter = options.filter; + } + + var keys = []; + + if (typeof obj !== 'object' || + obj === null) { + + 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]; + + if (!objKeys) { + 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, generateArrayPrefix, strictNullHandling, filter)); + } + + return keys.join(delimiter); +}; diff --git a/5-3/node_modules/express/node_modules/qs/lib/utils.js b/5-3/node_modules/express/node_modules/qs/lib/utils.js new file mode 100644 index 0000000..88f3147 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/lib/utils.js @@ -0,0 +1,190 @@ +// Load modules + + +// Declare internals + +var internals = {}; +internals.hexTable = new Array(256); +for (var h = 0; h < 256; ++h) { + internals.hexTable[h] = '%' + ((h < 16 ? '0' : '') + h.toString(16)).toUpperCase(); +} + + +exports.arrayToObject = function (source, options) { + + var obj = options.plainObjects ? Object.create(null) : {}; + for (var i = 0, il = source.length; i < il; ++i) { + if (typeof source[i] !== 'undefined') { + + obj[i] = source[i]; + } + } + + return obj; +}; + + +exports.merge = function (target, source, options) { + + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } + else if (typeof target === 'object') { + target[source] = true; + } + else { + target = [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + target = [target].concat(source); + return target; + } + + if (Array.isArray(target) && + !Array.isArray(source)) { + + target = exports.arrayToObject(target, options); + } + + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + + if (!Object.prototype.hasOwnProperty.call(target, key)) { + target[key] = value; + } + else { + target[key] = exports.merge(target[key], value, options); + } + } + + return target; +}; + + +exports.decode = function (str) { + + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function (str) { + + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + if (typeof str !== 'string') { + str = '' + str; + } + + var out = ''; + for (var i = 0, il = str.length; i < il; ++i) { + var c = str.charCodeAt(i); + + if (c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A)) { // A-Z + + out += str[i]; + continue; + } + + if (c < 0x80) { + out += internals.hexTable[c]; + continue; + } + + if (c < 0x800) { + out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + continue; + } + + ++i; + c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF)); + out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function (obj, refs) { + + if (typeof obj !== 'object' || + obj === null) { + + return obj; + } + + refs = refs || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } + + refs.push(obj); + + if (Array.isArray(obj)) { + var compacted = []; + + for (var i = 0, il = obj.length; i < il; ++i) { + if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } + + return compacted; + } + + var keys = Object.keys(obj); + for (i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + obj[key] = exports.compact(obj[key], refs); + } + + return obj; +}; + + +exports.isRegExp = function (obj) { + + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + + +exports.isBuffer = function (obj) { + + if (obj === null || + typeof obj === 'undefined') { + + return false; + } + + return !!(obj.constructor && + obj.constructor.isBuffer && + obj.constructor.isBuffer(obj)); +}; diff --git a/5-3/node_modules/express/node_modules/qs/package.json b/5-3/node_modules/express/node_modules/qs/package.json new file mode 100644 index 0000000..1bae0ed --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/package.json @@ -0,0 +1,57 @@ +{ + "name": "qs", + "version": "4.0.0", + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/hapijs/qs", + "main": "lib/index.js", + "dependencies": {}, + "devDependencies": { + "browserify": "^10.2.1", + "code": "1.x.x", + "lab": "5.x.x" + }, + "scripts": { + "test": "lab -a code -t 100 -L", + "test-cov-html": "lab -a code -r html -o coverage.html", + "dist": "browserify --standalone Qs lib/index.js > dist/qs.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/hapijs/qs.git" + }, + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "gitHead": "e573dd08eae6cce30d2202704691a102dfa3782a", + "bugs": { + "url": "https://github.com/hapijs/qs/issues" + }, + "_id": "qs@4.0.0", + "_shasum": "c31d9b74ec27df75e543a86c78728ed8d4623607", + "_from": "qs@4.0.0", + "_npmVersion": "2.12.0", + "_nodeVersion": "0.12.4", + "_npmUser": { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + "dist": { + "shasum": "c31d9b74ec27df75e543a86c78728ed8d4623607", + "tarball": "http://registry.npmjs.org/qs/-/qs-4.0.0.tgz" + }, + "maintainers": [ + { + "name": "nlf", + "email": "quitlahok@gmail.com" + }, + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/qs/-/qs-4.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/qs/test/parse.js b/5-3/node_modules/express/node_modules/qs/test/parse.js new file mode 100644 index 0000000..a19d764 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/test/parse.js @@ -0,0 +1,478 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('parse()', function () { + + it('parses a simple string', function (done) { + + expect(Qs.parse('0=foo')).to.deep.equal({ '0': 'foo' }); + expect(Qs.parse('foo=c++')).to.deep.equal({ foo: 'c ' }); + expect(Qs.parse('a[>=]=23')).to.deep.equal({ a: { '>=': '23' } }); + expect(Qs.parse('a[<=>]==23')).to.deep.equal({ a: { '<=>': '=23' } }); + expect(Qs.parse('a[==]=23')).to.deep.equal({ a: { '==': '23' } }); + expect(Qs.parse('foo', { strictNullHandling: true })).to.deep.equal({ foo: null }); + expect(Qs.parse('foo' )).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=')).to.deep.equal({ foo: '' }); + expect(Qs.parse('foo=bar')).to.deep.equal({ foo: 'bar' }); + expect(Qs.parse(' foo = bar = baz ')).to.deep.equal({ ' foo ': ' bar = baz ' }); + expect(Qs.parse('foo=bar=baz')).to.deep.equal({ foo: 'bar=baz' }); + expect(Qs.parse('foo=bar&bar=baz')).to.deep.equal({ foo: 'bar', bar: 'baz' }); + expect(Qs.parse('foo2=bar2&baz2=')).to.deep.equal({ foo2: 'bar2', baz2: '' }); + expect(Qs.parse('foo=bar&baz', { strictNullHandling: true })).to.deep.equal({ foo: 'bar', baz: null }); + expect(Qs.parse('foo=bar&baz')).to.deep.equal({ foo: 'bar', baz: '' }); + expect(Qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World')).to.deep.equal({ + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + done(); + }); + + it('allows disabling dot notation', function (done) { + + expect(Qs.parse('a.b=c')).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse('a.b=c', { allowDots: false })).to.deep.equal({ 'a.b': 'c' }); + done(); + }); + + it('parses a single nested string', function (done) { + + expect(Qs.parse('a[b]=c')).to.deep.equal({ a: { b: 'c' } }); + done(); + }); + + it('parses a double nested string', function (done) { + + expect(Qs.parse('a[b][c]=d')).to.deep.equal({ a: { b: { c: 'd' } } }); + done(); + }); + + it('defaults to a depth of 5', function (done) { + + expect(Qs.parse('a[b][c][d][e][f][g][h]=i')).to.deep.equal({ a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }); + done(); + }); + + it('only parses one level when depth = 1', function (done) { + + expect(Qs.parse('a[b][c]=d', { depth: 1 })).to.deep.equal({ a: { b: { '[c]': 'd' } } }); + expect(Qs.parse('a[b][c][d]=e', { depth: 1 })).to.deep.equal({ a: { b: { '[c][d]': 'e' } } }); + done(); + }); + + it('parses a simple array', function (done) { + + expect(Qs.parse('a=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses an explicit array', function (done) { + + expect(Qs.parse('a[]=b')).to.deep.equal({ a: ['b'] }); + expect(Qs.parse('a[]=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a[]=c&a[]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + done(); + }); + + it('parses a mix of simple and explicit arrays', function (done) { + + expect(Qs.parse('a=b&a[]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[0]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[0]=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=b&a=c')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a=b&a[1]=c')).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); + + it('parses a nested array', function (done) { + + expect(Qs.parse('a[b][]=c&a[b][]=d')).to.deep.equal({ a: { b: ['c', 'd'] } }); + expect(Qs.parse('a[>=]=25')).to.deep.equal({ a: { '>=': '25' } }); + done(); + }); + + it('allows to specify array indices', function (done) { + + expect(Qs.parse('a[1]=c&a[0]=b&a[2]=d')).to.deep.equal({ a: ['b', 'c', 'd'] }); + expect(Qs.parse('a[1]=c&a[0]=b')).to.deep.equal({ a: ['b', 'c'] }); + expect(Qs.parse('a[1]=c')).to.deep.equal({ a: ['c'] }); + done(); + }); + + it('limits specific array indices to 20', function (done) { + + expect(Qs.parse('a[20]=a')).to.deep.equal({ a: ['a'] }); + expect(Qs.parse('a[21]=a')).to.deep.equal({ a: { '21': 'a' } }); + done(); + }); + + it('supports keys that begin with a number', function (done) { + + expect(Qs.parse('a[12b]=c')).to.deep.equal({ a: { '12b': 'c' } }); + done(); + }); + + it('supports encoded = signs', function (done) { + + expect(Qs.parse('he%3Dllo=th%3Dere')).to.deep.equal({ 'he=llo': 'th=ere' }); + done(); + }); + + it('is ok with url encoded strings', function (done) { + + expect(Qs.parse('a[b%20c]=d')).to.deep.equal({ a: { 'b c': 'd' } }); + expect(Qs.parse('a[b]=c%20d')).to.deep.equal({ a: { b: 'c d' } }); + done(); + }); + + it('allows brackets in the value', function (done) { + + expect(Qs.parse('pets=["tobi"]')).to.deep.equal({ pets: '["tobi"]' }); + expect(Qs.parse('operators=[">=", "<="]')).to.deep.equal({ operators: '[">=", "<="]' }); + done(); + }); + + it('allows empty values', function (done) { + + expect(Qs.parse('')).to.deep.equal({}); + expect(Qs.parse(null)).to.deep.equal({}); + expect(Qs.parse(undefined)).to.deep.equal({}); + done(); + }); + + it('transforms arrays to objects', function (done) { + + expect(Qs.parse('foo[0]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo[bad]=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + expect(Qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c')).to.deep.equal({ a: { '0': 'b', t: 'u', c: true } }); + expect(Qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y')).to.deep.equal({ a: { '0': 'b', '1': 'c', x: 'y' } }); + done(); + }); + + it('transforms arrays to objects (dot notation)', function (done) { + + expect(Qs.parse('foo[0].baz=bar&fool.bad=baz')).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz=bar&fool.bad.boo=baz')).to.deep.equal({ foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + expect(Qs.parse('foo[0][0].baz=bar&fool.bad=baz')).to.deep.equal({ foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].bar=2')).to.deep.equal({ foo: [{ baz: ['15'], bar: '2' }] }); + expect(Qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2')).to.deep.equal({ foo: [{ baz: ['15', '16'], bar: '2' }] }); + expect(Qs.parse('foo.bad=baz&foo[0]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar' } }); + expect(Qs.parse('foo[]=bar&foo.bad=baz')).to.deep.equal({ foo: { '0': 'bar', bad: 'baz' } }); + expect(Qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo')).to.deep.equal({ foo: { bad: 'baz', '0': 'bar', '1': 'foo' } }); + expect(Qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb')).to.deep.equal({ foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + done(); + }); + + it('can add keys to objects', function (done) { + + expect(Qs.parse('a[b]=c&a=d')).to.deep.equal({ a: { b: 'c', d: true } }); + done(); + }); + + it('correctly prunes undefined values when converting an array to an object', function (done) { + + expect(Qs.parse('a[2]=b&a[99999999]=c')).to.deep.equal({ a: { '2': 'b', '99999999': 'c' } }); + done(); + }); + + it('supports malformed uri characters', function (done) { + + expect(Qs.parse('{%:%}', { strictNullHandling: true })).to.deep.equal({ '{%:%}': null }); + expect(Qs.parse('{%:%}=')).to.deep.equal({ '{%:%}': '' }); + expect(Qs.parse('foo=%:%}')).to.deep.equal({ foo: '%:%}' }); + done(); + }); + + it('doesn\'t produce empty keys', function (done) { + + expect(Qs.parse('_r=1&')).to.deep.equal({ '_r': '1' }); + done(); + }); + + it('cannot access Object prototype', function (done) { + + Qs.parse('constructor[prototype][bad]=bad'); + Qs.parse('bad[constructor][prototype][bad]=bad'); + expect(typeof Object.prototype.bad).to.equal('undefined'); + done(); + }); + + it('parses arrays of objects', function (done) { + + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + expect(Qs.parse('a[0][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + done(); + }); + + it('allows for empty strings in arrays', function (done) { + + expect(Qs.parse('a[]=b&a[]=&a[]=c')).to.deep.equal({ a: ['b', '', 'c'] }); + expect(Qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true })).to.deep.equal({ a: ['b', null, 'c', ''] }); + expect(Qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true })).to.deep.equal({ a: ['b', '', 'c', null] }); + expect(Qs.parse('a[]=&a[]=b&a[]=c')).to.deep.equal({ a: ['', 'b', 'c'] }); + done(); + }); + + it('compacts sparse arrays', function (done) { + + expect(Qs.parse('a[10]=1&a[2]=2')).to.deep.equal({ a: ['2', '1'] }); + done(); + }); + + it('parses semi-parsed strings', function (done) { + + expect(Qs.parse({ 'a[b]': 'c' })).to.deep.equal({ a: { b: 'c' } }); + expect(Qs.parse({ 'a[b]': 'c', 'a[d]': 'e' })).to.deep.equal({ a: { b: 'c', d: 'e' } }); + done(); + }); + + it('parses buffers correctly', function (done) { + + var b = new Buffer('test'); + expect(Qs.parse({ a: b })).to.deep.equal({ a: b }); + done(); + }); + + it('continues parsing when no parent is found', function (done) { + + expect(Qs.parse('[]=&a=b')).to.deep.equal({ '0': '', a: 'b' }); + expect(Qs.parse('[]&a=b', { strictNullHandling: true })).to.deep.equal({ '0': null, a: 'b' }); + expect(Qs.parse('[foo]=bar')).to.deep.equal({ foo: 'bar' }); + done(); + }); + + it('does not error when parsing a very long array', function (done) { + + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str += '&' + str; + } + + expect(function () { + + Qs.parse(str); + }).to.not.throw(); + + done(); + }); + + it('should not throw when a native prototype has an enumerable property', { parallel: false }, function (done) { + + Object.prototype.crash = ''; + Array.prototype.crash = ''; + expect(Qs.parse.bind(null, 'a=b')).to.not.throw(); + expect(Qs.parse('a=b')).to.deep.equal({ a: 'b' }); + expect(Qs.parse.bind(null, 'a[][b]=c')).to.not.throw(); + expect(Qs.parse('a[][b]=c')).to.deep.equal({ a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + done(); + }); + + it('parses a string with an alternative string delimiter', function (done) { + + expect(Qs.parse('a=b;c=d', { delimiter: ';' })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('parses a string with an alternative RegExp delimiter', function (done) { + + expect(Qs.parse('a=b; c=d', { delimiter: /[;,] */ })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not use non-splittable objects as delimiters', function (done) { + + expect(Qs.parse('a=b&c=d', { delimiter: true })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('allows overriding parameter limit', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: 1 })).to.deep.equal({ a: 'b' }); + done(); + }); + + it('allows setting the parameter limit to Infinity', function (done) { + + expect(Qs.parse('a=b&c=d', { parameterLimit: Infinity })).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + 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(); + }); + + it('allows disabling array parsing', function (done) { + + expect(Qs.parse('a[0]=b&a[1]=c', { parseArrays: false })).to.deep.equal({ a: { '0': 'b', '1': 'c' } }); + done(); + }); + + it('parses an object', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object in dot notation', function (done) { + + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': 3 }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('parses an object and not child values', function (done) { + + var input = { + 'user[name]': { 'pop[bob]': { 'test': 3 } }, + 'user[email]': null + }; + + var expected = { + 'user': { + 'name': { 'pop[bob]': { 'test': 3 } }, + 'email': null + } + }; + + var result = Qs.parse(input); + + expect(result).to.deep.equal(expected); + done(); + }); + + it('does not blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = Qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + expect(result).to.deep.equal({ a: 'b', c: 'd' }); + done(); + }); + + it('does not crash when parsing circular references', function (done) { + + var a = {}; + a.b = a; + + var parsed; + + expect(function () { + + parsed = Qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }).to.not.throw(); + + 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(); + }); + + it('parses plain objects correctly', function (done) { + + var a = Object.create(null); + a.b = 'c'; + + expect(Qs.parse(a)).to.deep.equal({ b: 'c' }); + var result = Qs.parse({ a: a }); + expect(result).to.contain('a'); + expect(result.a).to.deep.equal(a); + done(); + }); + + it('parses dates correctly', function (done) { + + var now = new Date(); + expect(Qs.parse({ a: now })).to.deep.equal({ a: now }); + done(); + }); + + it('parses regular expressions correctly', function (done) { + + var re = /^test$/; + expect(Qs.parse({ a: re })).to.deep.equal({ a: re }); + done(); + }); + + it('can allow overwriting prototype properties', function (done) { + + expect(Qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true })).to.deep.equal({ a: { hasOwnProperty: 'b' } }, { prototype: false }); + expect(Qs.parse('hasOwnProperty=b', { allowPrototypes: true })).to.deep.equal({ hasOwnProperty: 'b' }, { prototype: false }); + done(); + }); + + it('can return plain objects', function (done) { + + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + expect(Qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true })).to.deep.equal(expected); + expect(Qs.parse(null, { plainObjects: true })).to.deep.equal(Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a['0'] = 'b'; + expectedArray.a.c = 'd'; + expect(Qs.parse('a[]=b&a[c]=d', { plainObjects: true })).to.deep.equal(expectedArray); + done(); + }); +}); diff --git a/5-3/node_modules/express/node_modules/qs/test/stringify.js b/5-3/node_modules/express/node_modules/qs/test/stringify.js new file mode 100644 index 0000000..48b7803 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/test/stringify.js @@ -0,0 +1,259 @@ +/* eslint no-extend-native:0 */ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Qs = require('../'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('stringify()', function () { + + it('stringifies a querystring object', function (done) { + + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 })).to.equal('a=1'); + expect(Qs.stringify({ a: 1, b: 2 })).to.equal('a=1&b=2'); + expect(Qs.stringify({ a: 'A_Z' })).to.equal('a=A_Z'); + expect(Qs.stringify({ a: '€' })).to.equal('a=%E2%82%AC'); + expect(Qs.stringify({ a: '' })).to.equal('a=%EE%80%80'); + expect(Qs.stringify({ a: 'א' })).to.equal('a=%D7%90'); + expect(Qs.stringify({ a: '𐐷' })).to.equal('a=%F0%90%90%B7'); + done(); + }); + + it('stringifies a nested object', function (done) { + + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + expect(Qs.stringify({ a: { b: { c: { d: 'e' } } } })).to.equal('a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + done(); + }); + + it('stringifies an array value', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] })).to.equal('a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d'); + done(); + }); + + it('omits array indices when asked', function (done) { + + expect(Qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false })).to.equal('a=b&a=c&a=d'); + done(); + }); + + it('stringifies a nested array value', function (done) { + + expect(Qs.stringify({ a: { b: ['c', 'd'] } })).to.equal('a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + done(); + }); + + it('stringifies an object inside an array', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] })).to.equal('a%5B0%5D%5Bb%5D=c'); + expect(Qs.stringify({ a: [{ b: { c: [1] } }] })).to.equal('a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1'); + done(); + }); + + it('does not omit object keys when indices = false', function (done) { + + expect(Qs.stringify({ a: [{ b: 'c' }] }, { indices: false })).to.equal('a%5Bb%5D=c'); + 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'); + done(); + }); + + it('stringifies an empty value', function (done) { + + expect(Qs.stringify({ a: '' })).to.equal('a='); + expect(Qs.stringify({ a: null }, { strictNullHandling: true })).to.equal('a'); + + expect(Qs.stringify({ a: '', b: '' })).to.equal('a=&b='); + expect(Qs.stringify({ a: null, b: '' }, { strictNullHandling: true })).to.equal('a&b='); + + expect(Qs.stringify({ a: { b: '' } })).to.equal('a%5Bb%5D='); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: true })).to.equal('a%5Bb%5D'); + expect(Qs.stringify({ a: { b: null } }, { strictNullHandling: false })).to.equal('a%5Bb%5D='); + + done(); + }); + + it('stringifies an empty object', function (done) { + + var obj = Object.create(null); + obj.a = 'b'; + expect(Qs.stringify(obj)).to.equal('a=b'); + done(); + }); + + it('returns an empty string for invalid input', function (done) { + + expect(Qs.stringify(undefined)).to.equal(''); + expect(Qs.stringify(false)).to.equal(''); + expect(Qs.stringify(null)).to.equal(''); + expect(Qs.stringify('')).to.equal(''); + done(); + }); + + it('stringifies an object with an empty object as a child', function (done) { + + var obj = { + a: Object.create(null) + }; + + obj.a.b = 'c'; + expect(Qs.stringify(obj)).to.equal('a%5Bb%5D=c'); + done(); + }); + + it('drops keys with a value of undefined', function (done) { + + expect(Qs.stringify({ a: undefined })).to.equal(''); + + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true })).to.equal('a%5Bc%5D'); + expect(Qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false })).to.equal('a%5Bc%5D='); + expect(Qs.stringify({ a: { b: undefined, c: '' } })).to.equal('a%5Bc%5D='); + done(); + }); + + it('url encodes values', function (done) { + + expect(Qs.stringify({ a: 'b c' })).to.equal('a=b%20c'); + done(); + }); + + it('stringifies a date', function (done) { + + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + expect(Qs.stringify({ a: now })).to.equal(str); + done(); + }); + + it('stringifies the weird object from qs', function (done) { + + expect(Qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' })).to.equal('my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + done(); + }); + + it('skips properties that are part of the object prototype', function (done) { + + Object.prototype.crash = 'test'; + expect(Qs.stringify({ a: 'b' })).to.equal('a=b'); + expect(Qs.stringify({ a: { b: 'c' } })).to.equal('a%5Bb%5D=c'); + delete Object.prototype.crash; + done(); + }); + + it('stringifies boolean values', function (done) { + + expect(Qs.stringify({ a: true })).to.equal('a=true'); + expect(Qs.stringify({ a: { b: true } })).to.equal('a%5Bb%5D=true'); + expect(Qs.stringify({ b: false })).to.equal('b=false'); + expect(Qs.stringify({ b: { c: false } })).to.equal('b%5Bc%5D=false'); + done(); + }); + + it('stringifies buffer values', function (done) { + + expect(Qs.stringify({ a: new Buffer('test') })).to.equal('a=test'); + expect(Qs.stringify({ a: { b: new Buffer('test') } })).to.equal('a%5Bb%5D=test'); + done(); + }); + + it('stringifies an object using an alternative delimiter', function (done) { + + expect(Qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' })).to.equal('a=b;c=d'); + done(); + }); + + it('doesn\'t blow up when Buffer global is missing', function (done) { + + var tempBuffer = global.Buffer; + delete global.Buffer; + expect(Qs.stringify({ a: 'b', c: 'd' })).to.equal('a=b&c=d'); + global.Buffer = tempBuffer; + done(); + }); + + it('selects properties when filter=array', function (done) { + + expect(Qs.stringify({ a: 'b' }, { filter: ['a'] })).to.equal('a=b'); + expect(Qs.stringify({ a: 1 }, { filter: [] })).to.equal(''); + expect(Qs.stringify({ a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] })).to.equal('a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3'); + done(); + + }); + + it('supports custom representations when filter=function', function (done) { + + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + + calls++; + if (calls === 1) { + expect(prefix).to.be.empty(); + expect(value).to.equal(obj); + } + else if (prefix === 'c') { + return; + } + else if (value instanceof Date) { + expect(prefix).to.equal('e[f]'); + return value.getTime(); + } + return value; + }; + + expect(Qs.stringify(obj, { filter: filterFunc })).to.equal('a=b&e%5Bf%5D=1257894000000'); + expect(calls).to.equal(5); + done(); + + }); +}); diff --git a/5-3/node_modules/express/node_modules/qs/test/utils.js b/5-3/node_modules/express/node_modules/qs/test/utils.js new file mode 100644 index 0000000..a9a6b52 --- /dev/null +++ b/5-3/node_modules/express/node_modules/qs/test/utils.js @@ -0,0 +1,28 @@ +// Load modules + +var Code = require('code'); +var Lab = require('lab'); +var Utils = require('../lib/utils'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var expect = Code.expect; +var describe = lab.experiment; +var it = lab.test; + + +describe('merge()', function () { + + it('can merge two objects with the same key', function (done) { + + expect(Utils.merge({ a: 'b' }, { a: 'c' })).to.deep.equal({ a: ['b', 'c'] }); + done(); + }); +}); diff --git a/5-3/node_modules/express/node_modules/range-parser/HISTORY.md b/5-3/node_modules/express/node_modules/range-parser/HISTORY.md new file mode 100644 index 0000000..f640bea --- /dev/null +++ b/5-3/node_modules/express/node_modules/range-parser/HISTORY.md @@ -0,0 +1,40 @@ +unreleased +========== + + * perf: enable strict mode + +1.0.2 / 2014-09-08 +================== + + * Support Node.js 0.6 + +1.0.1 / 2014-09-07 +================== + + * Move repository to jshttp + +1.0.0 / 2013-12-11 +================== + + * Add repository to package.json + * Add MIT license + +0.0.4 / 2012-06-17 +================== + + * Change ret -1 for unsatisfiable and -2 when invalid + +0.0.3 / 2012-06-17 +================== + + * Fix last-byte-pos default to len - 1 + +0.0.2 / 2012-06-14 +================== + + * Add `.type` + +0.0.1 / 2012-06-11 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/range-parser/LICENSE b/5-3/node_modules/express/node_modules/range-parser/LICENSE new file mode 100644 index 0000000..a491841 --- /dev/null +++ b/5-3/node_modules/express/node_modules/range-parser/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/range-parser/README.md b/5-3/node_modules/express/node_modules/range-parser/README.md new file mode 100644 index 0000000..32f58f6 --- /dev/null +++ b/5-3/node_modules/express/node_modules/range-parser/README.md @@ -0,0 +1,57 @@ +# range-parser + +[![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] + +Range header field parser. + +## Installation + +``` +$ npm install range-parser +``` + +## API + +```js +var parseRange = require('range-parser') +``` + +### parseRange(size, header) + +Parse the given `header` string where `size` is the maximum size of the resource. +An array of ranges will be returned or negative numbers indicating an error parsing. + + * `-2` signals a malformed header string + * `-1` signals an invalid range + +```js +// parse header from request +var range = parseRange(req.headers.range) + +// the type of the range +if (range.type === 'bytes') { + // the ranges + range.forEach(function (r) { + // do something with r.start and r.end + }) +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/range-parser.svg +[npm-url]: https://npmjs.org/package/range-parser +[node-version-image]: https://img.shields.io/node/v/range-parser.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/range-parser.svg +[travis-url]: https://travis-ci.org/jshttp/range-parser +[coveralls-image]: https://img.shields.io/coveralls/jshttp/range-parser.svg +[coveralls-url]: https://coveralls.io/r/jshttp/range-parser +[downloads-image]: https://img.shields.io/npm/dm/range-parser.svg +[downloads-url]: https://npmjs.org/package/range-parser diff --git a/5-3/node_modules/express/node_modules/range-parser/index.js b/5-3/node_modules/express/node_modules/range-parser/index.js new file mode 100644 index 0000000..814e533 --- /dev/null +++ b/5-3/node_modules/express/node_modules/range-parser/index.js @@ -0,0 +1,63 @@ +/*! + * range-parser + * Copyright(c) 2012-2014 TJ Holowaychuk + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = rangeParser; + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @return {Array} + * @public + */ + +function rangeParser(size, str) { + var valid = true; + var i = str.indexOf('='); + + if (-1 == i) return -2; + + var arr = str.slice(i + 1).split(',').map(function(range){ + var range = range.split('-') + , start = parseInt(range[0], 10) + , end = parseInt(range[1], 10); + + // -nnn + if (isNaN(start)) { + start = size - end; + end = size - 1; + // nnn- + } else if (isNaN(end)) { + end = size - 1; + } + + // limit last-byte-pos to current length + if (end > size - 1) end = size - 1; + + // invalid + if (isNaN(start) + || isNaN(end) + || start > end + || start < 0) valid = false; + + return { + start: start, + end: end + }; + }); + + arr.type = str.slice(0, i); + + return valid ? arr : -1; +} diff --git a/5-3/node_modules/express/node_modules/range-parser/package.json b/5-3/node_modules/express/node_modules/range-parser/package.json new file mode 100644 index 0000000..5d4411b --- /dev/null +++ b/5-3/node_modules/express/node_modules/range-parser/package.json @@ -0,0 +1,75 @@ +{ + "name": "range-parser", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "description": "Range header field string parser", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "range", + "parser", + "http" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/range-parser.git" + }, + "devDependencies": { + "istanbul": "0.4.0", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "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" + }, + "gitHead": "18e46a3de74afff9f4e22717f11ddd6e9aa6d845", + "bugs": { + "url": "https://github.com/jshttp/range-parser/issues" + }, + "homepage": "https://github.com/jshttp/range-parser", + "_id": "range-parser@1.0.3", + "_shasum": "6872823535c692e2c2a0103826afd82c2e0ff175", + "_from": "range-parser@>=1.0.3 <1.1.0", + "_npmVersion": "1.4.28", + "_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": "6872823535c692e2c2a0103826afd82c2e0ff175", + "tarball": "http://registry.npmjs.org/range-parser/-/range-parser-1.0.3.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/send/HISTORY.md b/5-3/node_modules/express/node_modules/send/HISTORY.md new file mode 100644 index 0000000..d3dca9c --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/HISTORY.md @@ -0,0 +1,310 @@ +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * 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: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.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/5-3/node_modules/express/node_modules/send/LICENSE b/5-3/node_modules/express/node_modules/send/LICENSE new file mode 100644 index 0000000..e4d595b --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +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: + +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/5-3/node_modules/express/node_modules/send/README.md b/5-3/node_modules/express/node_modules/send/README.md new file mode 100644 index 0000000..3586060 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/README.md @@ -0,0 +1,195 @@ +# send + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Send is a library for streaming files from the file system as a http response +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. + +Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). + +## 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"). + + - `'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. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### 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 example + +```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 +[npm-url]: https://npmjs.org/package/send +[travis-image]: https://img.shields.io/travis/pillarjs/send/master.svg?label=linux +[travis-url]: https://travis-ci.org/pillarjs/send +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/send/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/send +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/send/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master +[downloads-image]: https://img.shields.io/npm/dm/send.svg +[downloads-url]: https://npmjs.org/package/send +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/5-3/node_modules/express/node_modules/send/index.js b/5-3/node_modules/express/node_modules/send/index.js new file mode 100644 index 0000000..3510989 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/index.js @@ -0,0 +1,820 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('send') +var deprecate = require('depd')('send') +var destroy = require('destroy') +var escapeHtml = require('escape-html') + , parseRange = require('range-parser') + , Stream = require('stream') + , mime = require('mime') + , fresh = require('fresh') + , path = require('path') + , fs = require('fs') + , normalize = path.normalize + , join = path.join +var etag = require('etag') +var EventEmitter = require('events').EventEmitter; +var ms = require('ms'); +var onFinished = require('on-finished') +var statuses = require('statuses') + +/** + * Variables. + */ +var extname = path.extname +var maxMaxAge = 60 * 60 * 24 * 365 * 1000; // 1 year +var resolve = path.resolve +var sep = path.sep +var toString = Object.prototype.toString +var upPathRegexp = /(?:^|[\\\/])\.\.(?:[\\\/]|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = send +module.exports.mime = mime + +/** + * Shim EventEmitter.listenerCount for node.js < 0.10 + */ + +/* istanbul ignore next */ +var listenerCount = EventEmitter.listenerCount + || function(emitter, type){ return emitter.listeners(type).length; }; + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ + +function send(req, path, options) { + return new SendStream(req, path, options); +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ + +function SendStream(req, path, options) { + var opts = options || {} + + this.options = opts + this.path = path + this.req = req + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true + + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' + + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + this._hidden = Boolean(opts.hidden) + + if (opts.hidden !== undefined) { + deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') + } + + // legacy support + if (opts.dotfiles === undefined) { + this._dotfiles = undefined + } + + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] + + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] + + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true + + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), maxMaxAge) + : 0 + + this._root = opts.root + ? resolve(opts.root) + : null + + if (!this._root && opts.from) { + this.from(opts.from) + } +} + +/** + * Inherits from `Stream.prototype`. + */ + +SendStream.prototype.__proto__ = Stream.prototype; + +/** + * Enable or disable etag generation. + * + * @param {Boolean} val + * @return {SendStream} + * @api public + */ + +SendStream.prototype.etag = deprecate.function(function etag(val) { + val = Boolean(val); + debug('etag %s', val); + this._etag = val; + return this; +}, 'send.etag: pass etag as option'); + +/** + * Enable or disable "hidden" (dot) files. + * + * @param {Boolean} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.hidden = deprecate.function(function hidden(val) { + val = Boolean(val); + debug('hidden %s', val); + this._hidden = val; + this._dotfiles = undefined + return this; +}, 'send.hidden: use dotfiles option'); + +/** + * Set index `paths`, set to a falsy + * value to disable index support. + * + * @param {String|Boolean|Array} paths + * @return {SendStream} + * @api public + */ + +SendStream.prototype.index = deprecate.function(function index(paths) { + var index = !paths ? [] : normalizeList(paths, 'paths argument'); + debug('index %o', paths); + this._index = index; + return this; +}, 'send.index: pass index as option'); + +/** + * Set root `path`. + * + * @param {String} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.root = function(path){ + path = String(path); + this._root = resolve(path) + return this; +}; + +SendStream.prototype.from = deprecate.function(SendStream.prototype.root, + 'send.from: pass root as option'); + +SendStream.prototype.root = deprecate.function(SendStream.prototype.root, + 'send.root: pass root as option'); + +/** + * Set max-age to `maxAge`. + * + * @param {Number} maxAge + * @return {SendStream} + * @api public + */ + +SendStream.prototype.maxage = deprecate.function(function maxage(maxAge) { + maxAge = typeof maxAge === 'string' + ? ms(maxAge) + : Number(maxAge); + if (isNaN(maxAge)) maxAge = 0; + if (Infinity == maxAge) maxAge = 60 * 60 * 24 * 365 * 1000; + debug('max-age %d', maxAge); + this._maxage = maxAge; + return this; +}, 'send.maxage: pass maxAge as option'); + +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [error] + * @private + */ + +SendStream.prototype.error = function error(status, error) { + // emit if listeners instead of responding + if (listenerCount(this, 'error') !== 0) { + return this.emit('error', createError(error, status, { + expose: false + })) + } + + var res = this.res + var msg = statuses[status] + + // wipe all existing headers + res._headers = null + + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/plain; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(msg) +} + +/** + * Check if the pathname ends with "/". + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.hasTrailingSlash = function(){ + return '/' == this.path[this.path.length - 1]; +}; + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function(){ + return this.req.headers['if-none-match'] + || this.req.headers['if-modified-since']; +}; + +/** + * Strip content-* header fields. + * + * @private + */ + +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields() { + var res = this.res + var headers = Object.keys(res._headers || {}) + + for (var i = 0; i < headers.length; i++) { + var header = headers[i] + if (header.substr(0, 8) === 'content-' && header !== 'content-location') { + res.removeHeader(header) + } + } +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function(){ + var res = this.res; + debug('not modified'); + this.removeContentHeaderFields(); + res.statusCode = 304; + res.end(); +}; + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent(){ + var err = new Error('Can\'t set headers after they are sent.'); + debug('headers already sent'); + this.error(500, err); +}; + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function(){ + var res = this.res; + return (res.statusCode >= 200 && res.statusCode < 300) || 304 == res.statusCode; +}; + +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ + +SendStream.prototype.onStatError = function onStatError(error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function(){ + return fresh(this.req.headers, this.res._headers); +}; + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh(){ + var ifRange = this.req.headers['if-range']; + + if (!ifRange) return true; + + return ~ifRange.indexOf('"') + ? ~ifRange.indexOf(this.res._headers['etag']) + : Date.parse(this.res._headers['last-modified']) <= Date.parse(ifRange); +}; + +/** + * Redirect to path. + * + * @param {string} path + * @private + */ + +SendStream.prototype.redirect = function redirect(path) { + if (listenerCount(this, 'directory') !== 0) { + this.emit('directory') + return + } + + if (this.hasTrailingSlash()) { + this.error(403) + return + } + + var loc = path + '/' + var msg = 'Redirecting to ' + escapeHtml(loc) + '\n' + var res = this.res + + // redirect + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(msg) +} + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function(res){ + var self = this + , args = arguments + , root = this._root; + + // references + this.res = res; + + // decode the path + var path = decode(this.path) + if (path === -1) return this.error(400) + + // null byte(s) + if (~path.indexOf('\0')) return this.error(400); + + var parts + if (root !== null) { + // malicious path + 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 { + // ".." is malicious without "root" + if (upPathRegexp.test(path)) { + debug('malicious path "%s"', path) + return this.error(403) + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + // dotfile handling + if (containsDotFile(parts)) { + var access = this._dotfiles + + // legacy support + if (access === undefined) { + access = parts[parts.length - 1][0] === '.' + ? (this._hidden ? 'allow' : 'ignore') + : 'allow' + } + + debug('%s dotfile "%s"', access, path) + switch (access) { + case 'allow': + break + case 'deny': + return this.error(403) + case 'ignore': + default: + return this.error(404) + } + } + + // index file support + if (this._index.length && this.path[this.path.length - 1] === '/') { + this.sendIndex(path); + return res; + } + + this.sendFile(path); + return res; +}; + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function(path, stat){ + var len = stat.size; + var options = this.options + var opts = {} + var res = this.res; + var req = this.req; + var ranges = req.headers.range; + var offset = options.start || 0; + + if (res._header) { + // impossible to send now + return this.headersAlreadySent(); + } + + debug('pipe "%s"', path) + + // set header fields + this.setHeader(path, stat); + + // set content-type + this.type(path); + + // conditional GET support + if (this.isConditionalGET() + && this.isCachable() + && this.isFresh()) { + return this.notModified(); + } + + // adjust len to start/end options + len = Math.max(0, len - offset); + if (options.end !== undefined) { + var bytes = options.end - offset + 1; + if (len > bytes) len = bytes; + } + + // Range support + if (ranges) { + ranges = parseRange(len, ranges); + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale'); + ranges = -2; + } + + // unsatisfiable + if (-1 == ranges) { + debug('range unsatisfiable'); + res.setHeader('Content-Range', 'bytes */' + stat.size); + return this.error(416); + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (-2 != ranges && ranges.length === 1) { + debug('range %j', ranges); + + // Content-Range + res.statusCode = 206; + res.setHeader('Content-Range', 'bytes ' + + ranges[0].start + + '-' + + ranges[0].end + + '/' + + len); + + 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, opts) +}; + +/** + * Transfer file for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendFile = function sendFile(path) { + var i = 0 + var self = this + + debug('stat "%s"', path); + fs.stat(path, function onstat(err, stat) { + if (err && err.code === 'ENOENT' + && !extname(path) + && path[path.length - 1] !== sep) { + // not found, check extensions + return next(err) + } + if (err) return self.onStatError(err) + if (stat.isDirectory()) return self.redirect(self.path) + self.emit('file', path, stat) + self.send(path, stat) + }) + + function next(err) { + if (self._extensions.length <= i) { + return err + ? self.onStatError(err) + : self.error(404) + } + + var p = path + '.' + self._extensions[i++] + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } +} + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex(path){ + var i = -1; + var self = this; + + function next(err){ + if (++i >= self._index.length) { + if (err) return self.onStatError(err); + return self.error(404); + } + + var p = join(path, self._index[i]); + + debug('stat "%s"', p); + fs.stat(p, function(err, stat){ + if (err) return next(err); + if (stat.isDirectory()) return next(); + self.emit('file', p, stat); + self.send(p, stat); + }); + } + + next(); +}; + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function(path, options){ + // TODO: this is all lame, refactor meeee + var finished = false; + var self = this; + var res = this.res; + var req = this.req; + + // pipe + var stream = fs.createReadStream(path, options); + this.emit('stream', stream); + stream.pipe(res); + + // response finished, done with the fd + onFinished(res, function onfinished(){ + finished = true; + destroy(stream); + }); + + // error handling code-smell + stream.on('error', function onerror(err){ + // request already finished + if (finished) return; + + // clean up stream + finished = true; + destroy(stream); + + // error + self.onStatError(err); + }); + + // end + stream.on('end', function onend(){ + self.emit('end'); + }); +}; + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function(path){ + var res = this.res; + if (res.getHeader('Content-Type')) return; + var type = mime.lookup(path); + var charset = mime.charsets.lookup(type); + debug('content-type %s', type); + res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')); +}; + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader(path, stat){ + var res = this.res; + + this.emit('headers', res, path, stat); + + if (!res.getHeader('Accept-Ranges')) res.setHeader('Accept-Ranges', 'bytes'); + if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + Math.floor(this._maxage / 1000)); + + if (this._lastModified && !res.getHeader('Last-Modified')) { + var modified = stat.mtime.toUTCString() + debug('modified %s', modified) + res.setHeader('Last-Modified', modified) + } + + if (this._etag && !res.getHeader('ETag')) { + var val = etag(stat) + debug('etag %s', val) + res.setHeader('ETag', val) + } +}; + +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ + +function containsDotFile(parts) { + for (var i = 0; i < parts.length; i++) { + if (parts[i][0] === '.') { + return true + } + } + + return false +} + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +function decode(path) { + try { + return decodeURIComponent(path) + } catch (err) { + return -1 + } +} + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +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/5-3/node_modules/express/node_modules/send/node_modules/.bin/mime b/5-3/node_modules/express/node_modules/send/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/5-3/node_modules/express/node_modules/send/node_modules/destroy/LICENSE b/5-3/node_modules/express/node_modules/send/node_modules/destroy/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/destroy/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/send/node_modules/destroy/README.md b/5-3/node_modules/express/node_modules/send/node_modules/destroy/README.md new file mode 100644 index 0000000..6474bc3 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/destroy/README.md @@ -0,0 +1,60 @@ +# Destroy + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Destroy a stream. + +This module is meant to ensure a stream gets destroyed, handling different APIs +and Node.js bugs. + +## API + +```js +var destroy = require('destroy') +``` + +### destroy(stream) + +Destroy the given stream. In most cases, this is identical to a simple +`stream.destroy()` call. The rules are as follows for a given stream: + + 1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()` + and add a listener to the `open` event to call `stream.close()` if it is + fired. This is for a Node.js bug that will leak a file descriptor if + `.destroy()` is called before `open`. + 2. If the `stream` is not an instance of `Stream`, then nothing happens. + 3. If the `stream` has a `.destroy()` method, then call it. + +The function returns the `stream` passed in as the argument. + +## Example + +```js +var destroy = require('destroy') + +var fs = require('fs') +var stream = fs.createReadStream('package.json') + +// ... and later +destroy(stream) +``` + +[npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square +[npm-url]: https://npmjs.org/package/destroy +[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square +[github-url]: https://github.com/stream-utils/destroy/tags +[travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square +[travis-url]: https://travis-ci.org/stream-utils/destroy +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master +[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/destroy +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/5-3/node_modules/express/node_modules/send/node_modules/destroy/index.js b/5-3/node_modules/express/node_modules/send/node_modules/destroy/index.js new file mode 100644 index 0000000..6da2d26 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/destroy/index.js @@ -0,0 +1,75 @@ +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var ReadStream = require('fs').ReadStream +var Stream = require('stream') + +/** + * Module exports. + * @public + */ + +module.exports = destroy + +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ + +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) + } + + if (!(stream instanceof Stream)) { + return stream + } + + if (typeof stream.destroy === 'function') { + stream.destroy() + } + + return stream +} + +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ + +function destroyReadStream(stream) { + stream.destroy() + + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } + + return stream +} + +/** + * On open handler to close stream. + * @private + */ + +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } +} diff --git a/5-3/node_modules/express/node_modules/send/node_modules/destroy/package.json b/5-3/node_modules/express/node_modules/send/node_modules/destroy/package.json new file mode 100644 index 0000000..f7f3f16 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/destroy/package.json @@ -0,0 +1,72 @@ +{ + "name": "destroy", + "description": "destroy a stream if possible", + "version": "1.0.4", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/destroy.git" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4" + }, + "scripts": { + "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" + }, + "files": [ + "index.js", + "LICENSE" + ], + "keywords": [ + "stream", + "streams", + "destroy", + "cleanup", + "leak", + "fd" + ], + "gitHead": "86edea01456f5fa1027f6a47250c34c713cbcc3b", + "bugs": { + "url": "https://github.com/stream-utils/destroy/issues" + }, + "homepage": "https://github.com/stream-utils/destroy", + "_id": "destroy@1.0.4", + "_shasum": "978857442c44749e4206613e37946205826abd80", + "_from": "destroy@>=1.0.4 <1.1.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" + } + ], + "dist": { + "shasum": "978857442c44749e4206613e37946205826abd80", + "tarball": "http://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md new file mode 100644 index 0000000..4c7087d --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/HISTORY.md @@ -0,0 +1,76 @@ +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/send/node_modules/http-errors/README.md b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/README.md new file mode 100644 index 0000000..520271e --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/README.md @@ -0,0 +1,63 @@ +# http-errors + +[![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] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Example + +```js +var createError = require('http-errors'); + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')); + next(); +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +### Error Properties + +- `message` +- `status` and `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + +```js +var err = createError(404, 'This video does not exist!'); +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### new createError\[code || name\](\[msg]\)) + +```js +var err = new createError.NotFound(); +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/http-errors.svg?style=flat +[npm-url]: https://npmjs.org/package/http-errors +[node-version-image]: https://img.shields.io/node/v/http-errors.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/http-errors.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/http-errors +[coveralls-image]: https://img.shields.io/coveralls/jshttp/http-errors.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors +[downloads-image]: https://img.shields.io/npm/dm/http-errors.svg?style=flat +[downloads-url]: https://npmjs.org/package/http-errors diff --git a/5-3/node_modules/express/node_modules/send/node_modules/http-errors/index.js b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/index.js new file mode 100644 index 0000000..d84b114 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/index.js @@ -0,0 +1,120 @@ + +var statuses = require('statuses'); +var inherits = require('inherits'); + +function toIdentifier(str) { + return str.split(' ').map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }).join('').replace(/[^ _0-9a-z]/gi, '') +} + +exports = module.exports = function httpError() { + // so much arity going on ~_~ + var err; + var msg; + var status = 500; + var props = {}; + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (arg instanceof Error) { + err = arg; + status = err.status || err.statusCode || status; + continue; + } + switch (typeof arg) { + case 'string': + msg = arg; + break; + case 'number': + status = arg; + break; + case 'object': + props = arg; + break; + } + } + + if (typeof status !== 'number' || !statuses[status]) { + status = 500 + } + + // constructor + var HttpError = exports[status] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, httpError) + } + + if (!HttpError || !(err instanceof HttpError)) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err; +}; + +// create generic error objects +var codes = statuses.codes.filter(function (num) { + return num >= 400; +}); + +codes.forEach(function (code) { + var name = toIdentifier(statuses[code]) + var className = name.match(/Error$/) ? name : name + 'Error' + + if (code >= 500) { + var ServerError = function ServerError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ServerError) + self.__proto__ = ServerError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ServerError, Error); + ServerError.prototype.status = + ServerError.prototype.statusCode = code; + ServerError.prototype.expose = false; + exports[code] = + exports[name] = ServerError + return; + } + + var ClientError = function ClientError(msg) { + var self = new Error(msg != null ? msg : statuses[code]) + Error.captureStackTrace(self, ClientError) + self.__proto__ = ClientError.prototype + Object.defineProperty(self, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + return self + } + inherits(ClientError, Error); + ClientError.prototype.status = + ClientError.prototype.statusCode = code; + ClientError.prototype.expose = true; + exports[code] = + exports[name] = ClientError + return; +}); + +// backwards-compatibility +exports["I'mateapot"] = exports.ImATeapot diff --git a/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +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/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +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/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +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/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json new file mode 100644 index 0000000..93d5078 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/package.json @@ -0,0 +1,50 @@ +{ + "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.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "_id": "inherits@2.0.1", + "dist": { + "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/inherits#readme" +} diff --git a/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +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/5-3/node_modules/express/node_modules/send/node_modules/http-errors/package.json b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/package.json new file mode 100644 index 0000000..41f845d --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/http-errors/package.json @@ -0,0 +1,85 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "1.3.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "contributors": [ + { + "name": "Alan Plum", + "email": "me@pluma.io" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/http-errors.git" + }, + "dependencies": { + "inherits": "~2.0.1", + "statuses": "1" + }, + "devDependencies": { + "istanbul": "0", + "mocha": "1" + }, + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ], + "gitHead": "89a8502b40d5dd42da2908f265275e2eeb8d0699", + "bugs": { + "url": "https://github.com/jshttp/http-errors/issues" + }, + "homepage": "https://github.com/jshttp/http-errors", + "_id": "http-errors@1.3.1", + "_shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "_from": "http-errors@>=1.3.1 <1.4.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "egeste", + "email": "npm@egeste.net" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "197e22cdebd4198585e8694ef6786197b91ed942", + "tarball": "http://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/send/node_modules/mime/.npmignore b/5-3/node_modules/express/node_modules/send/node_modules/mime/.npmignore new file mode 100644 index 0000000..e69de29 diff --git a/5-3/node_modules/express/node_modules/send/node_modules/mime/LICENSE b/5-3/node_modules/express/node_modules/send/node_modules/mime/LICENSE new file mode 100644 index 0000000..451fc45 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/mime/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/send/node_modules/mime/README.md b/5-3/node_modules/express/node_modules/send/node_modules/mime/README.md new file mode 100644 index 0000000..506fbe5 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/mime/README.md @@ -0,0 +1,90 @@ +# mime + +Comprehensive MIME type mapping API based on mime-db module. + +## Install + +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. + +```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.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + +```js +mime.extension('text/html'); // => 'html' +mime.extension('application/octet-stream'); // => 'bin' +``` + +### mime.charsets.lookup() + +Map mime-type to charset + +```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 + +Custom type mappings can be added on a per-project basis via the following APIs. + +### mime.define() + +Add custom mime/extension mappings + +```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' +``` + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + +```js +mime.extension('text/x-some-format'); // => 'x-sf' +``` + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + +```js +mime.load('./my_project.types'); +``` +The .types file format is simple - See the `types` dir for examples. diff --git a/5-3/node_modules/express/node_modules/send/node_modules/mime/build/build.js b/5-3/node_modules/express/node_modules/send/node_modules/mime/build/build.js new file mode 100644 index 0000000..ed5313e --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/mime/build/build.js @@ -0,0 +1,11 @@ +var db = require('mime-db'); + +var mapByType = {}; +Object.keys(db).forEach(function(key) { + var extensions = db[key].extensions; + if (extensions) { + mapByType[key] = extensions; + } +}); + +console.log(JSON.stringify(mapByType)); diff --git a/5-3/node_modules/express/node_modules/send/node_modules/mime/build/test.js b/5-3/node_modules/express/node_modules/send/node_modules/mime/build/test.js new file mode 100644 index 0000000..58b9ba7 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/mime/build/test.js @@ -0,0 +1,57 @@ +/** + * Usage: node test.js + */ + +var mime = require('../mime'); +var assert = require('assert'); +var path = require('path'); + +// +// Test mime lookups +// + +assert.equal('text/plain', mime.lookup('text.txt')); // normal file +assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase +assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file +assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file +assert.equal('text/plain', mime.lookup('.txt')); // nameless +assert.equal('text/plain', mime.lookup('txt')); // extension-only +assert.equal('text/plain', mime.lookup('/txt')); // extension-less () +assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less +assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized +assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +assert.equal('txt', mime.extension(mime.types.text)); +assert.equal('html', mime.extension(mime.types.htm)); +assert.equal('bin', mime.extension('application/octet-stream')); +assert.equal('bin', mime.extension('application/octet-stream ')); +assert.equal('html', mime.extension(' text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html; charset=UTF-8 ')); +assert.equal('html', mime.extension('text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html ; charset=UTF-8')); +assert.equal('html', mime.extension('text/html;charset=UTF-8')); +assert.equal('html', mime.extension('text/Html;charset=UTF-8')); +assert.equal(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +assert.equal('application/font-woff', mime.lookup('file.woff')); +assert.equal('application/octet-stream', mime.lookup('file.buffer')); +assert.equal('audio/mp4', mime.lookup('file.m4a')); +assert.equal('font/opentype', mime.lookup('file.otf')); + +// +// Test charsets +// + +assert.equal('UTF-8', mime.charsets.lookup('text/plain')); +assert.equal(undefined, mime.charsets.lookup(mime.types.js)); +assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +console.log('\nAll tests passed'); diff --git a/5-3/node_modules/express/node_modules/send/node_modules/mime/cli.js b/5-3/node_modules/express/node_modules/send/node_modules/mime/cli.js new file mode 100755 index 0000000..20b1ffe --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/mime/cli.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node + +var mime = require('./mime.js'); +var file = process.argv[2]; +var type = mime.lookup(file); + +process.stdout.write(type + '\n'); + diff --git a/5-3/node_modules/express/node_modules/send/node_modules/mime/mime.js b/5-3/node_modules/express/node_modules/send/node_modules/mime/mime.js new file mode 100644 index 0000000..341b6a5 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/mime/mime.js @@ -0,0 +1,108 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts]) { + console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Define built-in types +mime.define(require('./types.json')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/5-3/node_modules/express/node_modules/send/node_modules/mime/package.json b/5-3/node_modules/express/node_modules/send/node_modules/mime/package.json new file mode 100644 index 0000000..31e7669 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/mime/package.json @@ -0,0 +1,73 @@ +{ + "author": { + "name": "Robert Kieffer", + "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", + "email": "benjamin@benjaminthomas.org", + "url": "http://github.com/bentomas" + } + ], + "description": "A comprehensive library for mime-type mapping", + "licenses": [ + { + "type": "MIT", + "url": "https://raw.github.com/broofa/node-mime/master/LICENSE" + } + ], + "dependencies": {}, + "devDependencies": { + "mime-db": "^1.2.0" + }, + "keywords": [ + "util", + "mime" + ], + "main": "mime.js", + "name": "mime", + "repository": { + "url": "git+https://github.com/broofa/node-mime.git", + "type": "git" + }, + "version": "1.3.4", + "gitHead": "1628f6e0187095009dcef4805c3a49706f137974", + "bugs": { + "url": "https://github.com/broofa/node-mime/issues" + }, + "homepage": "https://github.com/broofa/node-mime", + "_id": "mime@1.3.4", + "_shasum": "115f9e3b6b3daf2959983cb38f149a2d40eb5d53", + "_from": "mime@1.3.4", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "broofa", + "email": "robert@broofa.com" + }, + "maintainers": [ + { + "name": "broofa", + "email": "robert@broofa.com" + }, + { + "name": "bentomas", + "email": "benjamin@benjaminthomas.org" + } + ], + "dist": { + "shasum": "115f9e3b6b3daf2959983cb38f149a2d40eb5d53", + "tarball": "http://registry.npmjs.org/mime/-/mime-1.3.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime/-/mime-1.3.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/send/node_modules/mime/types.json b/5-3/node_modules/express/node_modules/send/node_modules/mime/types.json new file mode 100644 index 0000000..c674b1c --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/mime/types.json @@ -0,0 +1 @@ +{"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomsvc+xml":["atomsvc"],"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/cu-seeme":["cu"],"application/dash+xml":["mdp"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/font-tdpfr":["pfr"],"application/font-woff":["woff"],"application/font-woff2":["woff2"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/java-archive":["jar"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","buffer"],"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/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"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/postscript":["ai","eps","ps"],"application/prs.cww":["cww"],"application/pskc+xml":["pskcxml"],"application/rdf+xml":["rdf"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"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-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"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.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"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.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.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"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.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.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"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.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"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.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"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.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"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.gmx":["gmx"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"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+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"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.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.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"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.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.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.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"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.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"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-officetheme":["thmx"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["stl"],"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-project":["mpp","mpt"],"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.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"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.n-gage.data":["ngdat"],"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.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.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"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.sailingtracker.track":["st"],"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.teacher":["teacher"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"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.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.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"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.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.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"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.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/voicexml+xml":["vxml"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"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-chrome-extension":["crx"],"application/x-conference":["nsc"],"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-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-otf":["otf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-ttf":["ttf","ttc"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"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-hdf":["hdf"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["iso"],"application/x-java-jnlp-file":["jnlp"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"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-web-app-manifest+json":["webapp"],"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/xaml+xml":["xaml"],"application/xcap-diff+xml":["xdf"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xml":["xml","xsl","xsd"],"application/xml-dtd":["dtd"],"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/adpcm":["adp"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mp4":["mp4a","m4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"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-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-xyz":["xyz"],"font/opentype":["otf"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/g3fax":["g3"],"image/gif":["gif"],"image/ief":["ief"],"image/jpeg":["jpeg","jpg","jpe"],"image/ktx":["ktx"],"image/png":["png"],"image/prs.btif":["btif"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/tiff":["tiff","tif"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["sub"],"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.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"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/rfc822":["eml","mime"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.vtu":["vtu"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["x3db","x3dbz"],"model/x3d+vrml":["x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee"],"text/css":["css"],"text/csv":["csv"],"text/hjson":["hjson"],"text/html":["html","htm"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/prs.lines.tag":["dsc"],"text/richtext":["rtx"],"text/sgml":["sgml","sgm"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"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.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/vtt":["vtt"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["markdown","md","mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-pascal":["p","pas"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"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/5-3/node_modules/express/node_modules/send/node_modules/ms/.npmignore b/5-3/node_modules/express/node_modules/send/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/5-3/node_modules/express/node_modules/send/node_modules/ms/History.md b/5-3/node_modules/express/node_modules/send/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/send/node_modules/ms/LICENSE b/5-3/node_modules/express/node_modules/send/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/5-3/node_modules/express/node_modules/send/node_modules/ms/README.md b/5-3/node_modules/express/node_modules/send/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/5-3/node_modules/express/node_modules/send/node_modules/ms/index.js b/5-3/node_modules/express/node_modules/send/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/5-3/node_modules/express/node_modules/send/node_modules/ms/package.json b/5-3/node_modules/express/node_modules/send/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/send/node_modules/statuses/LICENSE b/5-3/node_modules/express/node_modules/send/node_modules/statuses/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/statuses/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/send/node_modules/statuses/README.md b/5-3/node_modules/express/node_modules/send/node_modules/statuses/README.md new file mode 100644 index 0000000..f6ae24c --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/statuses/README.md @@ -0,0 +1,114 @@ +# Statuses + +[![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] + +HTTP status utility for node. + +## API + +```js +var status = require('statuses'); +``` + +### var code = status(Integer || String) + +If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown. + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status('forbidden') // => 403 +status('Forbidden') // => 403 +status(306) // throws, as it's not supported by node.js +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### var msg = status[code] + +Map of `code` to `status message`. `undefined` for invalid `code`s. + +```js +status[404] // => 'Not Found' +``` + +### var code = status[msg] + +Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s. + +```js +status['not found'] // => 404 +status['Not Found'] // => 404 +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +### statuses/codes.json + +```js +var codes = require('statuses/codes.json'); +``` + +This is a JSON file of the status codes +taken from `require('http').STATUS_CODES`. +This is saved so that codes are consistent even in older node.js versions. +For example, `308` will be added in v0.12. + +## Adding Status Codes + +The status codes are primarily sourced from http://www.iana.org/assignments/http-status-codes/http-status-codes-1.csv. +Additionally, custom codes are added from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes. +These are added manually in the `lib/*.json` files. +If you would like to add a status code, add it to the appropriate JSON file. + +To rebuild `codes.json`, run the following: + +```bash +# update src/iana.json +npm run update +# build codes.json +npm run build +``` + +[npm-image]: https://img.shields.io/npm/v/statuses.svg?style=flat +[npm-url]: https://npmjs.org/package/statuses +[node-version-image]: http://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/statuses.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/statuses +[coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[downloads-image]: http://img.shields.io/npm/dm/statuses.svg?style=flat +[downloads-url]: https://npmjs.org/package/statuses diff --git a/5-3/node_modules/express/node_modules/send/node_modules/statuses/codes.json b/5-3/node_modules/express/node_modules/send/node_modules/statuses/codes.json new file mode 100644 index 0000000..4c45a88 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/statuses/codes.json @@ -0,0 +1,64 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "(Unused)", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} \ No newline at end of file diff --git a/5-3/node_modules/express/node_modules/send/node_modules/statuses/index.js b/5-3/node_modules/express/node_modules/send/node_modules/statuses/index.js new file mode 100644 index 0000000..b06182d --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/statuses/index.js @@ -0,0 +1,60 @@ + +var codes = require('./codes.json'); + +module.exports = status; + +// [Integer...] +status.codes = Object.keys(codes).map(function (code) { + code = ~~code; + var msg = codes[code]; + status[code] = msg; + status[msg] = status[msg.toLowerCase()] = code; + return code; +}); + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true, +}; + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true, +}; + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true, +}; + +function status(code) { + if (typeof code === 'number') { + if (!status[code]) throw new Error('invalid status code: ' + code); + return code; + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string'); + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n); + return n; + } + + n = status[code.toLowerCase()]; + if (!n) throw new Error('invalid status message: "' + code + '"'); + return n; +} diff --git a/5-3/node_modules/express/node_modules/send/node_modules/statuses/package.json b/5-3/node_modules/express/node_modules/send/node_modules/statuses/package.json new file mode 100644 index 0000000..81aba72 --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/node_modules/statuses/package.json @@ -0,0 +1,84 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "1.2.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/statuses.git" + }, + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "0.0.6", + "istanbul": "0", + "mocha": "1", + "stream-to-array": "2" + }, + "scripts": { + "build": "node scripts/build.js", + "update": "node scripts/update.js", + "test": "mocha --reporter spec --bail --check-leaks", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks" + }, + "gitHead": "49e6ac7ae4c63ee8186f56cb52112a7eeda28ed7", + "bugs": { + "url": "https://github.com/jshttp/statuses/issues" + }, + "homepage": "https://github.com/jshttp/statuses", + "_id": "statuses@1.2.1", + "_shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "_from": "statuses@>=1.2.1 <1.3.0", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "shtylman", + "email": "shtylman@gmail.com" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "dded45cc18256d51ed40aec142489d5c61026d28", + "tarball": "http://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/statuses/-/statuses-1.2.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/send/package.json b/5-3/node_modules/express/node_modules/send/package.json new file mode 100644 index 0000000..38fcf6f --- /dev/null +++ b/5-3/node_modules/express/node_modules/send/package.json @@ -0,0 +1,89 @@ +{ + "name": "send", + "description": "Better streaming static file server with Range and conditional-GET support", + "version": "0.13.1", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/send.git" + }, + "keywords": [ + "static", + "file", + "server" + ], + "dependencies": { + "debug": "~2.2.0", + "depd": "~1.1.0", + "destroy": "~1.0.4", + "escape-html": "~1.0.3", + "etag": "~1.7.0", + "fresh": "0.3.0", + "http-errors": "~1.3.1", + "mime": "1.3.4", + "ms": "0.7.1", + "on-finished": "~2.3.0", + "range-parser": "~1.0.3", + "statuses": "~1.2.1" + }, + "devDependencies": { + "after": "0.8.1", + "istanbul": "0.4.2", + "mocha": "2.3.4", + "supertest": "1.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --check-leaks --reporter spec --bail", + "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": "dbce43fc7102c14b475c25cde918b726063cc991", + "bugs": { + "url": "https://github.com/pillarjs/send/issues" + }, + "homepage": "https://github.com/pillarjs/send", + "_id": "send@0.13.1", + "_shasum": "a30d5f4c82c8a9bae9ad00a1d9b1bdbe6f199ed7", + "_from": "send@0.13.1", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "a30d5f4c82c8a9bae9ad00a1d9b1bdbe6f199ed7", + "tarball": "http://registry.npmjs.org/send/-/send-0.13.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/send/-/send-0.13.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/serve-static/HISTORY.md b/5-3/node_modules/express/node_modules/serve-static/HISTORY.md new file mode 100644 index 0000000..da30741 --- /dev/null +++ b/5-3/node_modules/express/node_modules/serve-static/HISTORY.md @@ -0,0 +1,303 @@ +1.10.2 / 2016-01-19 +=================== + + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.10.1 / 2016-01-16 +=================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + +1.10.0 / 2015-06-17 +=================== + + * Add `fallthrough` option + - Allows declaring this middleware is the final destination + - Provides better integration with Express patterns + * Fix reading options from options prototype + * Improve the default redirect response headers + * deps: escape-html@1.0.2 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * Fix potential open redirect when mounted at root + +1.7.1 / 2014-10-22 +================== + + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +1.7.0 / 2014-10-15 +================== + + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - 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 +================== + + * Fix redirect loop when index file serving disabled + +1.6.3 / 2014-09-24 +================== + + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +1.6.2 / 2014-09-15 +================== + + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +1.6.1 / 2014-09-07 +================== + + * deps: send@0.9.1 + - deps: fresh@0.2.4 + +1.6.0 / 2014-09-07 +================== + + * deps: send@0.9.0 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + +1.5.4 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +1.5.3 / 2014-08-17 +================== + + * deps: send@0.8.3 + +1.5.2 / 2014-08-14 +================== + + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +1.5.1 / 2014-08-09 +================== + + * Fix parsing of weird `req.originalUrl` values + * deps: parseurl@~1.3.0 + * deps: utils-merge@1.0.0 + +1.5.0 / 2014-08-05 +================== + + * deps: send@0.8.1 + - Add `extensions` option + +1.4.4 / 2014-08-04 +================== + + * deps: send@0.7.4 + - Fix serving index files without root dir + +1.4.3 / 2014-07-29 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + +1.4.2 / 2014-07-27 +================== + + * deps: send@0.7.2 + - deps: depd@0.4.4 + +1.4.1 / 2014-07-26 +================== + + * deps: send@0.7.1 + - deps: depd@0.4.3 + +1.4.0 / 2014-07-21 +================== + + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +1.3.2 / 2014-07-11 +================== + + * deps: send@0.6.0 + - Cap `maxAge` value to 1 year + - deps: debug@1.0.3 + +1.3.1 / 2014-07-09 +================== + + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +1.3.0 / 2014-06-28 +================== + + * Add `setHeaders` option + * Include HTML link in redirect response + * deps: send@0.5.0 + - Accept string for `maxAge` (converted by `ms`) + +1.2.3 / 2014-06-11 +================== + + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +1.2.2 / 2014-06-09 +================== + + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + +1.2.1 / 2014-06-02 +================== + + * use `escape-html` for escaping + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +1.2.0 / 2014-05-29 +================== + + * deps: send@0.4.0 + - Calculate ETag with md5 for reduced collisions + - Fix wrong behavior when index file matches directory + - Ignore stream errors after request ends + - Skip directories in index file search + - deps: debug@0.8.1 + +1.1.0 / 2014-04-24 +================== + + * Accept options directly to `send` module + * deps: send@0.3.0 + +1.0.4 / 2014-04-07 +================== + + * Resolve relative paths at middleware setup + * Use parseurl to parse the URL from request + +1.0.3 / 2014-03-20 +================== + + * Do not rely on connect-like environments + +1.0.2 / 2014-03-06 +================== + + * deps: send@0.2.0 + +1.0.1 / 2014-03-05 +================== + + * Add mime export for back-compat + +1.0.0 / 2014-03-05 +================== + + * Genesis from `connect` diff --git a/5-3/node_modules/express/node_modules/serve-static/LICENSE b/5-3/node_modules/express/node_modules/serve-static/LICENSE new file mode 100644 index 0000000..d8cce67 --- /dev/null +++ b/5-3/node_modules/express/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014-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: + +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/5-3/node_modules/express/node_modules/serve-static/README.md b/5-3/node_modules/express/node_modules/serve-static/README.md new file mode 100644 index 0000000..62104b1 --- /dev/null +++ b/5-3/node_modules/express/node_modules/serve-static/README.md @@ -0,0 +1,236 @@ +# serve-static + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +## Install + +```sh +$ npm install serve-static +``` + +## API + +```js +var serveStatic = require('serve-static') +``` + +### serveStatic(root, options) + +Create a new middleware function to serve files from within a given root +directory. The file to serve will be determined by combining `req.url` +with the provided root directory. When a file is not found, instead of +sending a 404 response, this module will instead call `next()` to move on +to the next middleware, allowing for stacking and fall-backs. + +#### 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 set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Deny a request for a dotfile and 403/`next()`. + - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. + +The default value is similar to `'ignore'`, with the exception that this +default will not ignore the files within a directory that begins with a dot. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +Set file extension fallbacks. When set, if a file is not found, the given +extensions will be added to the file name and search for. The first that +exists will be served. Example: `['html', 'htm']`. + +The default value is `false`. + +##### fallthrough + +Set the middleware to have client errors fall-through as just unhandled +requests, otherwise forward a client error. The difference is that client +errors like a bad request or a request to a non-existent file will cause +this middleware to simply `next()` to your next middleware when this value +is `true`. When this value is `false`, these errors (even 404s), will invoke +`next(err)`. + +Typically `true` is desired such that multiple physical directories can be +mapped to the same web address or for routes to fill in non-existent files. + +The value `false` can be used if this middleware is mounted at a path that +is designed to be strictly a single file system directory, which allows for +short-circuiting 404s for less overhead. This middleware will also reply to +all methods. + +The default value is `true`. + +##### index + +By default this module will send "index.html" files in response to a request +on a directory. 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. + +##### redirect + +Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. + +##### setHeaders + +Function to set custom headers on response. Alterations to the headers need to +occur synchronously. The function is called as `fn(res, path, stat)`, where +the arguments are: + + - `res` the response object + - `path` the file path that is being sent + - `stat` the stat object of the file that is being sent + +## Examples + +### Serve files with vanilla node.js http server + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', {'index': ['index.html', 'index.htm']}) + +// Create server +var server = http.createServer(function(req, res){ + var done = finalhandler(req, res) + serve(req, res, done) +}) + +// Listen +server.listen(3000) +``` + +### Serve all files as downloads + +```js +var contentDisposition = require('content-disposition') +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { + 'index': false, + 'setHeaders': setHeaders +}) + +// Set header to force download +function setHeaders(res, path) { + res.setHeader('Content-Disposition', contentDisposition(path)) +} + +// Create server +var server = http.createServer(function(req, res){ + var done = finalhandler(req, res) + serve(req, res, done) +}) + +// Listen +server.listen(3000) +``` + +### Serving using express + +#### Simple + +This is a simple example of using Express. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +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 +[npm-url]: https://npmjs.org/package/serve-static +[travis-image]: https://img.shields.io/travis/expressjs/serve-static/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/serve-static +[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 +[downloads-url]: https://npmjs.org/package/serve-static +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://gratipay.com/dougwilson/ diff --git a/5-3/node_modules/express/node_modules/serve-static/index.js b/5-3/node_modules/express/node_modules/serve-static/index.js new file mode 100644 index 0000000..0a9f494 --- /dev/null +++ b/5-3/node_modules/express/node_modules/serve-static/index.js @@ -0,0 +1,187 @@ +/*! + * serve-static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var escapeHtml = require('escape-html') +var parseUrl = require('parseurl') +var resolve = require('path').resolve +var send = require('send') +var url = require('url') + +/** + * Module exports. + * @public + */ + +module.exports = serveStatic +module.exports.mime = send.mime + +/** + * @param {string} root + * @param {object} [options] + * @return {function} + * @public + */ + +function serveStatic(root, options) { + if (!root) { + throw new TypeError('root path required') + } + + if (typeof root !== 'string') { + throw new TypeError('root path must be a string') + } + + // copy options object + var opts = Object.create(options || null) + + // fall-though + var fallthrough = opts.fallthrough !== false + + // default redirect + var redirect = opts.redirect !== false + + // headers listener + var setHeaders = opts.setHeaders + + if (setHeaders && typeof setHeaders !== 'function') { + throw new TypeError('option setHeaders must be function') + } + + // setup options for send + opts.maxage = opts.maxage || opts.maxAge || 0 + opts.root = resolve(root) + + // construct directory listener + var onDirectory = redirect + ? createRedirectDirectoryListener() + : createNotFoundDirectoryListener() + + return function serveStatic(req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + if (fallthrough) { + return next() + } + + // method not allowed + res.statusCode = 405 + res.setHeader('Allow', 'GET, HEAD') + res.setHeader('Content-Length', '0') + res.end() + return + } + + var forwardError = !fallthrough + var originalUrl = parseUrl.original(req) + var path = parseUrl(req).pathname + + // make sure redirect occurs at mount + if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { + path = '' + } + + // create send stream + var stream = send(req, path, opts) + + // add directory handler + stream.on('directory', onDirectory) + + // add headers listener + if (setHeaders) { + stream.on('headers', setHeaders) + } + + // add file listener for fallthrough + if (fallthrough) { + stream.on('file', function onFile() { + // once file is determined, always forward error + forwardError = true + }) + } + + // forward errors + stream.on('error', function error(err) { + if (forwardError || !(err.statusCode < 500)) { + next(err) + return + } + + next() + }) + + // pipe + stream.pipe(res) + } +} + +/** + * Collapse all leading slashes into a single slash + * @private + */ +function collapseLeadingSlashes(str) { + for (var i = 0; i < str.length; i++) { + if (str[i] !== '/') { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Create a directory listener that just 404s. + * @private + */ + +function createNotFoundDirectoryListener() { + return function notFound() { + this.error(404) + } +} + +/** + * Create a directory listener that performs a redirect. + * @private + */ + +function createRedirectDirectoryListener() { + return function redirect() { + if (this.hasTrailingSlash()) { + this.error(404) + return + } + + // get original URL + var originalUrl = parseUrl.original(this.req) + + // append trailing slash + originalUrl.path = null + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') + + // reformat the URL + var loc = url.format(originalUrl) + var msg = 'Redirecting to ' + escapeHtml(loc) + '\n' + var res = this.res + + // send redirect response + res.statusCode = 303 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(msg)) + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(msg) + } +} diff --git a/5-3/node_modules/express/node_modules/serve-static/package.json b/5-3/node_modules/express/node_modules/serve-static/package.json new file mode 100644 index 0000000..b789b9a --- /dev/null +++ b/5-3/node_modules/express/node_modules/serve-static/package.json @@ -0,0 +1,83 @@ +{ + "name": "serve-static", + "description": "Serve static files", + "version": "1.10.2", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/serve-static.git" + }, + "dependencies": { + "escape-html": "~1.0.3", + "parseurl": "~1.3.1", + "send": "0.13.1" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4", + "supertest": "1.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "test": "mocha --reporter spec --bail --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": "aec36c897a33c6c2421fa41cc4947042d67332f6", + "bugs": { + "url": "https://github.com/expressjs/serve-static/issues" + }, + "homepage": "https://github.com/expressjs/serve-static", + "_id": "serve-static@1.10.2", + "_shasum": "feb800d0e722124dd0b00333160c16e9caa8bcb3", + "_from": "serve-static@>=1.10.2 <1.11.0", + "_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": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "mscdex", + "email": "mscdex@mscdex.net" + }, + { + "name": "fishrock123", + "email": "fishrock123@rocketmail.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "dist": { + "shasum": "feb800d0e722124dd0b00333160c16e9caa8bcb3", + "tarball": "http://registry.npmjs.org/serve-static/-/serve-static-1.10.2.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.10.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/type-is/HISTORY.md b/5-3/node_modules/express/node_modules/type-is/HISTORY.md new file mode 100644 index 0000000..e10b426 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/HISTORY.md @@ -0,0 +1,192 @@ +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +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 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/5-3/node_modules/express/node_modules/type-is/LICENSE b/5-3/node_modules/express/node_modules/type-is/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +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: + +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/5-3/node_modules/express/node_modules/type-is/README.md b/5-3/node_modules/express/node_modules/type-is/README.md new file mode 100644 index 0000000..7a754be --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/README.md @@ -0,0 +1,136 @@ +# type-is + +[![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] + +Infer the content-type of a request. + +### Install + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var is = require('type-is') + +http.createServer(function (req, res) { + var istext = is(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### type = is(request, types) + +`request` is the node HTTP request. `types` is an array of types. + +```js +// req.headers.content-type = 'application/json' + +is(req, ['json']) // 'json' +is(req, ['html', 'json']) // 'json' +is(req, ['application/*']) // 'application/json' +is(req, ['application/json']) // 'application/json' + +is(req, ['html']) // false +``` + +### is.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existance works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + +```js +if (is.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### type = is.is(mediaType, types) + +`mediaType` is the [media type](https://tools.ietf.org/html/rfc6838) string. `types` is an array of types. + +```js +var mediaType = 'application/json' + +is.is(mediaType, ['json']) // 'json' +is.is(mediaType, ['html', 'json']) // 'json' +is.is(mediaType, ['application/*']) // 'application/json' +is.is(mediaType, ['application/json']) // 'application/json' + +is.is(mediaType, ['html']) // false +``` + +### Each type can be: + +- An extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` 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 or the content type is invalid. + +`null` will be returned if the request does not have a body. + +## Examples + +#### Example body parser + +```js +var is = require('type-is'); + +function bodyParser(req, res, next) { + if (!is.hasBody(req)) { + return next() + } + + switch (is(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + break + case 'json': + // parse json body + throw new Error('implement json body parsing') + break + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + break + default: + // 415 error code + res.statusCode = 415 + res.end() + return + } +} +``` + +## License + +[MIT](LICENSE) + +[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 +[node-version-url]: https://nodejs.org/en/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[downloads-image]: https://img.shields.io/npm/dm/type-is.svg +[downloads-url]: https://npmjs.org/package/type-is diff --git a/5-3/node_modules/express/node_modules/type-is/index.js b/5-3/node_modules/express/node_modules/type-is/index.js new file mode 100644 index 0000000..ca2962e --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/index.js @@ -0,0 +1,262 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var typer = require('media-typer') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis(value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody(req) { + return req.headers['transfer-encoding'] !== undefined + || !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +function typeofrequest(req, types_) { + var types = types_ + + // no body + if (!hasbody(req)) { + return null + } + + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @private + */ + +function normalize(type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @private + */ + +function mimeMatch(expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // 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) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +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 { + return normalizeType(value) + } catch (err) { + return null + } +} diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md b/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md new file mode 100644 index 0000000..62c2003 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/HISTORY.md @@ -0,0 +1,22 @@ +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/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE b/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md b/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md new file mode 100644 index 0000000..d8df623 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/README.md @@ -0,0 +1,81 @@ +# 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/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js b/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js new file mode 100644 index 0000000..07f7295 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/index.js @@ -0,0 +1,270 @@ +/*! + * 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/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json b/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json new file mode 100644 index 0000000..e0f796d --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/media-typer/package.json @@ -0,0 +1,58 @@ +{ + "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": "git+https://github.com/jshttp/media-typer.git" + }, + "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/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..61b54b4 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/HISTORY.md @@ -0,0 +1,183 @@ +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +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 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(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 +'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/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md new file mode 100644 index 0000000..e26295d --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md @@ -0,0 +1,103 @@ +# mime-types + +[![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] + +The ultimate javascript content-type utility. + +Similar to [node-mime](https://github.com/broofa/node-mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, + so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db) +- No `.define()` functionality + +Otherwise, the API is compatible. + +## Install + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://github.com/jshttp/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/x-markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/x-markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[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/node/v/mime-types.svg +[node-version-url]: http://nodejs.org/download/ +[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/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js new file mode 100644 index 0000000..f7008b2 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js @@ -0,0 +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 + +/** + * 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) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * 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 +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension(type) { + if (!type || typeof type !== 'string') { + return false + } + + // 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 + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..41a667a --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/HISTORY.md @@ -0,0 +1,306 @@ +1.21.0 / 2016-01-06 +=================== + + * Add `application/emergencycalldata.comment+xml` + * Add `application/emergencycalldata.deviceinfo+xml` + * Add `application/emergencycalldata.providerinfo+xml` + * Add `application/emergencycalldata.serviceinfo+xml` + * Add `application/emergencycalldata.subscriberinfo+xml` + * Add `application/vnd.filmit.zfc` + * Add `application/vnd.google-apps.document` + * Add `application/vnd.google-apps.presentation` + * Add `application/vnd.google-apps.spreadsheet` + * Add `application/vnd.mapbox-vector-tile` + * Add `application/vnd.ms-printdevicecapabilities+xml` + * Add `application/vnd.ms-windows.devicepairing` + * Add `application/vnd.ms-windows.nwprinting.oob` + * Add `application/vnd.tml` + * Add `audio/evs` + +1.20.0 / 2015-11-10 +=================== + + * Add `application/cdni` + * Add `application/csvm+json` + * Add `application/rfc+xml` + * Add `application/vnd.3gpp.access-transfer-events+xml` + * Add `application/vnd.3gpp.srvcc-ext+xml` + * Add `application/vnd.ms-windows.wsd.oob` + * Add `application/vnd.oxli.countgraph` + * Add `application/vnd.pagerduty+json` + * Add `text/x-suse-ymp` + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.3gpp-prose-pc3ch+xml` + * Add `application/vnd.3gpp.srvcc-info+xml` + * Add `application/vnd.apple.pkpass` + * Add `application/vnd.drive+json` + +1.18.0 / 2015-09-03 +=================== + + * Add `application/pkcs12` + * Add `application/vnd.3gpp-prose+xml` + * Add `application/vnd.3gpp.mid-call+xml` + * Add `application/vnd.3gpp.state-and-event-info+xml` + * Add `application/vnd.anki` + * Add `application/vnd.firemonkeys.cloudcell` + * Add `application/vnd.openblox.game+xml` + * Add `application/vnd.openblox.game-binary` + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +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 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md new file mode 100644 index 0000000..7662440 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/README.md @@ -0,0 +1,82 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +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 + +```bash +npm install mime-db +``` + +### 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 +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + 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 can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +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 +[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/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[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 +[node-url]: http://nodejs.org/download/ diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json new file mode 100644 index 0000000..412ba9e --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/db.json @@ -0,0 +1,6552 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana" + }, + "application/3gpp-ims+xml": { + "source": "iana" + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana" + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana" + }, + "application/bacnet-xdd+zip": { + "source": "iana" + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana" + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana" + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana" + }, + "application/ccxml+xml": { + "source": "iana", + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana" + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana" + }, + "application/cellml+xml": { + "source": "iana" + }, + "application/cfw": { + "source": "iana" + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana" + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana" + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana" + }, + "application/cstadata+xml": { + "source": "iana" + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "extensions": ["mdp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana" + }, + "application/dicom": { + "source": "iana" + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana" + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/emergencycalldata.comment+xml": { + "source": "iana" + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana" + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana" + }, + "application/emma+xml": { + "source": "iana", + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana" + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana" + }, + "application/epub+zip": { + "source": "iana", + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana" + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false, + "extensions": ["woff"] + }, + "application/font-woff2": { + "compressible": false, + "extensions": ["woff2"] + }, + "application/framework-attributes+xml": { + "source": "iana" + }, + "application/gml+xml": { + "source": "apache", + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana" + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana" + }, + "application/ibe-pkg-reply+xml": { + "source": "iana" + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana" + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana" + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js"] + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana" + }, + "application/kpml-response+xml": { + "source": "iana" + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana" + }, + "application/lost+xml": { + "source": "iana", + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana" + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana" + }, + "application/mathml-presentation+xml": { + "source": "iana" + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana" + }, + "application/mbms-deregister+xml": { + "source": "iana" + }, + "application/mbms-envelope+xml": { + "source": "iana" + }, + "application/mbms-msk+xml": { + "source": "iana" + }, + "application/mbms-msk-response+xml": { + "source": "iana" + }, + "application/mbms-protection-description+xml": { + "source": "iana" + }, + "application/mbms-reception-report+xml": { + "source": "iana" + }, + "application/mbms-register+xml": { + "source": "iana" + }, + "application/mbms-register-response+xml": { + "source": "iana" + }, + "application/mbms-schedule+xml": { + "source": "iana" + }, + "application/mbms-user-service-description+xml": { + "source": "iana" + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana" + }, + "application/media_control+xml": { + "source": "iana" + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mods+xml": { + "source": "iana", + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana" + }, + "application/mrb-publish+xml": { + "source": "iana" + }, + "application/msc-ivr+xml": { + "source": "iana" + }, + "application/msc-mixer+xml": { + "source": "iana" + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "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", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana" + }, + "application/parityfec": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana" + }, + "application/pidf-diff+xml": { + "source": "iana" + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana" + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/provenance+xml": { + "source": "iana" + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana" + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana" + }, + "application/pskc+xml": { + "source": "iana", + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf"] + }, + "application/reginfo+xml": { + "source": "iana", + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana" + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana" + }, + "application/rls-services+xml": { + "source": "iana", + "extensions": ["rs"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana" + }, + "application/samlmetadata+xml": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana" + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/sep+xml": { + "source": "iana" + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana" + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana" + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "extensions": ["ssml"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/ttml+xml": { + "source": "iana" + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana" + }, + "application/urc-ressheet+xml": { + "source": "iana" + }, + "application/urc-targetdesc+xml": { + "source": "iana" + }, + "application/urc-uisocketdesc+xml": { + "source": "iana" + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana" + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana" + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana" + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana" + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana" + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana" + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana" + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "extensions": ["mpkg"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avistar+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana" + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "extensions": ["cdxml"] + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana" + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana" + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana" + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume-movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana" + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana" + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana" + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana" + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana" + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana" + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana" + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana" + }, + "application/vnd.etsi.cug+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana" + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana" + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana" + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana" + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana" + }, + "application/vnd.etsi.sci+xml": { + "source": "iana" + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana" + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana" + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana" + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana" + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana" + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana" + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana" + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana" + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana" + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana" + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+xml": { + "source": "iana", + "extensions": ["lasxml"] + }, + "application/vnd.liberty-request+xml": { + "source": "iana" + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana" + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana" + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana" + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana" + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache" + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana" + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana" + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana" + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana" + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana" + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana" + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana" + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana" + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana" + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana" + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana" + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana" + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana" + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana" + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana" + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana" + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana" + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana" + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana" + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana" + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana" + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana" + }, + "application/vnd.omads-email+xml": { + "source": "iana" + }, + "application/vnd.omads-file+xml": { + "source": "iana" + }, + "application/vnd.omads-folder+xml": { + "source": "iana" + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana" + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "apache", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "apache", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml-template": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "apache", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana" + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana" + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana" + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos+xml": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "apache" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana" + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana" + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana" + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana" + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana" + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana" + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana" + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana" + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana" + }, + "application/vnd.wv.ssp+xml": { + "source": "iana" + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana" + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "extensions": ["vxml"] + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/watcherinfo+xml": { + "source": "iana" + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-otf": { + "source": "apache", + "compressible": true, + "extensions": ["otf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-ttf": { + "source": "apache", + "compressible": true, + "extensions": ["ttf","ttc"] + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "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, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "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, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana" + }, + "application/xaml+xml": { + "source": "apache", + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana" + }, + "application/xcap-caps+xml": { + "source": "iana" + }, + "application/xcap-diff+xml": { + "source": "iana", + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana" + }, + "application/xcap-error+xml": { + "source": "iana" + }, + "application/xcap-ns+xml": { + "source": "iana" + }, + "application/xcon-conference-info+xml": { + "source": "iana" + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana" + }, + "application/xenc+xml": { + "source": "iana", + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache" + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana" + }, + "application/xmpp+xml": { + "source": "iana" + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yin+xml": { + "source": "iana", + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana" + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4a","m4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/opentype": { + "compressible": true, + "extensions": ["otf"] + }, + "image/bmp": { + "source": "apache", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/fits": { + "source": "iana" + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jp2": { + "source": "iana" + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana" + }, + "image/jpx": { + "source": "iana" + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana" + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana" + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tiff","tif"] + }, + "image/tiff-fx": { + "source": "iana" + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana" + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana" + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana" + }, + "image/vnd.valve.source.texture": { + "source": "iana" + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana" + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "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"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana" + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana" + }, + "message/global-delivery-status": { + "source": "iana" + }, + "message/global-disposition-notification": { + "source": "iana" + }, + "message/global-headers": { + "source": "iana" + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana" + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana" + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/hjson": { + "extensions": ["hjson"] + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana" + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["markdown","md","mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "apache" + }, + "video/3gpp": { + "source": "apache", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "apache" + }, + "video/3gpp2": { + "source": "apache", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "apache" + }, + "video/bt656": { + "source": "apache" + }, + "video/celb": { + "source": "apache" + }, + "video/dv": { + "source": "apache" + }, + "video/h261": { + "source": "apache", + "extensions": ["h261"] + }, + "video/h263": { + "source": "apache", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "apache" + }, + "video/h263-2000": { + "source": "apache" + }, + "video/h264": { + "source": "apache", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "apache" + }, + "video/h264-svc": { + "source": "apache" + }, + "video/jpeg": { + "source": "apache", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "apache" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "apache", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "apache" + }, + "video/mp2p": { + "source": "apache" + }, + "video/mp2t": { + "source": "apache", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "apache", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "apache" + }, + "video/mpeg": { + "source": "apache", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "apache" + }, + "video/mpv": { + "source": "apache" + }, + "video/nv": { + "source": "apache" + }, + "video/ogg": { + "source": "apache", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "apache" + }, + "video/pointer": { + "source": "apache" + }, + "video/quicktime": { + "source": "apache", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raw": { + "source": "apache" + }, + "video/rtp-enc-aescm128": { + "source": "apache" + }, + "video/rtx": { + "source": "apache" + }, + "video/smpte292m": { + "source": "apache" + }, + "video/ulpfec": { + "source": "apache" + }, + "video/vc1": { + "source": "apache" + }, + "video/vnd.cctv": { + "source": "apache" + }, + "video/vnd.dece.hd": { + "source": "apache", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "apache", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "apache" + }, + "video/vnd.dece.pd": { + "source": "apache", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "apache", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "apache", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "apache" + }, + "video/vnd.directv.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "apache" + }, + "video/vnd.dvb.file": { + "source": "apache", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "apache", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "apache" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "apache" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "apache" + }, + "video/vnd.motorola.video": { + "source": "apache" + }, + "video/vnd.motorola.videop": { + "source": "apache" + }, + "video/vnd.mpegurl": { + "source": "apache", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "apache", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "apache" + }, + "video/vnd.nokia.videovoip": { + "source": "apache" + }, + "video/vnd.objectvideo": { + "source": "apache" + }, + "video/vnd.sealed.mpeg1": { + "source": "apache" + }, + "video/vnd.sealed.mpeg4": { + "source": "apache" + }, + "video/vnd.sealed.swf": { + "source": "apache" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "apache" + }, + "video/vnd.uvvu.mp4": { + "source": "apache", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "apache", + "extensions": ["viv"] + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js new file mode 100644 index 0000000..551031f --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json new file mode 100644 index 0000000..e6c9732 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/package.json @@ -0,0 +1,94 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.21.0", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "devDependencies": { + "bluebird": "3.1.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "1.0.1", + "gnode": "0.1.1", + "istanbul": "0.4.1", + "mocha": "1.21.5", + "raw-body": "2.1.5", + "stream-to-array": "2.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "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": "9ab92f0a912a602408a64db5741dfef6f82c597f", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "homepage": "https://github.com/jshttp/mime-db", + "_id": "mime-db@1.21.0", + "_shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "_from": "mime-db@>=1.21.0 <1.22.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" + } + ], + "dist": { + "shasum": "9b5239e3353cf6eb015a00d890261027c36d4bac", + "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.21.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json new file mode 100644 index 0000000..d1a5ffa --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json @@ -0,0 +1,84 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.9", + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "dependencies": { + "mime-db": "~1.21.0" + }, + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "~1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec test/test.js", + "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": "329f1c77e1a77c8fac59b15038e3808e9e314d96", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "homepage": "https://github.com/jshttp/mime-types", + "_id": "mime-types@2.1.9", + "_shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "_from": "mime-types@>=2.1.6 <2.2.0", + "_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" + } + ], + "dist": { + "shasum": "dfb396764b5fdf75be34b1f4104bc3687fb635f8", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.9.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/type-is/package.json b/5-3/node_modules/express/node_modules/type-is/package.json new file mode 100644 index 0000000..cae6789 --- /dev/null +++ b/5-3/node_modules/express/node_modules/type-is/package.json @@ -0,0 +1,81 @@ +{ + "name": "type-is", + "description": "Infer the content-type of a request.", + "version": "1.6.11", + "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": "git+https://github.com/jshttp/type-is.git" + }, + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.9" + }, + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "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/" + }, + "keywords": [ + "content", + "type", + "checking" + ], + "gitHead": "8e60e3e78aef84928e0e6c09da950f6950adcdd2", + "bugs": { + "url": "https://github.com/jshttp/type-is/issues" + }, + "homepage": "https://github.com/jshttp/type-is", + "_id": "type-is@1.6.11", + "_shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "_from": "type-is@>=1.6.10 <1.7.0", + "_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": "ritch", + "email": "skawful@gmail.com" + } + ], + "dist": { + "shasum": "42ecde7970f2363738b986c0351efba5aa531648", + "tarball": "http://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.11.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/node_modules/utils-merge/.travis.yml b/5-3/node_modules/express/node_modules/utils-merge/.travis.yml new file mode 100644 index 0000000..af92b02 --- /dev/null +++ b/5-3/node_modules/express/node_modules/utils-merge/.travis.yml @@ -0,0 +1,6 @@ +language: "node_js" +node_js: + - "0.4" + - "0.6" + - "0.8" + - "0.10" diff --git a/5-3/node_modules/express/node_modules/utils-merge/LICENSE b/5-3/node_modules/express/node_modules/utils-merge/LICENSE new file mode 100644 index 0000000..e33bd10 --- /dev/null +++ b/5-3/node_modules/express/node_modules/utils-merge/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2013 Jared Hanson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/express/node_modules/utils-merge/README.md b/5-3/node_modules/express/node_modules/utils-merge/README.md new file mode 100644 index 0000000..2f94e9b --- /dev/null +++ b/5-3/node_modules/express/node_modules/utils-merge/README.md @@ -0,0 +1,34 @@ +# utils-merge + +Merges the properties from a source object into a destination object. + +## Install + + $ npm install utils-merge + +## Usage + +```javascript +var a = { foo: 'bar' } + , b = { bar: 'baz' }; + +merge(a, b); +// => { foo: 'bar', bar: 'baz' } +``` + +## Tests + + $ npm install + $ npm test + +[![Build Status](https://secure.travis-ci.org/jaredhanson/utils-merge.png)](http://travis-ci.org/jaredhanson/utils-merge) + +## Credits + + - [Jared Hanson](http://github.com/jaredhanson) + +## License + +[The MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2013 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> diff --git a/5-3/node_modules/express/node_modules/utils-merge/index.js b/5-3/node_modules/express/node_modules/utils-merge/index.js new file mode 100644 index 0000000..4265c69 --- /dev/null +++ b/5-3/node_modules/express/node_modules/utils-merge/index.js @@ -0,0 +1,23 @@ +/** + * Merge object b with object a. + * + * var a = { foo: 'bar' } + * , b = { bar: 'baz' }; + * + * merge(a, b); + * // => { foo: 'bar', bar: 'baz' } + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api public + */ + +exports = module.exports = function(a, b){ + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; +}; diff --git a/5-3/node_modules/express/node_modules/utils-merge/package.json b/5-3/node_modules/express/node_modules/utils-merge/package.json new file mode 100644 index 0000000..2f9660e --- /dev/null +++ b/5-3/node_modules/express/node_modules/utils-merge/package.json @@ -0,0 +1,60 @@ +{ + "name": "utils-merge", + "version": "1.0.0", + "description": "merge() utility function", + "keywords": [ + "util" + ], + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/utils-merge.git" + }, + "bugs": { + "url": "http://github.com/jaredhanson/utils-merge/issues" + }, + "author": { + "name": "Jared Hanson", + "email": "jaredhanson@gmail.com", + "url": "http://www.jaredhanson.net/" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://www.opensource.org/licenses/MIT" + } + ], + "main": "./index", + "dependencies": {}, + "devDependencies": { + "mocha": "1.x.x", + "chai": "1.x.x" + }, + "scripts": { + "test": "mocha --reporter spec --require test/bootstrap/node test/*.test.js" + }, + "engines": { + "node": ">= 0.4.0" + }, + "_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#readme" +} diff --git a/5-3/node_modules/express/node_modules/vary/HISTORY.md b/5-3/node_modules/express/node_modules/vary/HISTORY.md new file mode 100644 index 0000000..cddbcd4 --- /dev/null +++ b/5-3/node_modules/express/node_modules/vary/HISTORY.md @@ -0,0 +1,23 @@ +1.0.1 / 2015-07-08 +================== + + * Fix setting empty header from empty `field` + * perf: enable strict mode + * perf: remove argument reassignments + +1.0.0 / 2014-08-10 +================== + + * Accept valid `Vary` header string as `field` + * Add `vary.append` for low-level string manipulation + * Move to `jshttp` orgainzation + +0.1.0 / 2014-06-05 +================== + + * Support array of fields to set + +0.0.0 / 2014-06-04 +================== + + * Initial release diff --git a/5-3/node_modules/express/node_modules/vary/LICENSE b/5-3/node_modules/express/node_modules/vary/LICENSE new file mode 100644 index 0000000..142ede3 --- /dev/null +++ b/5-3/node_modules/express/node_modules/vary/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +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: + +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/5-3/node_modules/express/node_modules/vary/README.md b/5-3/node_modules/express/node_modules/vary/README.md new file mode 100644 index 0000000..5966542 --- /dev/null +++ b/5-3/node_modules/express/node_modules/vary/README.md @@ -0,0 +1,91 @@ +# vary + +[![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] + +Manipulate the HTTP Vary header + +## Installation + +```sh +$ npm install vary +``` + +## API + +```js +var vary = require('vary') +``` + +### vary(res, field) + +Adds the given header `field` to the `Vary` response header of `res`. +This can be a string of a single field, a string of a valid `Vary` +header, or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. + +```js +// Append "Origin" to the Vary header of the response +vary(res, 'Origin') +``` + +### vary.append(header, field) + +Adds the given header `field` to the `Vary` response header string `header`. +This can be a string of a single field, a string of a valid `Vary` header, +or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. The new header string is returned. + +```js +// Get header string appending "Origin" to "Accept, User-Agent" +vary.append('Accept, User-Agent', 'Origin') +``` + +## Examples + +### Updating the Vary header when content is based on it + +```js +var http = require('http') +var vary = require('vary') + +http.createServer(function onRequest(req, res) { + // about to user-agent sniff + vary(res, 'User-Agent') + + var ua = req.headers['user-agent'] || '' + var isMobile = /mobi|android|touch|mini/i.test(ua) + + // serve site, depending on isMobile + res.setHeader('Content-Type', 'text/html') + res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') +}) +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/vary.svg +[npm-url]: https://npmjs.org/package/vary +[node-version-image]: https://img.shields.io/node/v/vary.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg +[travis-url]: https://travis-ci.org/jshttp/vary +[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/vary +[downloads-image]: https://img.shields.io/npm/dm/vary.svg +[downloads-url]: https://npmjs.org/package/vary diff --git a/5-3/node_modules/express/node_modules/vary/index.js b/5-3/node_modules/express/node_modules/vary/index.js new file mode 100644 index 0000000..e818dbb --- /dev/null +++ b/5-3/node_modules/express/node_modules/vary/index.js @@ -0,0 +1,117 @@ +/*! + * vary + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + */ + +module.exports = vary; +module.exports.append = append; + +/** + * Variables. + */ + +var separators = /[\(\)<>@,;:\\"\/\[\]\?=\{\}\u0020\u0009]/; + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @api public + */ + +function append(header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required'); + } + + if (!field) { + throw new TypeError('field argument is required'); + } + + // get fields array + var fields = !Array.isArray(field) + ? parse(String(field)) + : field; + + // assert on invalid fields + for (var i = 0; i < fields.length; i++) { + if (separators.test(fields[i])) { + throw new TypeError('field argument contains an invalid header'); + } + } + + // existing, unspecified vary + if (header === '*') { + return header; + } + + // enumerate current values + var val = header; + var vals = parse(header.toLowerCase()); + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*'; + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase(); + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld); + val = val + ? val + ', ' + fields[i] + : fields[i]; + } + } + + return val; +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @api private + */ + +function parse(header) { + return header.trim().split(/ *, */); +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @api public + */ + +function vary(res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required'); + } + + // get existing header + var val = res.getHeader('Vary') || '' + var header = Array.isArray(val) + ? val.join(', ') + : String(val); + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val); + } +} diff --git a/5-3/node_modules/express/node_modules/vary/package.json b/5-3/node_modules/express/node_modules/vary/package.json new file mode 100644 index 0000000..8e1bee4 --- /dev/null +++ b/5-3/node_modules/express/node_modules/vary/package.json @@ -0,0 +1,72 @@ +{ + "name": "vary", + "description": "Manipulate the HTTP Vary header", + "version": "1.0.1", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "license": "MIT", + "keywords": [ + "http", + "res", + "vary" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/vary.git" + }, + "devDependencies": { + "istanbul": "0.3.17", + "mocha": "2.2.5", + "supertest": "1.0.1" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "gitHead": "650282ff8e614731837040a23e10f51c20728392", + "bugs": { + "url": "https://github.com/jshttp/vary/issues" + }, + "homepage": "https://github.com/jshttp/vary", + "_id": "vary@1.0.1", + "_shasum": "99e4981566a286118dfb2b817357df7993376d10", + "_from": "vary@>=1.0.1 <1.1.0", + "_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": "fishrock123", + "email": "fishrock123@rocketmail.com" + } + ], + "dist": { + "shasum": "99e4981566a286118dfb2b817357df7993376d10", + "tarball": "http://registry.npmjs.org/vary/-/vary-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/vary/-/vary-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/express/package.json b/5-3/node_modules/express/package.json new file mode 100644 index 0000000..66d0e95 --- /dev/null +++ b/5-3/node_modules/express/package.json @@ -0,0 +1,143 @@ +{ + "name": "express", + "description": "Fast, unopinionated, minimalist web framework", + "version": "4.13.4", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "Ciaran Jessup", + "email": "ciaranj@gmail.com" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Guillermo Rauch", + "email": "rauchg@gmail.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com" + }, + { + "name": "Roman Shtylman", + "email": "shtylman+expressjs@gmail.com" + }, + { + "name": "Young Jae Sim", + "email": "hanul@hanul.me" + } + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/express.git" + }, + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "rest", + "restful", + "router", + "app", + "api" + ], + "dependencies": { + "accepts": "~1.2.12", + "array-flatten": "1.1.1", + "content-disposition": "0.5.1", + "content-type": "~1.0.1", + "cookie": "0.1.5", + "cookie-signature": "1.0.6", + "debug": "~2.2.0", + "depd": "~1.1.0", + "escape-html": "~1.0.3", + "etag": "~1.7.0", + "finalhandler": "0.4.1", + "fresh": "0.3.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.1", + "path-to-regexp": "0.1.7", + "proxy-addr": "~1.0.10", + "qs": "4.0.0", + "range-parser": "~1.0.3", + "send": "0.13.1", + "serve-static": "~1.10.2", + "type-is": "~1.6.6", + "utils-merge": "1.0.0", + "vary": "~1.0.1" + }, + "devDependencies": { + "after": "0.8.1", + "ejs": "2.3.4", + "istanbul": "0.4.2", + "marked": "0.3.5", + "mocha": "2.3.4", + "should": "7.1.1", + "supertest": "1.1.0", + "body-parser": "~1.14.2", + "connect-redis": "~2.4.1", + "cookie-parser": "~1.4.1", + "cookie-session": "~1.2.0", + "express-session": "~1.13.0", + "jade": "~1.11.0", + "method-override": "~2.3.5", + "morgan": "~1.6.1", + "multiparty": "~4.1.2", + "vhost": "~3.0.1" + }, + "engines": { + "node": ">= 0.10.0" + }, + "files": [ + "LICENSE", + "History.md", + "Readme.md", + "index.js", + "lib/" + ], + "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/" + }, + "gitHead": "193bed2649c55c1fd362e46cd4702c773f3e7434", + "bugs": { + "url": "https://github.com/expressjs/express/issues" + }, + "homepage": "https://github.com/expressjs/express", + "_id": "express@4.13.4", + "_shasum": "3c0b76f3c77590c8345739061ec0bd3ba067ec24", + "_from": "express@*", + "_npmVersion": "1.4.28", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "maintainers": [ + { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + } + ], + "dist": { + "shasum": "3c0b76f3c77590c8345739061ec0bd3ba067ec24", + "tarball": "http://registry.npmjs.org/express/-/express-4.13.4.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/express/-/express-4.13.4.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/.eslintignore b/5-3/node_modules/mongoose/.eslintignore new file mode 100644 index 0000000..235bdcd --- /dev/null +++ b/5-3/node_modules/mongoose/.eslintignore @@ -0,0 +1,3 @@ +docs/ +bin/ +test/triage/ diff --git a/5-3/node_modules/mongoose/.eslintrc.yml b/5-3/node_modules/mongoose/.eslintrc.yml new file mode 100644 index 0000000..c16c336 --- /dev/null +++ b/5-3/node_modules/mongoose/.eslintrc.yml @@ -0,0 +1,31 @@ +extends: 'eslint:recommended' + +env: + node: true + mocha: true + +rules: + comma-style: 2 + consistent-this: + - 2 + - _this + indent: + - 2 + - 2 + - SwitchCase: 1 + VariableDeclarator: 2 + keyword-spacing: 2 + no-console: 0 + no-multi-spaces: 2 + no-spaced-func: 2 + no-trailing-spaces: 2 + quotes: + - 2 + - single + semi: 2 + space-before-blocks: 2 + space-before-function-paren: + - 2 + - never + space-infix-ops: 2 + space-unary-ops: 2 diff --git a/5-3/node_modules/mongoose/.npmignore b/5-3/node_modules/mongoose/.npmignore new file mode 100644 index 0000000..377d63f --- /dev/null +++ b/5-3/node_modules/mongoose/.npmignore @@ -0,0 +1,16 @@ +lib-cov +**.swp +*.sw* +*.orig +.DS_Store +node_modules/ +benchmarks/ +docs/ +test/ +Makefile +CNAME +index.html +index.jade +bin/ +karma.*.js +format_deps.js diff --git a/5-3/node_modules/mongoose/.travis.yml b/5-3/node_modules/mongoose/.travis.yml new file mode 100644 index 0000000..05a3e8d --- /dev/null +++ b/5-3/node_modules/mongoose/.travis.yml @@ -0,0 +1,13 @@ +language: node_js +sudo: false +node_js: + - "5" + - "4" + - "0.12" + - "0.10" + - "iojs" +before_script: + - wget http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.6.11.tgz + - tar -zxvf mongodb-linux-x86_64-2.6.11.tgz + - mkdir -p ./data/db + - ./mongodb-linux-x86_64-2.6.11/bin/mongod --fork --nopreallocj --dbpath ./data/db --syslog --port 27017 diff --git a/5-3/node_modules/mongoose/CONTRIBUTING.md b/5-3/node_modules/mongoose/CONTRIBUTING.md new file mode 100644 index 0000000..02f24b7 --- /dev/null +++ b/5-3/node_modules/mongoose/CONTRIBUTING.md @@ -0,0 +1,51 @@ +## Contributing to Mongoose + +If you have a question about Mongoose (not a bug report) please post it to either [StackOverflow](http://stackoverflow.com/questions/tagged/mongoose), our [Google Group](http://groups.google.com/group/mongoose-orm), or on the #mongoosejs irc channel on freenode. + +### Reporting bugs + +- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new). + - Please describe the issue you are experiencing, along with any associated stack trace. + - Please post code that reproduces the issue, the version of mongoose, node version, and mongodb version. + - _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_. + +### Requesting new features + +- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new). +- Please describe a use case for it +- it would be ideal to include test cases as well + +### Fixing bugs / Adding features + +- Before starting to write code, look for existing [issues](https://github.com/learnboost/mongoose/issues). That way you avoid working on something that might not be of interest or that has been addressed already in a different branch. You can create a new issue [here](https://github.com/learnboost/mongoose/issues/new). + - _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_. +- Fork the [repo](https://github.com/Automattic/mongoose) _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 + - inline documentation for new methods, class members, etc. + - 1 space between conditionals/functions, and their parenthesis and curly braces + - `if (..) {` + - `for (..) {` + - `while (..) {` + - `function(err) {` +- Write tests and make sure they pass (tests are in the [test](https://github.com/Automattic/mongoose/tree/master/test) directory). + +### Running the tests +- Open a terminal and navigate to the root of the project +- execute `npm install` to install the necessary dependencies +- execute `npm test` to run the tests (we're using [mocha](http://mochajs.org/)) + - or to execute a single test `npm test -- -g 'some regexp that matches the test description'` + - any mocha flags can be specified with `-- ` + +### Documentation + +To contribute to the [API documentation](http://mongoosejs.com/docs/api.html) just make your changes to the inline documentation of the appropriate [source code](https://github.com/Automattic/mongoose/tree/master/lib) 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. + +To contribute to the [guide](http://mongoosejs.com/docs/guide.html) or [quick start](http://mongoosejs.com/docs/index.html) docs, make your changes to the appropriate `.jade` files in the [docs](https://github.com/Automattic/mongoose/tree/master/docs) directory of the master branch and submit a pull request. Again, the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button might work for you here. + +If you'd like to preview your documentation changes, first commit your changes to your local master branch, then execute `make docs` from the project root, which switches to the gh-pages branch, merges from the master branch and builds all the static pages for you. Now execute `node static.js` from the project root which will launch a local webserver where you can browse the documentation site locally. If all looks good, submit a [pull request](https://help.github.com/articles/using-pull-requests/) to the master branch with your changes. + +### Plugins website + +The [plugins](http://plugins.mongoosejs.com/) site is also an [open source project](https://github.com/aheckmann/mongooseplugins) that you can get involved with. Feel free to fork and improve it as well! diff --git a/5-3/node_modules/mongoose/History.md b/5-3/node_modules/mongoose/History.md new file mode 100644 index 0000000..81e18b9 --- /dev/null +++ b/5-3/node_modules/mongoose/History.md @@ -0,0 +1,2887 @@ +4.4.3 / 2016-02-09 +================== + * fix: upgrade to mongodb 2.1.6 to remove kerberos log output #3861 #3860 [cartuchogl](https://github.com/cartuchogl) + * fix: require('mongoose') is no longer a pseudo-promise #3856 + * fix(query): update casting for single nested docs #3820 + * fix(populate): deep populating multiple paths with same options #3808 + * docs(middleware): clarify save/validate hook order #1149 + +4.4.2 / 2016-02-05 +================== + * fix(aggregate): handle calling .cursor() with no options #3855 + * fix: upgrade mongodb driver to 2.1.5 for GridFS memory leak fix #3854 + * docs: fix schematype.html conflict #3853 #3850 #3843 + * fix(model): bluebird unhandled rejection with ensureIndexes() on init #3837 + * docs: autoIndex option for createConnection #3805 + +4.4.1 / 2016-02-03 +================== + * fix: linting broke some cases where we use `== null` as shorthand #3852 + * docs: fix up schematype.html conflict #3848 #3843 [mynameiscoffey](https://github.com/mynameiscoffey) + * fix: backwards breaking change with `.connect()` return value #3847 + * docs: downgrade dox and highlight.js to fix docs build #3845 + * docs: clean up typo #3842 [Flash-](https://github.com/Flash-) + * fix(document): storeShard handles undefined values #3841 + * chore: more linting #3838 [TrejGun](https://github.com/TrejGun) + * fix(schema): handle `text: true` as a way to declare a text index #3824 + +4.4.0 / 2016-02-02 +================== + * docs: fix expireAfterSeconds index option name #3831 [Flash-](https://github.com/Flash-) + * chore: run lint after test #3829 [ChristianMurphy](https://github.com/ChristianMurphy) + * chore: use power-assert instead of assert #3828 [TrejGun](https://github.com/TrejGun) + * chore: stricter lint #3827 [TrejGun](https://github.com/TrejGun) + * feat(types): casting moment to date #3813 [TrejGun](https://github.com/TrejGun) + * chore: comma-last lint for test folder #3810 [ChristianMurphy](https://github.com/ChristianMurphy) + * fix: upgrade async mpath, mpromise, muri, and sliced #3801 [TrejGun](https://github.com/TrejGun) + * fix(query): geo queries now return proper ES2015 promises #3800 [TrejGun](https://github.com/TrejGun) + * perf(types): use `Object.defineProperties()` for array #3799 [TrejGun](https://github.com/TrejGun) + * fix(model): mapReduce, ensureIndexes, remove, and save properly return ES2015 promises #3795 #3628 #3595 [TrejGun](https://github.com/TrejGun) + * docs: fixed dates in History.md #3791 [Jokero](https://github.com/Jokero) + * feat: connect, open, openSet, and disconnect return ES2015 promises #3790 #3622 [TrejGun](https://github.com/TrejGun) + * feat: custom type for int32 via mongoose-int32 npm package #3652 #3102 + * feat: basic custom schema type API #995 + * feat(model): `insertMany()` for more performant bulk inserts #723 + +4.3.7 / 2016-01-23 +================== + * docs: grammar fix in timestamps docs #3786 [zclancy](https://github.com/zclancy) + * fix(document): setting nested populated docs #3783 [slamuu](https://github.com/slamuu) + * fix(document): don't call post save hooks twice for pushed docs #3780 + * fix(model): handle `_id=0` correctly #3776 + * docs(middleware): async post hooks #3770 + * docs: remove confusing sentence #3765 [marcusmellis89](https://github.com/marcusmellis89) + +3.8.39 / 2016-01-15 +=================== + * fixed; casting a number to a buffer #3764 + * fixed; enumerating virtual property with nested objects #3743 [kusold](https://github.com/kusold) + +4.3.6 / 2016-01-15 +================== + * fix(types): casting a number to a buffer #3764 + * fix: add "listener" to reserved keywords #3759 + * chore: upgrade uglify #3757 [ChristianMurphy](https://github.com/ChristianMurphy) + * fix: broken execPopulate() in 4.3.5 #3755 #3753 + * fix: ability to remove() a single embedded doc #3754 + * style: comma-last in test folder #3751 [ChristianMurphy](https://github.com/ChristianMurphy) + * docs: clarify versionKey option #3747 + * fix: improve colorization for arrays #3744 [TrejGun](https://github.com/TrejGun) + * fix: webpack build #3713 + +4.3.5 / 2016-01-09 +================== + * fix(query): throw when 4th parameter to update not a function #3741 [kasselTrankos](https://github.com/kasselTrankos) + * fix(document): separate error type for setting an object to a primitive #3735 + * fix(populate): Model.populate returns ES6 promise #3734 + * fix(drivers): re-register event handlers after manual reconnect #3729 + * docs: broken links #3727 + * fix(validation): update validators run array validation #3724 + * docs: clarify the need to use markModified with in-place date ops #3722 + * fix(document): mark correct path as populated when manually populating array #3721 + * fix(aggregate): support for array pipeline argument to append #3718 [dbkup](https://github.com/dbkup) + * docs: clarify `.connect()` callback #3705 + * fix(schema): properly validate nested single nested docs #3702 + * fix(types): handle setting documentarray of wrong type #3701 + * docs: broken links #3700 + * fix(drivers): debug output properly displays '0' #3689 + +3.8.38 / 2016-01-07 +=================== + * fixed; aggregate.append an array #3730 [dbkup](https://github.com/dbkup) + +4.3.4 / 2015-12-23 +================== + * fix: upgrade mongodb driver to 2.1.2 for repl set error #3712 [sansmischevia](https://github.com/sansmischevia) + * docs: validation docs typo #3709 [ivanmaeder](https://github.com/ivanmaeder) + * style: remove unused variables #3708 [ChristianMurphy](https://github.com/ChristianMurphy) + * fix(schema): duck-typing for schemas #3703 [mgcrea](https://github.com/mgcrea) + * docs: connection sample code issue #3697 + * fix(schema): duck-typing for schemas #3693 [mgcrea](https://github.com/mgcrea) + * docs: clarify id schema option #3638 + +4.3.3 / 2015-12-18 +================== + * fix(connection): properly support 'replSet' as well as 'replset' #3688 [taxilian](https://github.com/taxilian) + * fix(document): single nested doc pre hooks called before nested doc array #3687 [aliatsis](https://github.com/aliatsis) + +4.3.2 / 2015-12-17 +================== + * fix(document): .set() into single nested schemas #3686 + * fix(connection): support 'replSet' as well as 'replset' option #3685 + * fix(document): bluebird unhandled rejection when validating doc arrays #3681 + * fix(document): hooks for doc arrays in single nested schemas #3680 + * fix(document): post hooks for single nested schemas #3679 + * fix: remove unused npm module #3674 [sybarite](https://github.com/sybarite) + * fix(model): don't swallow exceptions in nested doc save callback #3671 + * docs: update keepAlive info #3667 [ChrisZieba](https://github.com/ChrisZieba) + * fix(document): strict 'throw' throws a specific mongoose error #3662 + * fix: flakey test #3332 + * fix(query): more robust check for RegExp #2969 + +4.3.1 / 2015-12-11 +================== + * feat(aggregate): `.sample()` helper #3665 + * fix(query): bitwise query operators with buffers #3663 + * docs(migration): clarify `new` option and findByIdAndUpdate #3661 + +4.3.0 / 2015-12-09 +================== + * feat(query): support for mongodb 3.2 bitwise query operators #3660 + * style: use comma-last style consistently #3657 [ChristianMurphy](https://github.com/ChristianMurphy) + * feat: upgrade mongodb driver to 2.1.0 for full MongoDB 3.2 support #3656 + * feat(aggregate): `.lookup()` helper #3532 + +4.2.10 / 2015-12-08 +=================== + * fixed; upgraded marked #3653 [ChristianMurphy](https://github.com/ChristianMurphy) + * docs; cross-db populate #3648 + * docs; update mocha URL #3646 [ojhaujjwal](https://github.com/ojhaujjwal) + * fixed; call close callback asynchronously #3645 + * docs; virtuals.html issue #3644 [Psarna94](https://github.com/Psarna94) + * fixed; single embedded doc casting on init #3642 + * docs; validation docs improvements #3640 + +4.2.9 / 2015-12-02 +================== + * docs; defaults docs #3625 + * fix; nested numeric keys causing an embedded document crash #3623 + * fix; apply path getters before virtual getters #3618 + * fix; casting for arrays in single nested schemas #3616 + +4.2.8 / 2015-11-25 +================== + * docs; clean up README links #3612 [ReadmeCritic](https://github.com/ReadmeCritic) + * fix; ESLint improvements #3605 [ChristianMurphy](https://github.com/ChristianMurphy) + * fix; assigning single nested subdocs #3601 + * docs; describe custom logging functions in `mongoose.set()` docs #3557 + +4.2.7 / 2015-11-20 +================== + * fixed; readPreference connection string option #3600 + * fixed; pulling from manually populated arrays #3598 #3579 + * docs; FAQ about OverwriteModelError #3597 [stcruy](https://github.com/stcruy) + * fixed; setting single embedded schemas to null #3596 + * fixed; indexes for single embedded schemas #3594 + * docs; clarify projection for `findOne()` #3593 [gunar](https://github.com/gunar) + * fixed; .ownerDocument() method on single embedded schemas #3589 + * fixed; properly throw casterror for query on single embedded schema #3580 + * upgraded; mongodb driver -> 2.0.49 for reconnect issue fix #3481 + +4.2.6 / 2015-11-16 +================== + * fixed; ability to manually populate an array #3575 + * docs; clarify `isAsync` parameter to hooks #3573 + * fixed; use captureStackTrace if possible instead #3571 + * fixed; crash with buffer and update validators #3565 [johnpeb](https://github.com/johnpeb) + * fixed; update casting with operators overwrite: true #3564 + * fixed; validation with single embedded docs #3562 + * fixed; inline docs inherit parents $type key #3560 + * docs; bad grammar in populate docs #3559 [amaurymedeiros](https://github.com/amaurymedeiros) + * fixed; properly handle populate option for find() #2321 + +3.8.37 / 2015-11-16 +=================== + * fixed; use retainKeyOrder for cloning update op #3572 + +4.2.5 / 2015-11-09 +================== + * fixed; handle setting fields in pre update hooks with exec #3549 + * upgraded; ESLint #3547 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; bluebird unhandled rejections with cast errors and .exec #3543 + * fixed; min/max validators handling undefined #3539 + * fixed; standalone mongos connections #3537 + * fixed; call `.toObject()` when setting a single nested doc #3535 + * fixed; single nested docs now have methods #3534 + * fixed; single nested docs with .create() #3533 #3521 [tusbar](https://github.com/tusbar) + * docs; deep populate docs #3528 + * fixed; deep populate schema ref handling #3507 + * upgraded; mongodb driver -> 2.0.48 for sort overflow issue #3493 + * docs; clarify default ids for discriminators #3482 + * fixed; properly support .update(doc) #3221 + +4.2.4 / 2015-11-02 +================== + * fixed; upgraded `ms` package for security vulnerability #3254 [fhemberger](https://github.com/fhemberger) + * fixed; ESlint rules #3517 [ChristianMurphy](https://github.com/ChristianMurphy) + * docs; typo in aggregation docs #3513 [rafakato](https://github.com/rafakato) + * fixed; add `dontThrowCastError` option to .update() for promises #3512 + * fixed; don't double-cast buffers in node 4.x #3510 #3496 + * fixed; population with single embedded schemas #3501 + * fixed; pre('set') hooks work properly #3479 + * docs; promises guide #3441 + +4.2.3 / 2015-10-26 +================== + * docs; remove unreferenced function in middleware.jade #3506 + * fixed; handling auth with no username/password #3500 #3498 #3484 [mleanos](https://github.com/mleanos) + * fixed; more ESlint rules #3491 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; swallowing exceptions in save callback #3478 + * docs; fixed broken links in subdocs guide #3477 + * fixed; casting booleans to numbers #3475 + * fixed; report CastError for subdoc arrays in findOneAndUpdate #3468 + * fixed; geoNear returns ES6 promise #3458 + +4.2.2 / 2015-10-22 +================== + * fixed; go back to old pluralization code #3490 + +4.2.1 / 2015-10-22 +================== + * fixed; pluralization issues #3492 [ChristianMurphy](https://github.com/ChristianMurphy) + +4.2.0 / 2015-10-22 +================== + * added; support for skipVersioning for document arrays #3467 [chazmo03](https://github.com/chazmo03) + * added; ability to customize schema 'type' key #3459 #3245 + * fixed; writeConcern for index builds #3455 + * added; emit event when individual index build starts #3440 [objectiveSee](https://github.com/objectiveSee) + * added; 'context' option for update validators #3430 + * refactor; pluralization now in separate pluralize-mongoose npm module #3415 [ChristianMurphy](https://github.com/ChristianMurphy) + * added; customizable error validation messages #3406 [geronime](https://github.com/geronime) + * added; support for passing 'minimize' option to update #3381 + * added; ability to customize debug logging format #3261 + * added; baseModelName property for discriminator models #3202 + * added; 'emitIndexErrors' option #3174 + * added; 'async' option for aggregation cursor to support buffering #3160 + * added; ability to skip validation for individual save() calls #2981 + * added; single embedded schema support #2689 #585 + * added; depopulate function #2509 + +4.1.12 / 2015-10-19 +=================== + * docs; use readPreference instead of slaveOk for Query.setOptions docs #3471 [buunguyen](https://github.com/buunguyen) + * fixed; more helpful error when regexp contains null bytes #3456 + * fixed; x509 auth issue #3454 [NoxHarmonium](https://github.com/NoxHarmonium) + +3.8.36 / 2015-10-18 +=================== + * fixed; Make array props non-enumerable #3461 [boblauer](https://github.com/boblauer) + +4.1.11 / 2015-10-12 +=================== + * fixed; update timestamps for update() if they're enabled #3450 [isayme](https://github.com/isayme) + * fixed; unit test error on node 0.10 #3449 [isayme](https://github.com/isayme) + * docs; timestamp option docs #3448 [isayme](https://github.com/isayme) + * docs; fix unexpected indent #3443 [isayme](https://github.com/isayme) + * fixed; use ES6 promises for Model.prototype.remove() #3442 + * fixed; don't use unused 'safe' option for index builds #3439 + * fixed; elemMatch casting bug #3437 #3435 [DefinitelyCarter](https://github.com/DefinitelyCarter) + * docs; schema.index docs #3434 + * fixed; exceptions in save() callback getting swallowed on mongodb 2.4 #3371 + +4.1.10 / 2015-10-05 +=================== + * docs; improve virtuals docs to explain virtuals schema option #3433 [zoyaH](https://github.com/zoyaH) + * docs; MongoDB server version compatibility guide #3427 + * docs; clarify that findById and findByIdAndUpdate fire hooks #3422 + * docs; clean up Model.save() docs #3420 + * fixed; properly handle projection with just id #3407 #3412 + * fixed; infinite loop when database document is corrupted #3405 + * docs; clarify remove middleware #3388 + +4.1.9 / 2015-09-28 +================== + * docs; minlength and maxlength string validation docs #3368 #3413 [cosmosgenius](https://github.com/cosmosgenius) + * fixed; linting for infix operators #3397 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; proper casting for $all #3394 + * fixed; unhandled rejection warnings with .create() #3391 + * docs; clarify update validators on paths that aren't explicitly set #3386 + * docs; custom validator examples #2778 + +4.1.8 / 2015-09-21 +================== + * docs; fixed typo in example #3390 [kmctown](https://github.com/kmctown) + * fixed; error in toObject() #3387 [guumaster](https://github.com/guumaster) + * fixed; handling for casting null dates #3383 [alexmingoia](https://github.com/alexmingoia) + * fixed; passing composite ids to `findByIdAndUpdate` #3380 + * fixed; linting #3376 #3375 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; added NodeJS v4 to Travis #3374 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; casting $elemMatch inside of $not #3373 [gaguirre](https://github.com/gaguirre) + * fixed; handle case where $slice is 0 #3369 + * fixed; avoid running getters if path is populated #3357 + * fixed; cast documents to objects when setting to a nested path #3346 + +4.1.7 / 2015-09-14 +================== + * docs; typos in SchemaType documentation #3367 [jasson15](https://github.com/jasson15) + * fixed; MONGOOSE_DRIVER_PATH env variable again #3360 + * docs; added validateSync docs #3353 + * fixed; set findOne op synchronously in query #3344 + * fixed; handling for `.pull()` on a documentarray without an id #3341 + * fixed; use natural order for cloning update conditions #3338 + * fixed; issue with strict mode casting for mixed type updates #3337 + +4.1.6 / 2015-09-08 +================== + * fixed; MONGOOSE_DRIVER_PATH env variable #3345 [g13013](https://github.com/g13013) + * docs; global autoIndex option #3335 [albertorestifo](https://github.com/albertorestifo) + * docs; model documentation typos #3330 + * fixed; report reason for CastError #3320 + * fixed; .populate() no longer returns true after re-assigning #3308 + * fixed; discriminators with aggregation geoNear #3304 + * docs; discriminator docs #2743 + +4.1.5 / 2015-09-01 +================== + * fixed; document.remove() removing all docs #3326 #3325 + * fixed; connect() checks for rs_name in options #3299 + * docs; examples for schema.set() #3288 + * fixed; checkKeys issue with bluebird #3286 [gregthegeek](https://github.com/gregthegeek) + +4.1.4 / 2015-08-31 +================== + * fixed; ability to set strict: false for update #3305 + * fixed; .create() properly uses ES6 promises #3297 + * fixed; pre hooks on nested subdocs #3291 #3284 [aliatsis](https://github.com/aliatsis) + * docs; remove unclear text in .remove() docs #3282 + * fixed; pre hooks called twice for 3rd-level nested doc #3281 + * fixed; nested transforms #3279 + * upgraded; mquery -> 1.6.3 #3278 #3272 + * fixed; don't swallow callback errors by default #3273 #3222 + * fixed; properly get nested paths from nested schemas #3265 + * fixed; remove() with id undefined deleting all docs #3260 [thanpolas](https://github.com/thanpolas) + * fixed; handling for non-numeric projections #3256 + * fixed; findById with id undefined returning first doc #3255 + * fixed; use retainKeyOrder for update #3215 + * added; passRawResult option to findOneAndUpdate for backwards compat #3173 + +4.1.3 / 2015-08-16 +================== + * fixed; getUpdate() in pre update hooks #3520 [gregthegeek](https://github.com/gregthegeek) + * fixed; handleArray() ensures arg is an array #3238 [jloveridge](https://github.com/jloveridge) + * fixed; refresh required path cache when recreating docs #3199 + * fixed; $ operator on unwind aggregation helper #3197 + * fixed; findOneAndUpdate() properly returns raw result as third arg to callback #3173 + * fixed; querystream with dynamic refs #3108 + +3.8.35 / 2015-08-14 +=================== + * fixed; handling for minimize on nested objects #2930 + * fixed; don't crash when schema.path.options undefined #1824 + +4.1.2 / 2015-08-10 +================== + * fixed; better handling for Jade templates #3241 [kbadk](https://github.com/kbadk) + * added; ESlint trailing spaces #3234 [ChristianMurphy](https://github.com/ChristianMurphy) + * added; ESlint #3191 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; properly emit event on disconnect #3183 + * fixed; copy options properly using Query.toConstructor() #3176 + * fixed; setMaxListeners() issue in browser build #3170 + * fixed; node driver -> 2.0.40 to not store undefined keys as null #3169 + * fixed; update validators handle positional operator #3167 + * fixed; handle $all + $elemMatch query casting #3163 + * fixed; post save hooks don't swallow extra args #3155 + * docs; spelling mistake in index.jade #3154 + * fixed; don't crash when toObject() has no fields #3130 + * fixed; apply toObject() recursively for find and update queries #3086 [naoina](https://github.com/naoina) + +4.1.1 / 2015-08-03 +================== + * fixed; aggregate exec() crash with no callback #3212 #3198 [jpgarcia](https://github.com/jpgarcia) + * fixed; pre init hooks now properly synchronous #3207 [burtonjc](https://github.com/burtonjc) + * fixed; updateValidators doesn't flatten dates #3206 #3194 [victorkohl](https://github.com/victorkohl) + * fixed; default fields don't make document dirty between saves #3205 [burtonjc](https://github.com/burtonjc) + * fixed; save passes 0 as numAffected rather than undefined when no change #3195 [burtonjc](https://github.com/burtonjc) + * fixed; better handling for positional operator in update #3185 + * fixed; use Travis containers #3181 [ChristianMurphy](https://github.com/ChristianMurphy) + * fixed; leaked variable #3180 [ChristianMurphy](https://github.com/ChristianMurphy) + +4.1.0 / 2015-07-24 +================== + * added; `schema.queue()` now public #3193 + * added; raw result as third parameter to findOneAndX callback #3173 + * added; ability to run validateSync() on only certain fields #3153 + * added; subPopulate #3103 [timbur](https://github.com/timbur) + * added; $isDefault function on documents #3077 + * added; additional properties for built-in validator messages #3063 [KLicheR](https://github.com/KLicheR) + * added; getQuery() and getUpdate() functions for Query #3013 + * added; export DocumentProvider #2996 + * added; ability to remove path from schema #2993 [JohnnyEstilles](https://github.com/JohnnyEstilles) + * added; .explain() helper for aggregate #2714 + * added; ability to specify which ES6-compatible promises library mongoose uses #2688 + * added; export Aggregate #1910 + +4.0.8 / 2015-07-20 +================== + * fixed; assignment with document arrays #3178 [rosston](https://github.com/rosston) + * docs; remove duplicate paragraph #3164 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * docs; improve findOneAndXYZ parameter descriptions #3159 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * docs; add findOneAndRemove to list of supported middleware #3158 + * docs; clarify ensureIndex #3156 + * fixed; refuse to save/remove document without id #3118 + * fixed; hooks next() no longer accidentally returns promise #3104 + * fixed; strict mode for findOneAndUpdate #2947 + * added; .min.js.gz file for browser component #2806 + +3.8.34 / 2015-07-20 +=================== + * fixed; allow using $rename #3171 + * fixed; no longer modifies update arguments #3008 + +4.0.7 / 2015-07-11 +================== + * fixed; documentarray id method when using object id #3157 [siboulet](https://github.com/siboulet) + * docs; improve findById docs #3147 + * fixed; update validators handle null properly #3136 [odeke-em](https://github.com/odeke-em) + * docs; jsdoc syntax errors #3128 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * docs; fix typo #3126 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * docs; proper formatting in queries.jade #3121 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * docs; correct example for string maxlength validator #3111 [rhmeeuwisse](https://github.com/rhmeeuwisse) + * fixed; setDefaultsOnInsert with arrays #3107 + * docs; LearnBoost -> Automattic in package.json #3099 + * docs; pre update hook example #3094 [danpe](https://github.com/danpe) + * docs; clarify query middleware example #3051 + * fixed; ValidationErrors in strict mode #3046 + * fixed; set findOneAndUpdate properties before hooks run #3024 + +3.8.33 / 2015-07-10 +=================== + * upgraded; node driver -> 1.4.38 + * fixed; dont crash when `match` validator undefined + +4.0.6 / 2015-06-21 +================== + * upgraded; node driver -> 2.0.34 #3087 + * fixed; apply setters on addToSet, etc #3067 [victorkohl](https://github.com/victorkohl) + * fixed; missing semicolons #3065 [sokolikp](https://github.com/sokolikp) + * fixed; proper handling for async doc hooks #3062 [gregthegeek](https://github.com/gregthegeek) + * fixed; dont set failed populate field to null if other docs are successfully populated #3055 [eloytoro](https://github.com/eloytoro) + * fixed; setDefaultsOnInsert with document arrays #3034 [taxilian](https://github.com/taxilian) + * fixed; setters fired on array items #3032 + * fixed; stop validateSync() on first error #3025 [victorkohl](https://github.com/victorkohl) + * docs; improve query docs #3016 + * fixed; always exclude _id when its deselected #3010 + * fixed; enum validator kind property #3009 + * fixed; mquery collection names #3005 + * docs; clarify mongos option #3000 + * docs; clarify that query builder has a .then() #2995 + * fixed; race condition in dynamic ref #2992 + +3.8.31 / 2015-06-20 +=================== + * fixed; properly handle text search with discriminators and $meta #2166 + +4.0.5 / 2015-06-05 +================== + * fixed; ObjectIds and buffers when mongodb driver is a sibling dependency #3050 #3048 #3040 #3031 #3020 #2988 #2951 + * fixed; warn user when 'increment' is used in schema #3039 + * fixed; setDefaultsOnInsert with array in schema #3035 + * fixed; dont use default Object toString to cast to string #3030 + * added; npm badge #3020 [odeke-em](https://github.com/odeke-em) + * fixed; proper handling for calling .set() with a subdoc #2782 + * fixed; dont throw cast error when using $rename on non-string path #1845 + +3.8.30 / 2015-06-05 +=================== + * fixed; enable users to set all options with tailable() #2883 + +4.0.4 / 2015-05-28 +================== + * docs; findAndModify new parameter correct default value #3012 [JonForest](https://github.com/JonForest) + * docs; clarify pluralization rules #2999 [anonmily](https://github.com/anonmily) + * fix; discriminators with schema methods #2978 + * fix; make `isModified` a schema reserved keyword #2975 + * fix; properly fire setters when initializing path with object #2943 + * fix; can use `setDefaultsOnInsert` without specifying `runValidators` #2938 + * fix; always set validation errors `kind` property #2885 + * upgraded; node driver -> 2.0.33 #2865 + +3.8.29 / 2015-05-27 +=================== + * fixed; Handle JSON.stringify properly for nested docs #2990 + +4.0.3 / 2015-05-13 +================== + * upgraded; mquery -> 1.5.1 #2983 + * docs; clarify context for query middleware #2974 + * docs; fix missing type -> kind rename in History.md #2961 + * fixed; broken ReadPreference include on Heroku #2957 + * docs; correct form for cursor aggregate option #2955 + * fixed; sync post hooks now properly called after function #2949 #2925 + * fixed; fix sub-doc validate() function #2929 + * upgraded; node driver -> 2.0.30 #2926 + * docs; retainKeyOrder for save() #2924 + * docs; fix broken class names #2913 + * fixed; error when using node-clone on a doc #2909 + * fixed; no more hard references to bson #2908 #2906 + * fixed; dont overwrite array values #2907 [naoina](https://github.com/naoina) + * fixed; use readPreference=primary for findOneAndUpdate #2899 #2823 + * docs; clarify that update validators only run on $set and $unset #2889 + * fixed; set kind consistently for built-in validators #2885 + * docs; single field populated documents #2884 + * fixed; nested objects are now enumerable #2880 [toblerpwn](https://github.com/toblerpwn) + * fixed; properly populate field when ref, lean, stream used together #2841 + * docs; fixed migration guide jade error #2807 + +3.8.28 / 2015-05-12 +=================== + * fixed; proper handling for toJSON options #2910 + * fixed; dont attach virtuals to embedded docs in update() #2046 + +4.0.2 / 2015-04-23 +================== + * fixed; error thrown when calling .validate() on subdoc not in an array #2902 + * fixed; rename define() to play nice with webpack #2900 [jspears](https://github.com/jspears) + * fixed; pre validate called twice with discriminators #2892 + * fixed; .inspect() on mongoose.Types #2875 + * docs; correct callback params for Model.update #2872 + * fixed; setDefaultsOnInsert now works when runValidators not specified #2870 + * fixed; Document now wraps EventEmitter.addListener #2867 + * fixed; call non-hook functions in schema queue #2856 + * fixed; statics can be mocked out for tests #2848 [ninelb](https://github.com/ninelb) + * upgraded; mquery 1.4.0 for bluebird bug fix #2846 + * fixed; required validators run first #2843 + * docs; improved docs for new option to findAndMody #2838 + * docs; populate example now uses correct field #2837 [swilliams](https://github.com/swilliams) + * fixed; pre validate changes causing VersionError #2835 + * fixed; get path from correct place when setting CastError #2832 + * docs; improve docs for Model.update() function signature #2827 [irnc](https://github.com/irnc) + * fixed; populating discriminators #2825 [chetverikov](https://github.com/chetverikov) + * fixed; discriminators with nested schemas #2821 + * fixed; CastErrors with embedded docs #2819 + * fixed; post save hook context #2816 + * docs; 3.8.x -> 4.x migration guide #2807 + * fixed; proper _distinct copying for query #2765 [cdelauder](https://github.com/cdelauder) + +3.8.27 / 2015-04-22 +=================== + * fixed; dont duplicate db calls on Q.ninvoke() #2864 + * fixed; Model.find arguments naming in docs #2828 + * fixed; Support ipv6 in connection strings #2298 + +3.8.26 / 2015-04-07 +=================== + * fixed; TypeError when setting date to undefined #2833 + * fixed; handle CastError properly in distinct() with no callback #2786 + * fixed; broken links in queries docs #2779 + * fixed; dont mark buffer as modified when setting type initially #2738 + * fixed; dont crash when using slice with populate #1934 + +4.0.1 / 2015-03-28 +================== + * fixed; properly handle empty cast doc in update() with promises #2796 + * fixed; unstable warning #2794 + * fixed; findAndModify docs now show new option is false by default #2793 + +4.0.0 / 2015-03-25 +================== + * fixed; on-the-fly schema docs typo #2783 [artiifix](https://github.com/artiifix) + * fixed; cast error validation handling #2775 #2766 #2678 + * fixed; discriminators with populate() #2773 #2719 [chetverikov](https://github.com/chetverikov) + * fixed; increment now a reserved path #2709 + * fixed; avoid sending duplicate object ids in populate() #2683 + * upgraded; mongodb to 2.0.24 to properly emit reconnect event multiple times #2656 + +4.0.0-rc4 / 2015-03-14 +====================== + * fixed; toObject virtuals schema option handled properly #2751 + * fixed; update validators work on document arrays #2733 + * fixed; check for cast errors on $set #2729 + * fixed; instance field set for all schema types #2727 [csdco](https://github.com/csdco) + * fixed; dont run other validators if required fails #2725 + * fixed; custom getters execute on ref paths #2610 + * fixed; save defaults if they were set when doc was loaded from db #2558 + * fixed; pre validate now runs before pre save #2462 + * fixed; no longer throws errors with --use_strict #2281 + +3.8.25 / 2015-03-13 +=================== + * fixed; debug output reverses order of aggregation keys #2759 + * fixed; $eq is a valid query selector in 3.0 #2752 + * fixed; upgraded node driver to 1.4.32 for handling non-numeric poolSize #2682 + * fixed; update() with overwrite sets _id for nested docs #2658 + * fixed; casting for operators in $elemMatch #2199 + +4.0.0-rc3 / 2015-02-28 +====================== + * fixed; update() pre hooks run before validators #2706 + * fixed; setters not called on arrays of refs #2698 [brandom](https://github.com/brandom) + * fixed; use node driver 2.0.18 for nodejs 0.12 support #2685 + * fixed; comments reference file that no longer exists #2681 + * fixed; populated() returns _id of manually populated doc #2678 + * added; ability to exclude version key in toObject() #2675 + * fixed; dont allow setting nested path to a string #2592 + * fixed; can cast objects with _id field to ObjectIds #2581 + * fixed; on-the-fly schema getters #2360 + * added; strict option for findOneAndUpdate() #1967 + +3.8.24 / 2015-02-25 +=================== + * fixed; properly apply child schema transforms #2691 + * fixed; make copy of findOneAndUpdate options before modifying #2687 + * fixed; apply defaults when parent path is selected #2670 #2629 + * fixed; properly get ref property for nested paths #2665 + * fixed; node driver makes copy of authenticate options before modifying them #2619 + * fixed; dont block process exit when auth fails #2599 + * fixed; remove redundant clone in update() #2537 + +4.0.0-rc2 / 2015-02-10 +====================== + * added; io.js to travis build + * removed; browser build dependencies not installed by default + * added; dynamic refpaths #2640 [chetverikov](https://github.com/chetverikov) + * fixed; dont call child schema transforms on parent #2639 [chetverikov](https://github.com/chetverikov) + * fixed; get rid of remove option if new is set in findAndModify #2598 + * fixed; aggregate all document array validation errors #2589 + * fixed; custom setters called when setting value to undefined #1892 + +3.8.23 / 2015-02-06 +=================== + * fixed; unset opts.remove when upsert is true #2519 + * fixed; array saved as object when path is object in array #2442 + * fixed; inline transforms #2440 + * fixed; check for callback in count() #2204 + * fixed; documentation for selecting fields #1534 + +4.0.0-rc1 / 2015-02-01 +====================== + * fixed; use driver 2.0.14 + * changed; use transform: true by default #2245 + +4.0.0-rc0 / 2015-01-31 +=================== + * fixed; wrong order for distinct() params #2628 + * fixed; handling no query argument to remove() #2627 + * fixed; createModel and discriminators #2623 [ashaffer](https://github.com/ashaffer) + * added; pre('count') middleware #2621 + * fixed; double validation calls on document arrays #2618 + * added; validate() catches cast errors #2611 + * fixed; respect replicaSet parameter in connection string #2609 + * added; can explicitly exclude paths from versioning #2576 [csabapalfi](https://github.com/csabapalfi) + * upgraded; driver to 2.0.15 #2552 + * fixed; save() handles errors more gracefully in ES6 #2371 + * fixed; undefined is now a valid argument to findOneAndUpdate #2272 + * changed; `new` option to findAndModify ops is false by default #2262 + +3.8.22 / 2015-01-24 +=================== + * upgraded; node-mongodb-native to 1.4.28 #2587 [Climax777](https://github.com/Climax777) + * added; additional documentation for validators #2449 + * fixed; stack overflow when creating massive arrays #2423 + * fixed; undefined is a valid id for queries #2411 + * fixed; properly create nested schema index when same schema used twice #2322 + * added; link to plugin generator in docs #2085 [huei90](https://github.com/huei90) + * fixed; optional arguments documentation for findOne() #1971 [nachinius](https://github.com/nachinius) + +3.9.7 / 2014-12-19 +=================== + * added; proper cursors for aggregate #2539 [changyy](https://github.com/changyy) + * added; min/max built-in validators for dates #2531 [bshamblen](https://github.com/bshamblen) + * fixed; save and validate are now reserved keywords #2380 + * added; basic documentation for browser component #2256 + * added; find and findOne hooks (query middleware) #2138 + * fixed; throw a DivergentArrayError when saving positional operator queries #2031 + * added; ability to use options as a document property #1416 + * fixed; document no longer inherits from event emitter and so domain and _events are no longer reserved #1351 + * removed; setProfiling #1349 + +3.8.21 / 2014-12-18 +=================== + * fixed; syntax in index.jade #2517 [elderbas](https://github.com/elderbas) + * fixed; writable statics #2510 #2528 + * fixed; overwrite and explicit $set casting #2515 + +3.9.6 / 2014-12-05 +=================== + * added; correctly run validators on each element of array when entire array is modified #661 #1227 + * added; castErrors in validation #1013 [jondavidjohn](https://github.com/jondavidjohn) + * added; specify text indexes in schema fields #1401 [sr527](https://github.com/sr527) + * added; ability to set field with validators to undefined #1594 [alabid](https://github.com/alabid) + * added; .create() returns an array when passed an array #1746 [alabid](https://github.com/alabid) + * added; test suite and docs for use with co and yield #2177 #2474 + * fixed; subdocument toObject() transforms #2447 [chmanie](https://github.com/chmanie) + * fixed; Model.create() with save errors #2484 + * added; pass options to .save() and .remove() #2494 [jondavidjohn](https://github.com/jondavidjohn) + +3.8.20 / 2014-12-01 +=================== + * fixed; recursive readPref #2490 [kjvalencik](https://github.com/kjvalencik) + * fixed; make sure to copy parameters to update() before modifying #2406 [alabid](https://github.com/alabid) + * fixed; unclear documentation about query callbacks #2319 + * fixed; setting a schema-less field to an empty object #2314 [alabid](https://github.com/alabid) + * fixed; registering statics and methods for discriminators #2167 [alabid](https://github.com/alabid) + +3.9.5 / 2014-11-10 +=================== + * added; ability to disable autoIndex on a per-connection basis #1875 [sr527](https://github.com/sr527) + * fixed; `geoNear()` no longer enforces legacy coordinate pairs - supports GeoJSON #1987 [alabid](https://github.com/alabid) + * fixed; browser component works when minified with mangled variable names #2302 + * fixed; `doc.errors` now cleared before `validate()` called #2302 + * added; `execPopulate()` function to make `doc.populate()` compatible with promises #2317 + * fixed; `count()` no longer throws an error when used with `sort()` #2374 + * fixed; `save()` no longer recursively calls `save()` on populated fields #2418 + +3.8.19 / 2014-11-09 +=================== + * fixed; make sure to not override subdoc _ids on find #2276 [alabid](https://github.com/alabid) + * fixed; exception when comparing two documents when one lacks _id #2333 [slawo](https://github.com/slawo) + * fixed; getters for properties with non-strict schemas #2439 [alabid](https://github.com/alabid) + * fixed; inconsistent URI format in docs #2414 [sr527](https://github.com/sr527) + +3.9.4 / 2014-10-25 +================== + * fixed; statics no longer can be overwritten #2343 [nkcmr](https://github.com/chetverikov) + * added; ability to set single populated paths to documents #1530 + * added; setDefaultsOnInsert and runValidator options for findOneAndUpdate() #860 + +3.8.18 / 2014-10-22 +================== + * fixed; Dont use all toObject options in save #2340 [chetverikov](https://github.com/chetverikov) + +3.9.3 / 2014-10-01 +================= + * added; support for virtuals that return objects #2294 + * added; ability to manually hydrate POJOs into mongoose objects #2292 + * added; setDefaultsOnInsert and runValidator options for update() #860 + +3.8.17 / 2014-09-29 +================== + * fixed; use schema options retainKeyOrder in save() #2274 + * fixed; fix skip in populate when limit is set #2252 + * fixed; fix stack overflow when passing MongooseArray to findAndModify #2214 + * fixed; optimize .length usage in populate #2289 + +3.9.2 / 2014-09-08 +================== + * added; test coverage for browser component #2255 + * added; in-order execution of validators #2243 + * added; custom fields for validators #2132 + * removed; exception thrown when find() used with count() #1950 + +3.8.16 / 2014-09-08 +================== + * fixed; properly remove modified array paths if array has been overwritten #1638 + * fixed; key check errors #1884 + * fixed; make sure populate on an array always returns a Mongoose array #2214 + * fixed; SSL connections with node 0.11 #2234 + * fixed; return sensible strings for promise errors #2239 + +3.9.1 / 2014-08-17 +================== + * added; alpha version of browser-side schema validation #2254 + * added; support passing a function to schemas `required` field #2247 + * added; support for setting updatedAt and createdAt timestamps #2227 + * added; document.validate() returns a promise #2131 + +3.8.15 / 2014-08-17 +================== + * fixed; Replica set connection string example in docs #2246 + * fixed; bubble up parseError event #2229 + * fixed; removed buggy populate cache #2176 + * fixed; dont $inc versionKey if its being $set #1933 + * fixed; cast $or and $and in $pull #1932 + * fixed; properly cast to schema in stream() #1862 + * fixed; memory leak in nested objects #1565 #2211 [devongovett](https://github.com/devongovett) + +3.8.14 / 2014-07-26 +================== + * fixed; stringifying MongooseArray shows nested arrays #2002 + * fixed; use populated doc schema in toObject and toJSON by default #2035 + * fixed; dont crash on arrays containing null #2140 + * fixed; model.update w/ upsert has same return values on .exec and promise #2143 + * fixed; better handling for populate limit with multiple documents #2151 + * fixed; dont prevent users from adding weights to text index #2183 + * fixed; helper for aggregation cursor #2187 + * updated; node-mongodb-native to 1.4.7 + +3.8.13 / 2014-07-15 +================== + * fixed; memory leak with isNew events #2159 + * fixed; docs for overwrite option for update() #2144 + * fixed; storeShard() handles dates properly #2127 + * fixed; sub-doc changes not getting persisted to db after save #2082 + * fixed; populate with _id: 0 actually removes _id instead of setting to undefined #2123 + * fixed; save versionKey on findOneAndUpdate w/ upsert #2122 + * fixed; fix typo in 2.8 docs #2120 [shakirullahi](https://github.com/shakirullahi) + * fixed; support maxTimeMs #2102 [yuukinajima](https://github.com/yuukinajima) + * fixed; support $currentDate #2019 + * fixed; $addToSet handles objects without _ids properly #1973 + * fixed; dont crash on invalid nearSphere query #1874 + +3.8.12 / 2014-05-30 +================== + * fixed; single-server reconnect event fires #1672 + * fixed; sub-docs not saved when pushed into populated array #1794 + * fixed; .set() sometimes converts embedded docs to pojos #1954 [archangel-irk](https://github.com/archangel-irk) + * fixed; sub-doc changes not getting persisted to db after save #2082 + * fixed; custom getter might cause mongoose to mistakenly think a path is dirty #2100 [pgherveou](https://github.com/pgherveou) + * fixed; chainable helper for allowDiskUse option in aggregation #2114 + +3.9.0 (unstable) / 2014-05-22 +================== + * changed; added `domain` to reserved keywords #1338 #2052 [antoinepairet](https://github.com/antoinepairet) + * added; asynchronous post hooks #1977 #2081 [chopachom](https://github.com/chopachom) [JasonGhent](https://github.com/JasonGhent) + * added; using model for population, cross-db populate [mihai-chiorean](https://github.com/mihai-chiorean) + * added; can define a type for schema validators + * added; `doc.remove()` returns a promise #1619 [refack](https://github.com/refack) + * added; internal promises for hooks, pre-save hooks run in parallel #1732 [refack](https://github.com/refack) + * fixed; geoSearch hanging when no results returned #1846 [ghartnett](https://github.com/ghartnett) + * fixed; do not set .type property on ValidationError, use .kind instead #1323 + +3.8.11 / 2014-05-22 +================== + * updated; node-mongodb-native to 1.4.5 + * reverted; #2052, fixes #2097 + +3.8.10 / 2014-05-20 +================== + + * updated; node-mongodb-native to 1.4.4 + * fixed; _.isEqual false negatives bug in js-bson #2070 + * fixed; missing check for schema.options #2014 + * fixed; missing support for $position #2024 + * fixed; options object corruption #2049 + * fixed; improvements to virtuals docs #2055 + * fixed; added `domain` to reserved keywords #2052 #1338 + +3.8.9 / 2014-05-08 +================== + + * updated; mquery to 0.7.0 + * updated; node-mongodb-native to 1.4.3 + * fixed; $near failing against MongoDB 2.6 + * fixed; relying on .options() to determine if collection exists + * fixed; $out aggregate helper + * fixed; all test failures against MongoDB 2.6.1, with caveat #2065 + +3.8.8 / 2014-02-22 +================== + + * fixed; saving Buffers #1914 + * updated; expose connection states for user-land #1926 [yorkie](https://github.com/yorkie) + * updated; mquery to 0.5.3 + * updated; added get / set to reserved path list #1903 [tstrimple](https://github.com/tstrimple) + * docs; README code highlighting, syntax fixes #1930 [IonicaBizau](https://github.com/IonicaBizau) + * docs; fixes link in the doc at #1925 [kapeels](https://github.com/kapeels) + * docs; add a missed word 'hook' for the description of the post-hook api #1924 [ipoval](https://github.com/ipoval) + +3.8.7 / 2014-02-09 +================== + + * fixed; sending safe/read options in Query#exec #1895 + * fixed; findOneAnd..() with sort #1887 + +3.8.6 / 2014-01-30 +================== + + * fixed; setting readPreferences #1895 + +3.8.5 / 2014-01-23 +================== + + * fixed; ssl setting when using URI #1882 + * fixed; findByIdAndUpdate now respects the overwrite option #1809 [owenallenaz](https://github.com/owenallenaz) + +3.8.4 / 2014-01-07 +================== + + * updated; mongodb driver to 1.3.23 + * updated; mquery to 0.4.1 + * updated; mpromise to 0.4.3 + * fixed; discriminators now work when selecting fields #1820 [daemon1981](https://github.com/daemon1981) + * fixed; geoSearch with no results timeout #1846 [ghartnett](https://github.com/ghartnett) + * fixed; infitite recursion in ValidationError #1834 [chetverikov](https://github.com/chetverikov) + +3.8.3 / 2013-12-17 +================== + + * fixed; setting empty array with model.update #1838 + * docs; fix url + +3.8.2 / 2013-12-14 +================== + + * fixed; enum validation of multiple values #1778 [heroicyang](https://github.com/heroicyang) + * fixed; global var leak #1803 + * fixed; post remove now fires on subdocs #1810 + * fixed; no longer set default empty array for geospatial-indexed fields #1668 [shirish87](https://github.com/shirish87) + * fixed; model.stream() not hydrating discriminators correctly #1792 [j](https://github.com/j) + * docs: Stablility -> Stability [nikmartin](https://github.com/nikmartin) + * tests; improve shard error handling + +3.8.1 / 2013-11-19 +================== + + * fixed; mishandling of Dates with minimize/getters #1764 + * fixed; Normalize bugs.email, so `npm` will shut up #1769 [refack](https://github.com/refack) + * docs; Improve the grammar where "lets us" was used #1777 [alexyoung](https://github.com/alexyoung) + * docs; Fix some grammatical issues in the documentation #1777 [alexyoung](https://github.com/alexyoung) + * docs; fix Query api exposure + * docs; fix return description + * docs; Added Notes on findAndUpdate() #1750 [sstadelman](https://github.com/sstadelman) + * docs; Update version number in README #1762 [Fodi69](https://github.com/Fodi69) + +3.8.0 / 2013-10-31 +================== + + * updated; warn when using an unstable version + * updated; error message returned in doc.save() #1595 + * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) + * updated; mquery to 0.3.2 + * updated; mocha to 1.12.0 + * updated; mpromise 0.3.0 + * updated; sliced 0.0.5 + * removed; mongoose.Error.DocumentError (never used) + * removed; namedscope (undocumented and broken) #679 #642 #455 #379 + * changed; no longer offically supporting node 0.6.x + * changed; query.within getter is now a method -> query.within() + * changed; query.intersects getter is now a method -> query.intersects() + * added; custom error msgs for built-in validators #747 + * added; discriminator support #1647 #1003 [j](https://github.com/j) + * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) + * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) + * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) + * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) + * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) + * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) + * added; promise support to model.mapReduce() + * added; promise support to model.ensureIndexes() + * added; promise support to model.populate() + * added; benchmarks [ebensing](https://github.com/ebensing) + * added; publicly exposed connection states #1585 + * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) + * added; query method chain validation + * added; model.update `overwrite` option + * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) + * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) + * added; MongooseBuffer#subtype() + * added; model.create() now returns a promise #1340 + * added; support for `awaitdata` query option + * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) + * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) + * fixed; document.toObject when using `minimize` and `getters` options #1607 [JedWatson](https://github.com/JedWatson) + * fixed; Mixed types can now be required #1722 [Reggino](https://github.com/Reggino) + * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) + * fixed; repopulating modified populated paths #1697 + * fixed; doc.equals() when _id option is set to false #1687 + * fixed; strict mode warnings #1686 + * fixed; $near GeoJSON casting #1683 + * fixed; nearSphere GeoJSON query builder + * fixed; population field selection w/ strings #1669 + * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) + * fixed; handle another versioning edge case #1520 + * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) + * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) + * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) + * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) + * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) + * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) + * fixed; model.remove() removes only what is necessary #1649 + * fixed; update() now only runs with cb or explicit true #1644 + * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) + * fixed; model.update "overwrite" option works as documented + * fixed; query#remove() works as documented + * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) + * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) + * fixed; benchmarks to actually output valid json + * deprecated; promise#addBack (use promise#onResolve) + * deprecated; promise#complete (use promise#fulfill) + * deprecated; promise#addCallback (use promise#onFulFill) + * deprecated; promise#addErrback (use promise#onReject) + * deprecated; query.nearSphere() (use query.near) + * deprecated; query.center() (use query.circle) + * deprecated; query.centerSphere() (use query.circle) + * deprecated; query#slaveOk (use query#read) + * docs; custom validator messages + * docs; 10gen -> MongoDB + * docs; add Date method caveats #1598 + * docs; more validation details + * docs; state which branch is stable/unstable + * docs; mention that middleware does not run on Models + * docs; promise.fulfill() + * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) + * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) + * website; add "show code" for properties + * website; move "show code" links down + * website; update guide + * website; add unstable docs + * website; many improvements + * website; fix copyright #1439 + * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) + * tests; refactor 1703 + * tests; add test generator + * tests; validate formatMessage() throws + * tests; add script for continuously running tests + * tests; fixed versioning tests + * tests; race conditions in tests + * tests; added for nested and/or queries + * tests; close some test connections + * tests; validate db contents + * tests; remove .only + * tests; close some test connections + * tests; validate db contents + * tests; remove .only + * tests; replace deprecated method names + * tests; convert id to string + * tests; fix sharding tests for MongoDB 2.4.5 + * tests; now 4-5 seconds faster + * tests; fix race condition + * make; suppress warning msg in test + * benchmarks; updated for pull requests + * examples; improved and expanded [ebensing](https://github.com/ebensing) + +3.7.4 (unstable) / 2013-10-01 +============================= + + * updated; mquery to 0.3.2 + * removed; mongoose.Error.DocumentError (never used) + * added; custom error msgs for built-in validators #747 + * added; discriminator support #1647 #1003 [j](https://github.com/j) + * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) + * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) + * fixed; repopulating modified populated paths #1697 + * fixed; doc.equals() when _id option is set to false #1687 + * fixed; strict mode warnings #1686 + * fixed; $near GeoJSON casting #1683 + * fixed; nearSphere GeoJSON query builder + * fixed; population field selection w/ strings #1669 + * docs; custom validator messages + * docs; 10gen -> MongoDB + * docs; add Date method caveats #1598 + * docs; more validation details + * website; add "show code" for properties + * website; move "show code" links down + * tests; refactor 1703 + * tests; add test generator + * tests; validate formatMessage() throws + +3.7.3 (unstable) / 2013-08-22 +============================= + + * updated; warn when using an unstable version + * updated; mquery to 0.3.1 + * updated; mocha to 1.12.0 + * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) + * changed; no longer offically supporting node 0.6.x + * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) + * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) + * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) + * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) + * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) + * fixed; handle another versioning edge case #1520 + * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) + * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) + * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) + * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) + * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) + * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) + * make; suppress warning msg in test + * docs; state which branch is stable/unstable + * docs; mention that middleware does not run on Models + * tests; add script for continuously running tests + * tests; fixed versioning tests + * benchmarks; updated for pull requests + +3.7.2 (unstable) / 2013-08-15 +================== + + * fixed; model.remove() removes only what is necessary #1649 + * fixed; update() now only runs with cb or explicit true #1644 + * tests; race conditions in tests + * website; update guide + +3.7.1 (unstable) / 2013-08-13 +============================= + + * updated; driver to 1.3.18 (fixes memory leak) + * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) + * added; promise support to model.mapReduce() + * added; promise support to model.ensureIndexes() + * added; promise support to model.populate() + * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) + * fixed; model.update "overwrite" option works as documented + * fixed; query#remove() works as documented + * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) + * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) + * fixed; benchmarks to actually output valid json + * tests; added for nested and/or queries + * tests; close some test connections + * tests; validate db contents + * tests; remove .only + * tests; close some test connections + * tests; validate db contents + * tests; remove .only + * tests; replace deprecated method names + * tests; convert id to string + * docs; promise.fulfill() + +3.7.0 (unstable) / 2013-08-05 +=================== + + * changed; query.within getter is now a method -> query.within() + * changed; query.intersects getter is now a method -> query.intersects() + * deprecated; promise#addBack (use promise#onResolve) + * deprecated; promise#complete (use promise#fulfill) + * deprecated; promise#addCallback (use promise#onFulFill) + * deprecated; promise#addErrback (use promise#onReject) + * deprecated; query.nearSphere() (use query.near) + * deprecated; query.center() (use query.circle) + * deprecated; query.centerSphere() (use query.circle) + * deprecated; query#slaveOk (use query#read) + * removed; namedscope (undocumented and broken) #679 #642 #455 #379 + * added; benchmarks [ebensing](https://github.com/ebensing) + * added; publicly exposed connection states #1585 + * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) + * added; query method chain validation + * added; model.update `overwrite` option + * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) + * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) + * added; MongooseBuffer#subtype() + * added; model.create() now returns a promise #1340 + * added; support for `awaitdata` query option + * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) + * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) + * updated; integrate mquery #1562 [ebensing](https://github.com/ebensing) + * updated; error msg in doc.save() #1595 + * updated; bump driver to 1.3.15 + * updated; mpromise 0.3.0 + * updated; sliced 0.0.5 + * tests; fix sharding tests for MongoDB 2.4.5 + * tests; now 4-5 seconds faster + * tests; fix race condition + * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) + * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) + * website; add unstable docs + * website; many improvements + * website; fix copyright #1439 + * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) + * examples; improved and expanded [ebensing](https://github.com/ebensing) + +3.6.20 (stable) / 2013-09-23 +=================== + + * fixed; repopulating modified populated paths #1697 + * fixed; doc.equals w/ _id false #1687 + * fixed; strict mode warning #1686 + * docs; near/nearSphere + +3.6.19 (stable) / 2013-09-04 +================== + + * fixed; population field selection w/ strings #1669 + * docs; Date method caveats #1598 + +3.6.18 (stable) / 2013-08-22 +=================== + + * updated; warn when using an unstable version of mongoose + * updated; mocha to 1.12.0 + * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) + * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) + * fixed; properly exclude subdocument fields #1280 [ebensing](https://github.com/ebensing) + * fixed; cast error in findAndModify #1643 [aheuermann](https://github.com/aheuermann) + * website; update guide + * website; added documentation for safe:false and versioning interaction + * docs; mention that middleware dont run on Models + * docs; fix indexes link + * make; suppress warning msg in test + * tests; moar + +3.6.17 / 2013-08-13 +=================== + + * updated; driver to 1.3.18 (fixes memory leak) + * fixed; casting ref docs on creation #1606 + * docs; query options + +3.6.16 / 2013-08-08 +=================== + + * added; publicly expose connection states #1585 + * fixed; limit applies to individual items on population #1490 [ebensing](https://github.com/ebensing) + * fixed; positional operator casting in updates #1572 [ebensing](https://github.com/ebensing) + * updated; MongoDB driver to 1.3.17 + * updated; sliced to 0.0.5 + * website; tweak homepage + * tests; fixed + added + * docs; fix some examples + * docs; multi-mongos support details + * docs; auto open browser after starting static server + +3.6.15 / 2013-07-16 +================== + + * added; mongos failover support #1037 + * updated; make schematype return vals return self #1580 + * docs; add note to model.update #571 + * docs; document third param to document.save callback #1536 + * tests; tweek mongos test timeout + +3.6.14 / 2013-07-05 +=================== + + * updated; driver to 1.3.11 + * fixed; issue with findOneAndUpdate not returning null on upserts #1533 [ebensing](https://github.com/ebensing) + * fixed; missing return statement in SchemaArray#$geoIntersects() #1498 [bsrykt](https://github.com/bsrykt) + * fixed; wrong isSelected() behavior #1521 [kyano](https://github.com/kyano) + * docs; note about toObject behavior during save() + * docs; add callbacks details #1547 [nikmartin](https://github.com/nikmartin) + +3.6.13 / 2013-06-27 +=================== + + * fixed; calling model.distinct without conditions #1541 + * fixed; regression in Query#count() #1542 + * now working on 3.6.13 + +3.6.12 / 2013-06-25 +=================== + + * updated; driver to 1.3.10 + * updated; clearer capped collection error message #1509 [bitmage](https://github.com/bitmage) + * fixed; MongooseBuffer subtype loss during casting #1517 [zedgu](https://github.com/zedgu) + * fixed; docArray#id when doc.id is disabled #1492 + * fixed; docArray#id now supports matches on populated arrays #1492 [pgherveou](https://github.com/pgherveou) + * website; fix example + * website; improve _id disabling example + * website; fix typo #1494 [dejj](https://github.com/dejj) + * docs; added a 'Requesting new features' section #1504 [shovon](https://github.com/shovon) + * docs; improve subtypes description + * docs; clarify _id disabling + * docs: display by alphabetical order the methods list #1508 [nicolasleger](https://github.com/nicolasleger) + * tests; refactor isSelected checks + * tests; remove pointless test + * tests; fixed timeouts + +3.6.11 / 2013-05-15 +=================== + + * updated; driver to 1.3.5 + * fixed; compat w/ Object.create(null) #1484 #1485 + * fixed; cloning objects w/ missing constructors + * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) + * docs; add doc.increment() example + * docs; add $size example + * docs; add "distinct" example + +3.6.10 / 2013-05-09 +================== + + * update driver to 1.3.3 + * fixed; increment() works without other changes #1475 + * website; fix links to posterous + * docs; fix link #1472 + +3.6.9 / 2013-05-02 +================== + + * fixed; depopulation of mixed documents #1471 + * fixed; use of $options in array #1462 + * tests; fix race condition + * docs; fix default example + +3.6.8 / 2013-04-25 +================== + + * updated; driver to 1.3.0 + * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) + * tests; 4-5 seconds faster + +3.6.7 / 2013-04-19 +================== + + * fixed; population regression in 3.6.6 #1444 + +3.6.6 / 2013-04-18 +================== + + * fixed; saving populated new documents #1442 + * fixed; population regession in 3.6.5 #1441 + * website; fix copyright #1439 + +3.6.5 / 2013-04-15 +================== + + * fixed; strict:throw edge case using .set(path, val) + * fixed; schema.pathType() on some numbericAlpha paths + * fixed; numbericAlpha path versioning + * fixed; setting nested mixed paths #1418 + * fixed; setting nested objects with null prop #1326 + * fixed; regression in v3.6 population performance #1426 [vedmalex](https://github.com/vedmalex) + * fixed; read pref typos #1422 [kyano](https://github.com/kyano) + * docs; fix method example + * website; update faq + * website; add more deep links + * website; update poolSize docs + * website; add 3.6 release notes + * website; note about keepAlive + +3.6.4 / 2013-04-03 +================== + + * fixed; +field conflict with $slice #1370 + * fixed; nested deselection conflict #1333 + * fixed; RangeError in ValidationError.toString() #1296 + * fixed; do not save user defined transforms #1415 + * tests; fix race condition + +3.6.3 / 2013-04-02 +================== + + * fixed; setting subdocuments deeply nested fields #1394 + * fixed; regression: populated streams #1411 + * docs; mention hooks/validation with findAndModify + * docs; mention auth + * docs; add more links + * examples; add document methods example + * website; display "see" links for properties + * website; clean up homepage + +3.6.2 / 2013-03-29 +================== + + * fixed; corrupted sub-doc array #1408 + * fixed; document#update returns a Query #1397 + * docs; readpref strategy + +3.6.1 / 2013-03-27 +================== + + * added; populate support to findAndModify varients #1395 + * added; text index type to schematypes + * expose allowed index types as Schema.indexTypes + * fixed; use of `setMaxListeners` as path + * fixed; regression in node 0.6 on docs with > 10 arrays + * fixed; do not alter schema arguments #1364 + * fixed; subdoc#ownerDocument() #1385 + * website; change search id + * website; add search from google [jackdbernier](https://github.com/jackdbernier) + * website; fix link + * website; add 3.5.x docs release + * website; fix link + * docs; fix geometry + * docs; hide internal constructor + * docs; aggregation does not cast arguments #1399 + * docs; querystream options + * examples; added for population + +3.6.0 / 2013-03-18 +================== + + * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) + * changed; Buffer arrays can now contain nulls + * added; QueryStream transform option + * added; support for authSource driver option + * added; {mongoose,db}.modelNames() + * added; $push w/ $slice,$sort support (MongoDB 2.4) + * added; hashed index type (MongoDB 2.4) + * added; support for mongodb 2.4 geojson (MongoDB 2.4) + * added; value at time of validation error + * added; support for object literal schemas + * added; bufferCommands schema option + * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) + * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) + * added; allow adding uncasted docs to populated arrays and properties #570 + * added; doc#populated(path) stores original populated _ids + * added; lean population #1260 + * added; query.populate() now accepts an options object + * added; document#populate(opts, callback) + * added; Model.populate(docs, opts, callback) + * added; support for rich nested path population + * added; doc.array.remove(value) subdoc with _id value support #1278 + * added; optionally allow non-strict sets and updates + * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) + * added; promise#then + * added; promise#end + * fixed; use of `model` as doc property + * fixed; lean population #1382 + * fixed; empty object mixed defaults #1380 + * fixed; populate w/ deselected _id using string syntax + * fixed; attempted save of divergent populated arrays #1334 related + * fixed; better error msg when attempting toObject as property name + * fixed; non population buffer casting from doc + * fixed; setting populated paths #570 + * fixed; casting when added docs to populated arrays #570 + * fixed; prohibit updating arrays selected with $elemMatch #1334 + * fixed; pull / set subdoc combination #1303 + * fixed; multiple bg index creation #1365 + * fixed; manual reconnection to single mongod + * fixed; Constructor / version exposure #1124 + * fixed; CastError race condition + * fixed; no longer swallowing misuse of subdoc#invalidate() + * fixed; utils.clone retains RegExp opts + * fixed; population of non-schema property + * fixed; allow updating versionKey #1265 + * fixed; add EventEmitter props to reserved paths #1338 + * fixed; can now deselect populated doc _ids #1331 + * fixed; properly pass subtype to Binary in MongooseBuffer + * fixed; casting _id from document with non-ObjectId _id + * fixed; specifying schema type edge case { path: [{type: "String" }] } + * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) + * updated; driver to 1.2.14 + * updated; muri to 0.3.1 + * updated; mpromise to 0.2.1 + * updated; mocha 1.8.1 + * updated; mpath to 0.1.1 + * deprecated; pluralization will die in 4.x + * refactor; rename private methods to something unusable as doc properties + * refactor MongooseArray#remove + * refactor; move expires index to SchemaDate #1328 + * refactor; internal document properties #1171 #1184 + * tests; added + * docs; indexes + * docs; validation + * docs; populate + * docs; populate + * docs; add note about stream compatibility with node 0.8 + * docs; fix for private names + * docs; Buffer -> mongodb.Binary #1363 + * docs; auth options + * docs; improved + * website; update FAQ + * website; add more api links + * website; add 3.5.x docs to prior releases + * website; Change mongoose-types to an active repo [jackdbernier](https://github.com/jackdbernier) + * website; compat with node 0.10 + * website; add news section + * website; use T for generic type + * benchmark; make adjustable + +3.6.0rc1 / 2013-03-12 +====================== + + * refactor; rename private methods to something unusable as doc properties + * added; {mongoose,db}.modelNames() + * added; $push w/ $slice,$sort support (MongoDB 2.4) + * added; hashed index type (MongoDB 2.4) + * added; support for mongodb 2.4 geojson (MongoDB 2.4) + * added; value at time of validation error + * added; support for object literal schemas + * added; bufferCommands schema option + * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) + * fixed; lean population #1382 + * fixed; empty object mixed defaults #1380 + * fixed; populate w/ deselected _id using string syntax + * fixed; attempted save of divergent populated arrays #1334 related + * fixed; better error msg when attempting toObject as property name + * fixed; non population buffer casting from doc + * fixed; setting populated paths #570 + * fixed; casting when added docs to populated arrays #570 + * fixed; prohibit updating arrays selected with $elemMatch #1334 + * fixed; pull / set subdoc combination #1303 + * fixed; multiple bg index creation #1365 + * fixed; manual reconnection to single mongod + * fixed; Constructor / version exposure #1124 + * fixed; CastError race condition + * fixed; no longer swallowing misuse of subdoc#invalidate() + * fixed; utils.clone retains RegExp opts + * fixed; population of non-schema property + * fixed; allow updating versionKey #1265 + * fixed; add EventEmitter props to reserved paths #1338 + * fixed; can now deselect populated doc _ids #1331 + * updated; muri to 0.3.1 + * updated; driver to 1.2.12 + * updated; mpromise to 0.2.1 + * deprecated; pluralization will die in 4.x + * docs; Buffer -> mongodb.Binary #1363 + * docs; auth options + * docs; improved + * website; add news section + * benchmark; make adjustable + +3.6.0rc0 / 2013-02-03 +====================== + + * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) + * changed; Buffer arrays can now contain nulls + * fixed; properly pass subtype to Binary in MongooseBuffer + * fixed; casting _id from document with non-ObjectId _id + * fixed; specifying schema type edge case { path: [{type: "String" }] } + * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) + * refactor; move expires index to SchemaDate #1328 + * refactor; internal document properties #1171 #1184 + * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) + * added; allow adding uncasted docs to populated arrays and properties #570 + * added; doc#populated(path) stores original populated _ids + * added; lean population #1260 + * added; query.populate() now accepts an options object + * added; document#populate(opts, callback) + * added; Model.populate(docs, opts, callback) + * added; support for rich nested path population + * added; doc.array.remove(value) subdoc with _id value support #1278 + * added; optionally allow non-strict sets and updates + * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) + * added; promise#then + * added; promise#end + * updated; mocha 1.8.1 + * updated; muri to 0.3.0 + * updated; mpath to 0.1.1 + * updated; docs + +3.5.16 / 2013-08-13 +=================== + + * updated; driver to 1.3.18 + +3.5.15 / 2013-07-26 +================== + + * updated; sliced to 0.0.5 + * updated; driver to 1.3.12 + * fixed; regression in Query#count() due to driver change + * tests; fixed timeouts + * tests; handle differing test uris + +3.5.14 / 2013-05-15 +=================== + + * updated; driver to 1.3.5 + * fixed; compat w/ Object.create(null) #1484 #1485 + * fixed; cloning objects missing constructors + * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) + +3.5.13 / 2013-05-09 +================== + + * update driver to 1.3.3 + * fixed; use of $options in array #1462 + +3.5.12 / 2013-04-25 +=================== + + * updated; driver to 1.3.0 + * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) + * fixed; read pref typos #1422 [kyano](https://github.com/kyano) + +3.5.11 / 2013-04-03 +================== + + * fixed; +field conflict with $slice #1370 + * fixed; RangeError in ValidationError.toString() #1296 + * fixed; nested deselection conflict #1333 + * remove time from Makefile + +3.5.10 / 2013-04-02 +================== + + * fixed; setting subdocuments deeply nested fields #1394 + * fixed; do not alter schema arguments #1364 + +3.5.9 / 2013-03-15 +================== + + * updated; driver to 1.2.14 + * added; support for authSource driver option (mongodb 2.4) + * added; QueryStream transform option (node 0.10 helper) + * fixed; backport for saving required populated buffers + * fixed; pull / set subdoc combination #1303 + * fixed; multiple bg index creation #1365 + * test; added for saveable required populated buffers + * test; added for #1365 + * test; add authSource test + +3.5.8 / 2013-03-12 +================== + + * added; auth option in connection [geoah](https://github.com/geoah) + * fixed; CastError race condition + * docs; add note about stream compatibility with node 0.8 + +3.5.7 / 2013-02-22 +================== + + * updated; driver to 1.2.13 + * updated; muri to 0.3.1 #1347 + * fixed; utils.clone retains RegExp opts #1355 + * fixed; deepEquals RegExp support + * tests; fix a connection test + * website; clean up docs [afshinm](https://github.com/afshinm) + * website; update homepage + * website; migragtion: emphasize impact of strict docs #1264 + +3.5.6 / 2013-02-14 +================== + + * updated; driver to 1.2.12 + * fixed; properly pass Binary subtype + * fixed; add EventEmitter props to reserved paths #1338 + * fixed; use correct node engine version + * fixed; display empty docs as {} in log output #953 follow up + * improved; "bad $within $box argument" error message + * populate; add unscientific benchmark + * website; add stack overflow to help section + * website; use better code font #1336 [risseraka](https://github.com/risseraka) + * website; clarify where help is available + * website; fix source code links #1272 [floatingLomas](https://github.com/floatingLomas) + * docs; be specific about _id schema option #1103 + * docs; add ensureIndex error handling example + * docs; README + * docs; CONTRIBUTING.md + +3.5.5 / 2013-01-29 +================== + + * updated; driver to 1.2.11 + * removed; old node < 0.6x shims + * fixed; documents with Buffer _ids equality + * fixed; MongooseBuffer properly casts numbers + * fixed; reopening closed connection on alt host/port #1287 + * docs; fixed typo in Readme #1298 [rened](https://github.com/rened) + * docs; fixed typo in migration docs [Prinzhorn](https://github.com/Prinzhorn) + * docs; fixed incorrect annotation in SchemaNumber#min [bilalq](https://github.com/bilalq) + * docs; updated + +3.5.4 / 2013-01-07 +================== + + * changed; "_pres" & "_posts" are now reserved pathnames #1261 + * updated; driver to 1.2.8 + * fixed; exception when reopening a replica set. #1263 [ethankan](https://github.com/ethankan) + * website; updated + +3.5.3 / 2012-12-26 +================== + + * added; support for geo object notation #1257 + * fixed; $within query casting with arrays + * fixed; unix domain socket support #1254 + * updated; driver to 1.2.7 + * updated; muri to 0.0.5 + +3.5.2 / 2012-12-17 +================== + + * fixed; using auth with replica sets #1253 + +3.5.1 / 2012-12-12 +================== + + * fixed; regression when using subdoc with `path` as pathname #1245 [daeq](https://github.com/daeq) + * fixed; safer db option checks + * updated; driver to 1.2.5 + * website; add more examples + * website; clean up old docs + * website; fix prev release urls + * docs; clarify streaming with HTTP responses + +3.5.0 / 2012-12-10 +================== + + * added; paths to CastErrors #1239 + * added; support for mongodb connection string spec #1187 + * added; post validate event + * added; Schema#get (to retrieve schema options) + * added; VersionError #1071 + * added; npmignore [hidekiy](https://github.com/hidekiy) + * update; driver to 1.2.3 + * fixed; stackoverflow in setter #1234 + * fixed; utils.isObject() + * fixed; do not clobber user specified driver writeConcern #1227 + * fixed; always pass current document to post hooks + * fixed; throw error when user attempts to overwrite a model + * fixed; connection.model only caches on connection #1209 + * fixed; respect conn.model() creation when matching global model exists #1209 + * fixed; passing model name + collection name now always honors collection name + * fixed; setting virtual field to an empty object #1154 + * fixed; subclassed MongooseErrors exposure, now available in mongoose.Error.xxxx + * fixed; model.remove() ignoring callback when executed twice [daeq](https://github.com/daeq) #1210 + * docs; add collection option to schema api docs #1222 + * docs; NOTE about db safe options + * docs; add post hooks docs + * docs; connection string options + * docs; middleware is not executed with Model.remove #1241 + * docs; {g,s}etter introspection #777 + * docs; update validation docs + * docs; add link to plugins page + * docs; clarify error returned by unique indexes #1225 + * docs; more detail about disabling autoIndex behavior + * docs; add homepage section to package (npm docs mongoose) + * docs; more detail around collection name pluralization #1193 + * website; add .important css + * website; update models page + * website; update getting started + * website; update quick start + +3.4.0 / 2012-11-10 +================== + + * added; support for generic toJSON/toObject transforms #1160 #1020 #1197 + * added; doc.set() merge support #1148 [NuORDER](https://github.com/NuORDER) + * added; query#add support #1188 [aleclofabbro](https://github.com/aleclofabbro) + * changed; adding invalid nested paths to non-objects throws 4216f14 + * changed; fixed; stop invalid function cloning (internal fix) + * fixed; add query $and casting support #1180 [anotheri](https://github.com/anotheri) + * fixed; overwriting of query arguments #1176 + * docs; fix expires examples + * docs; transforms + * docs; schema `collection` option docs [hermanjunge](https://github.com/hermanjunge) + * website; updated + * tests; added + +3.3.1 / 2012-10-11 +================== + + * fixed; allow goose.connect(uris, dbname, opts) #1144 + * docs; persist API private checked state across page loads + +3.3.0 / 2012-10-10 +================== + + * fixed; passing options as 2nd arg to connect() #1144 + * fixed; race condition after no-op save #1139 + * fixed; schema field selection application in findAndModify #1150 + * fixed; directly setting arrays #1126 + * updated; driver to 1.1.11 + * updated; collection pluralization rules [mrickard](https://github.com/mrickard) + * tests; added + * docs; updated + +3.2.2 / 2012-10-08 +================== + + * updated; driver to 1.1.10 #1143 + * updated; use sliced 0.0.3 + * fixed; do not recast embedded docs unnecessarily + * fixed; expires schema option helper #1132 + * fixed; built in string setters #1131 + * fixed; debug output for Dates/ObjectId properties #1129 + * docs; fixed Javascript syntax error in example [olalonde](https://github.com/olalonde) + * docs; fix toJSON example #1137 + * docs; add ensureIndex production notes + * docs; fix spelling + * docs; add blogposts about v3 + * website; updated + * removed; undocumented inGroupsOf util + * tests; added + +3.2.1 / 2012-09-28 +================== + + * fixed; remove query batchSize option default of 1000 https://github.com/learnboost/mongoose/commit/3edaa8651 + * docs; updated + * website; updated + +3.2.0 / 2012-09-27 +================== + + * added; direct array index assignment with casting support `doc.array.set(index, value)` + * fixed; QueryStream#resume within same tick as pause() #1116 + * fixed; default value validatation #1109 + * fixed; array splice() not casting #1123 + * fixed; default array construction edge case #1108 + * fixed; query casting for inequalities in arrays #1101 [dpatti](https://github.com/dpatti) + * tests; added + * website; more documentation + * website; fixed layout issue #1111 [SlashmanX](https://github.com/SlashmanX) + * website; refactored [guille](https://github.com/guille) + +3.1.2 / 2012-09-10 +================== + + * added; ReadPreferrence schema option #1097 + * updated; driver to 1.1.7 + * updated; default query batchSize to 1000 + * fixed; we now cast the mapReduce query option #1095 + * fixed; $elemMatch+$in with field selection #1091 + * fixed; properly cast $elemMatch+$in conditions #1100 + * fixed; default field application of subdocs #1027 + * fixed; querystream prematurely dying #1092 + * fixed; querystream never resumes when paused at getMore boundries #1092 + * fixed; querystream occasionally emits data events after destroy #1092 + * fixed; remove unnecessary ObjectId creation in querystream + * fixed; allow ne(boolean) again #1093 + * docs; add populate/field selection syntax notes + * docs; add toObject/toJSON options detail + * docs; `read` schema option + +3.1.1 / 2012-08-31 +================== + + * updated; driver to 1.1.6 + +3.1.0 / 2012-08-29 +================== + + * changed; fixed; directly setting nested objects now overwrites entire object (previously incorrectly merged them) + * added; read pref support (mongodb 2.2) 205a709c + * added; aggregate support (mongodb 2.2) f3a5bd3d + * added; virtual {g,s}etter introspection (#1070) + * updated; docs [brettz9](https://github.com/brettz9) + * updated; driver to 1.1.5 + * fixed; retain virtual setter return values (#1069) + +3.0.3 / 2012-08-23 +================== + + * fixed; use of nested paths beginning w/ numbers #1062 + * fixed; query population edge case #1053 #1055 [jfremy](https://github.com/jfremy) + * fixed; simultaneous top and sub level array modifications #1073 + * added; id and _id schema option aliases + tests + * improve debug formatting to allow copy/paste logged queries into mongo shell [eknkc](https://github.com/eknkc) + * docs + +3.0.2 / 2012-08-17 +================== + + * added; missing support for v3 sort/select syntax to findAndModify helpers (#1058) + * fixed; replset fullsetup event emission + * fixed; reconnected event for replsets + * fixed; server reconnection setting discovery + * fixed; compat with non-schema path props using positional notation (#1048) + * fixed; setter/casting order (#665) + * docs; updated + +3.0.1 / 2012-08-11 +================== + + * fixed; throw Error on bad validators (1044) + * fixed; typo in EmbeddedDocument#parentArray [lackac] + * fixed; repair mongoose.SchemaTypes alias + * updated; docs + +3.0.0 / 2012-08-07 +================== + + * removed; old subdocument#commit method + * fixed; setting arrays of matching docs [6924cbc2] + * fixed; doc!remove event now emits in save order as save for consistency + * fixed; pre-save hooks no longer fire on subdocuments when validation fails + * added; subdoc#parent() and subdoc#parentArray() to access subdocument parent objects + * added; query#lean() helper + +3.0.0rc0 / 2012-08-01 +===================== + + * fixed; allow subdoc literal declarations containing "type" pathname (#993) + * fixed; unsetting a default array (#758) + * fixed; boolean $in queries (#998) + * fixed; allow use of `options` as a pathname (#529) + * fixed; `model` is again a permitted schema path name + * fixed; field selection option on subdocs (#1022) + * fixed; handle another edge case with subdoc saving (#975) + * added; emit save err on model if listening + * added; MongoDB TTL collection support (#1006) + * added; $center options support + * added; $nearSphere and $polygon support + * updated; driver version to 1.1.2 + +3.0.0alpha2 / 2012-07-18 +========================= + + * changed; index errors are now emitted on their model and passed to an optional callback (#984) + * fixed; specifying index along with sparse/unique option no longer overwrites (#1004) + * fixed; never swallow connection errors (#618) + * fixed; creating object from model with emded object no longer overwrites defaults [achurkin] (#859) + * fixed; stop needless validation of unchanged/unselected fields (#891) + * fixed; document#equals behavior of objectids (#974) + * fixed; honor the minimize schema option (#978) + * fixed; provide helpful error msgs when reserved schema path is used (#928) + * fixed; callback to conn#disconnect is optional (#875) + * fixed; handle missing protocols in connection urls (#987) + * fixed; validate args to query#where (#969) + * fixed; saving modified/removed subdocs (#975) + * fixed; update with $pull from Mixed array (#735) + * fixed; error with null shard key value + * fixed; allow unsetting enums (#967) + * added; support for manual index creation (#984) + * added; support for disabled auto-indexing (#984) + * added; support for preserving MongooseArray#sort changes (#752) + * added; emit state change events on connection + * added; support for specifying BSON subtype in MongooseBuffer#toObject [jcrugzz] + * added; support for disabled versioning (#977) + * added; implicit "new" support for models and Schemas + +3.0.0alpha1 / 2012-06-15 +========================= + + * removed; doc#commit (use doc#markModified) + * removed; doc.modified getter (#950) + * removed; mongoose{connectSet,createSetConnection}. use connect,createConnection instead + * removed; query alias methods 1149804c + * removed; MongooseNumber + * changed; now creating indexes in background by default + * changed; strict mode now enabled by default (#952) + * changed; doc#modifiedPaths is now a method (#950) + * changed; getters no longer cast (#820); casting happens during set + * fixed; no need to pass updateArg to findOneAndUpdate (#931) + * fixed: utils.merge bug when merging nested non-objects. [treygriffith] + * fixed; strict:throw should produce errors in findAndModify (#963) + * fixed; findAndUpdate no longer overwrites document (#962) + * fixed; setting default DocumentArrays (#953) + * fixed; selection of _id with schema deselection (#954) + * fixed; ensure promise#error emits instanceof Error + * fixed; CursorStream: No stack overflow on any size result (#929) + * fixed; doc#remove now passes safe options + * fixed; invalid use of $set during $pop + * fixed; array#{$pop,$shift} mirror MongoDB behavior + * fixed; no longer test non-required vals in string match (#934) + * fixed; edge case with doc#inspect + * fixed; setter order (#665) + * fixed; setting invalid paths in strict mode (#916) + * fixed; handle docs without id in DocumentArray#id method (#897) + * fixed; do not save virtuals during model.update (#894) + * fixed; sub doc toObject virtuals application (#889) + * fixed; MongooseArray#pull of ObjectId (#881) + * fixed; handle passing db name with any repl set string + * fixed; default application of selected fields (#870) + * fixed; subdoc paths reported in validation errors (#725) + * fixed; incorrect reported num of affected docs in update ops (#862) + * fixed; connection assignment in Model#model (#853) + * fixed; stringifying arrays of docs (#852) + * fixed; modifying subdoc and parent array works (#842) + * fixed; passing undefined to next hook (#785) + * fixed; Query#{update,remove}() works without callbacks (#788) + * fixed; set/updating nested objects by parent pathname (#843) + * fixed; allow null in number arrays (#840) + * fixed; isNew on sub doc after insertion error (#837) + * fixed; if an insert fails, set isNew back to false [boutell] + * fixed; isSelected when only _id is selected (#730) + * fixed; setting an unset default value (#742) + * fixed; query#sort error messaging (#671) + * fixed; support for passing $options with $regex + * added; array of object literal notation in schema creates DocumentArrays + * added; gt,gte,lt,lte query support for arrays (#902) + * added; capped collection support (#938) + * added; document versioning support + * added; inclusion of deselected schema path (#786) + * added; non-atomic array#pop + * added; EmbeddedDocument constructor is now exposed in DocArray#create 7cf8beec + * added; mapReduce support (#678) + * added; support for a configurable minimize option #to{Object,JSON}(option) (#848) + * added; support for strict: `throws` [regality] + * added; support for named schema types (#795) + * added; to{Object,JSON} schema options (#805) + * added; findByIdAnd{Update,Remove}() + * added; findOneAnd{Update,Remove}() + * added; query.setOptions() + * added; instance.update() (#794) + * added; support specifying model in populate() [DanielBaulig] + * added; `lean` query option [gitfy] + * added; multi-atomic support to MongooseArray#nonAtomicPush + * added; support for $set + other $atomic ops on single array + * added; tests + * updated; driver to 1.0.2 + * updated; query.sort() syntax to mirror query.select() + * updated; clearer cast error msg for array numbers + * updated; docs + * updated; doc.clone 3x faster (#950) + * updated; only create _id if necessary (#950) + +2.7.3 / 2012-08-01 +================== + + * fixed; boolean $in queries (#998) + * fixed field selection option on subdocs (#1022) + +2.7.2 / 2012-07-18 +================== + + * fixed; callback to conn#disconnect is optional (#875) + * fixed; handle missing protocols in connection urls (#987) + * fixed; saving modified/removed subdocs (#975) + * updated; tests + +2.7.1 / 2012-06-26 +=================== + + * fixed; sharding: when a document holds a null as a value of the shard key + * fixed; update() using $pull on an array of Mixed (gh-735) + * deprecated; MongooseNumber#{inc, increment, decrement} methods + * tests; now using mocha + +2.7.0 / 2012-06-14 +=================== + + * added; deprecation warnings to methods being removed in 3.x + +2.6.8 / 2012-06-14 +=================== + + * fixed; edge case when using 'options' as a path name (#961) + +2.6.7 / 2012-06-08 +=================== + + * fixed; ensure promise#error always emits instanceof Error + * fixed; selection of _id w/ another excluded path (#954) + * fixed; setting default DocumentArrays (#953) + +2.6.6 / 2012-06-06 +=================== + + * fixed; stack overflow in query stream with large result sets (#929) + * added; $gt, $gte, $lt, $lte support to arrays (#902) + * fixed; pass option `safe` along to doc#remove() calls + +2.6.5 / 2012-05-24 +=================== + + * fixed; do not save virtuals in Model.update (#894) + * added; missing $ prefixed query aliases (going away in 3.x) (#884) [timoxley] + * fixed; setting invalid paths in strict mode (#916) + * fixed; resetting isNew after insert failure (#837) [boutell] + +2.6.4 / 2012-05-15 +=================== + + * updated; backport string regex $options to 2.x + * updated; use driver 1.0.2 (performance improvements) (#914) + * fixed; calling MongooseDocumentArray#id when the doc has no _id (#897) + +2.6.3 / 2012-05-03 +=================== + + * fixed; repl-set connectivity issues during failover on MongoDB 2.0.1 + * updated; driver to 1.0.0 + * fixed; virtuals application of subdocs when using toObject({ virtuals: true }) (#889) + * fixed; MongooseArray#pull of ObjectId correctly updates the array itself (#881) + +2.6.2 / 2012-04-30 +=================== + + * fixed; default field application of selected fields (#870) + +2.6.1 / 2012-04-30 +=================== + + * fixed; connection assignment in mongoose#model (#853, #877) + * fixed; incorrect reported num of affected docs in update ops (#862) + +2.6.0 / 2012-04-19 +=================== + + * updated; hooks.js to 0.2.1 + * fixed; issue with passing undefined to a hook callback. thanks to [chrisleishman] for reporting. + * fixed; updating/setting nested objects in strict schemas (#843) as reported by [kof] + * fixed; Query#{update,remove}() work without callbacks again (#788) + * fixed; modifying subdoc along with parent array $atomic op (#842) + +2.5.14 / 2012-04-13 +=================== + + * fixed; setting an unset default value (#742) + * fixed; doc.isSelected(otherpath) when only _id is selected (#730) + * updated; docs + +2.5.13 / 2012-03-22 +=================== + + * fixed; failing validation of unselected required paths (#730,#713) + * fixed; emitting connection error when only one listener (#759) + * fixed; MongooseArray#splice was not returning values (#784) [chrisleishman] + +2.5.12 / 2012-03-21 +=================== + + * fixed; honor the `safe` option in all ensureIndex calls + * updated; node-mongodb-native driver to 0.9.9-7 + +2.5.11 / 2012-03-15 +=================== + + * added; introspection for getters/setters (#745) + * updated; node-mongodb-driver to 0.9.9-5 + * added; tailable method to Query (#769) [holic] + * fixed; Number min/max validation of null (#764) [btamas] + * added; more flexible user/password connection options (#738) [KarneAsada] + +2.5.10 / 2012-03-06 +=================== + + * updated; node-mongodb-native driver to 0.9.9-4 + * added; Query#comment() + * fixed; allow unsetting arrays + * fixed; hooking the set method of subdocuments (#746) + * fixed; edge case in hooks + * fixed; allow $id and $ref in queries (fixes compatibility with mongoose-dbref) (#749) [richtera] + * added; default path selection to SchemaTypes + +2.5.9 / 2012-02-22 +=================== + + * fixed; properly cast nested atomic update operators for sub-documents + +2.5.8 / 2012-02-21 +=================== + + * added; post 'remove' middleware includes model that was removed (#729) [timoxley] + +2.5.7 / 2012-02-09 +=================== + + * fixed; RegExp validators on node >= v0.6.x + +2.5.6 / 2012-02-09 +=================== + + * fixed; emit errors returned from db.collection() on the connection (were being swallowed) + * added; can add multiple validators in your schema at once (#718) [diogogmt] + * fixed; strict embedded documents (#717) + * updated; docs [niemyjski] + * added; pass number of affected docs back in model.update/save + +2.5.5 / 2012-02-03 +=================== + + * fixed; RangeError: maximum call stack exceed error when removing docs with Number _id (#714) + +2.5.4 / 2012-02-03 +=================== + + * fixed; RangeError: maximum call stack exceed error (#714) + +2.5.3 / 2012-02-02 +=================== + + * added; doc#isSelected(path) + * added; query#equals() + * added; beta sharding support + * added; more descript error msgs (#700) [obeleh] + * added; document.modifiedPaths (#709) [ljharb] + * fixed; only functions can be added as getters/setters (#707,704) [ljharb] + +2.5.2 / 2012-01-30 +=================== + + * fixed; rollback -native driver to 0.9.7-3-5 (was causing timeouts and other replica set weirdness) + * deprecated; MongooseNumber (will be moved to a separate repo for 3.x) + * added; init event is emitted on schemas + +2.5.1 / 2012-01-27 +=================== + + * fixed; honor strict schemas in Model.update (#699) + +2.5.0 / 2012-01-26 +=================== + + * added; doc.toJSON calls toJSON on embedded docs when exists [jerem] + * added; populate support for refs of type Buffer (#686) [jerem] + * added; $all support for ObjectIds and Dates (#690) + * fixed; virtual setter calling on instantiation when strict: true (#682) [hunterloftis] + * fixed; doc construction triggering getters (#685) + * fixed; MongooseBuffer check in deepEquals (#688) + * fixed; range error when using Number _ids with `instance.save()` (#691) + * fixed; isNew on embedded docs edge case (#680) + * updated; driver to 0.9.8-3 + * updated; expose `model()` method within static methods + +2.4.10 / 2012-01-10 +=================== + + * added; optional getter application in .toObject()/.toJSON() (#412) + * fixed; nested $operators in $all queries (#670) + * added; $nor support (#674) + * fixed; bug when adding nested schema (#662) [paulwe] + +2.4.9 / 2012-01-04 +=================== + + * updated; driver to 0.9.7-3-5 to fix Linux performance degradation on some boxes + +2.4.8 / 2011-12-22 +=================== + + * updated; bump -native to 0.9.7.2-5 + * fixed; compatibility with date.js (#646) [chrisleishman] + * changed; undocumented schema "lax" option to "strict" + * fixed; default value population for strict schemas + * updated; the nextTick helper for small performance gain. 1bee2a2 + +2.4.7 / 2011-12-16 +=================== + + * fixed; bug in 2.4.6 with path setting + * updated; bump -native to 0.9.7.2-1 + * added; strict schema option [nw] + +2.4.6 / 2011-12-16 +=================== + + * fixed; conflicting mods on update bug [sirlantis] + * improved; doc.id getter performance + +2.4.5 / 2011-12-14 +=================== + + * fixed; bad MongooseArray behavior in 2.4.2 - 2.4.4 + +2.4.4 / 2011-12-14 +=================== + + * fixed; MongooseArray#doAtomics throwing after sliced + +2.4.3 / 2011-12-14 +=================== + + * updated; system.profile schema for MongoDB 2x + +2.4.2 / 2011-12-12 +=================== + + * fixed; partially populating multiple children of subdocs (#639) [kenpratt] + * fixed; allow Update of numbers to null (#640) [jerem] + +2.4.1 / 2011-12-02 +=================== + + * added; options support for populate() queries + * updated; -native driver to 0.9.7-1.4 + +2.4.0 / 2011-11-29 +=================== + + * added; QueryStreams (#614) + * added; debug print mode for development + * added; $within support to Array queries (#586) [ggoodale] + * added; $centerSphere query support + * fixed; $within support + * added; $unset is now used when setting a path to undefined (#519) + * added; query#batchSize support + * updated; docs + * updated; -native driver to 0.9.7-1.3 (provides Windows support) + +2.3.13 / 2011-11-15 +=================== + + * fixed; required validation for Refs (#612) [ded] + * added; $nearSphere support for Arrays (#610) + +2.3.12 / 2011-11-09 +=================== + + * fixed; regression, objects passed to Model.update should not be changed (#605) + * fixed; regression, empty Model.update should not be executed + +2.3.11 / 2011-11-08 +=================== + + * fixed; using $elemMatch on arrays of Mixed types (#591) + * fixed; allow using $regex when querying Arrays (#599) + * fixed; calling Model.update with no atomic keys (#602) + +2.3.10 / 2011-11-05 +=================== + + * fixed; model.update casting for nested paths works (#542) + +2.3.9 / 2011-11-04 +================== + + * fixed; deepEquals check for MongooseArray returned false + * fixed; reset modified flags of embedded docs after save [gitfy] + * fixed; setting embedded doc with identical values no longer marks modified [gitfy] + * updated; -native driver to 0.9.6.23 [mlazarov] + * fixed; Model.update casting (#542, #545, #479) + * fixed; populated refs no longer fail required validators (#577) + * fixed; populating refs of objects with custom ids works + * fixed; $pop & $unset work with Model.update (#574) + * added; more helpful debugging message for Schema#add (#578) + * fixed; accessing .id when no _id exists now returns null (#590) + +2.3.8 / 2011-10-26 +================== + + * added; callback to query#findOne is now optional (#581) + +2.3.7 / 2011-10-24 +================== + + * fixed; wrapped save/remove callbacks in nextTick to mitigate -native swallowing thrown errors + +2.3.6 / 2011-10-21 +================== + + * fixed; exclusion of embedded doc _id from query results (#541) + +2.3.5 / 2011-10-19 +================== + + * fixed; calling queries without passing a callback works (#569) + * fixed; populate() works with String and Number _ids too (#568) + +2.3.4 / 2011-10-18 +================== + + * added; Model.create now accepts an array as a first arg + * fixed; calling toObject on a DocumentArray with nulls no longer throws + * fixed; calling inspect on a DocumentArray with nulls no longer throws + * added; MongooseArray#unshift support + * fixed; save hooks now fire on embedded documents [gitfy] (#456) + * updated; -native driver to 0.9.6-22 + * fixed; correctly pass $addToSet op instead of $push + * fixed; $addToSet properly detects dates + * fixed; $addToSet with multiple items works + * updated; better node 0.6 Buffer support + +2.3.3 / 2011-10-12 +================== + + * fixed; population conditions in multi-query settings [vedmalex] (#563) + * fixed; now compatible with Node v0.5.x + +2.3.2 / 2011-10-11 +================== + + * fixed; population of null subdoc properties no longer hangs (#561) + +2.3.1 / 2011-10-10 +================== + + * added; support for Query filters to populate() [eneko] + * fixed; querying with number no longer crashes mongodb (#555) [jlbyrey] + * updated; version of -native driver to 0.9.6-21 + * fixed; prevent query callbacks that throw errors from corrupting -native connection state + +2.3.0 / 2011-10-04 +================== + + * fixed; nulls as default values for Boolean now works as expected + * updated; version of -native driver to 0.9.6-20 + +2.2.4 / 2011-10-03 +================== + + * fixed; populate() works when returned array contains undefined/nulls + +2.2.3 / 2011-09-29 +================== + + * updated; version of -native driver to 0.9.6-19 + +2.2.2 / 2011-09-28 +================== + + * added; $regex support to String [davidandrewcope] + * added; support for other contexts like repl etc (#535) + * fixed; clear modified state properly after saving + * added; $addToSet support to Array + +2.2.1 / 2011-09-22 +================== + + * more descript error when casting undefined to string + * updated; version of -native driver to 0.9.6-18 + +2.2.0 / 2011-09-22 +================== + + * fixed; maxListeners warning on schemas with many arrays (#530) + * changed; return / apply defaults based on fields selected in query (#423) + * fixed; correctly detect Mixed types within schema arrays (#532) + +2.1.4 / 2011-09-20 +================== + + * fixed; new private methods that stomped on users code + * changed; finished removing old "compat" support which did nothing + +2.1.3 / 2011-09-16 +================== + + * updated; version of -native driver to 0.9.6-15 + * added; emit `error` on connection when open fails [edwardhotchkiss] + * added; index support to Buffers (thanks justmoon for helping track this down) + * fixed; passing collection name via schema in conn.model() now works (thanks vedmalex for reporting) + +2.1.2 / 2011-09-07 +================== + + * fixed; Query#find with no args no longer throws + +2.1.1 / 2011-09-07 +================== + + * added; support Model.count(fn) + * fixed; compatibility with node >=0.4.0 < 0.4.3 + * added; pass model.options.safe through with .save() so w:2, wtimeout:5000 options work [andrewjstone] + * added; support for $type queries + * added; support for Query#or + * added; more tests + * optimized populate queries + +2.1.0 / 2011-09-01 +================== + + * changed; document#validate is a public method + * fixed; setting number to same value no longer marks modified (#476) [gitfy] + * fixed; Buffers shouldn't have default vals + * added; allow specifying collection name in schema (#470) [ixti] + * fixed; reset modified paths and atomics after saved (#459) + * fixed; set isNew on embedded docs to false after save + * fixed; use self to ensure proper scope of options in doOpenSet (#483) [andrewjstone] + +2.0.4 / 2011-08-29 +================== + + * Fixed; Only send the depopulated ObjectId instead of the entire doc on save (DBRefs) + * Fixed; Properly cast nested array values in Model.update (the data was stored in Mongo incorrectly but recast on document fetch was "fixing" it) + +2.0.3 / 2011-08-28 +================== + + * Fixed; manipulating a populated array no longer causes infinite loop in BSON serializer during save (#477) + * Fixed; populating an empty array no longer hangs foreeeeeeeever (#481) + +2.0.2 / 2011-08-25 +================== + + * Fixed; Maintain query option key order (fixes 'bad hint' error from compound query hints) + +2.0.1 / 2011-08-25 +================== + + * Fixed; do not over-write the doc when no valide props exist in Model.update (#473) + +2.0.0 / 2011-08-24 +=================== + + * Added; support for Buffers [justmoon] + * Changed; improved error handling [maelstrom] + * Removed: unused utils.erase + * Fixed; support for passing other context object into Schemas (#234) [Sija] + * Fixed; getters are no longer circular refs to themselves (#366) + * Removed; unused compat.js + * Fixed; getter/setter scopes are set properly + * Changed; made several private properties more obvious by prefixing _ + * Added; DBRef support [guille] + * Changed; removed support for multiple collection names per model + * Fixed; no longer applying setters when document returned from db + * Changed; default auto_reconnect to true + * Changed; Query#bind no longer clones the query + * Fixed; Model.update now accepts $pull, $inc and friends (#404) + * Added; virtual type option support [nw] + +1.8.4 / 2011-08-21 +=================== + + * Fixed; validation bug when instantiated with non-schema properties (#464) [jmreidy] + +1.8.3 / 2011-08-19 +=================== + + * Fixed; regression in connection#open [jshaw86] + +1.8.2 / 2011-08-17 +=================== + + * fixed; reset connection.readyState after failure [tomseago] + * fixed; can now query positionally for non-embedded docs (arrays of numbers/strings etc) + * fixed; embedded document query casting + * added; support for passing options to node-mongo-native db, server, and replsetserver [tomseago] + +1.8.1 / 2011-08-10 +=================== + + * fixed; ObjectIds were always marked modified + * fixed; can now query using document instances + * fixed; can now query/update using documents with subdocs + +1.8.0 / 2011-08-04 +=================== + + * fixed; can now use $all with String and Number + * fixed; can query subdoc array with $ne: null + * fixed; instance.subdocs#id now works with custom _ids + * fixed; do not apply setters when doc returned from db (change in bad behavior) + +1.7.4 / 2011-07-25 +=================== + + * fixed; sparse now a valid seperate schema option + * fixed; now catching cast errors in queries + * fixed; calling new Schema with object created in vm.runInNewContext now works (#384) [Sija] + * fixed; String enum was disallowing null + * fixed; Find by nested document _id now works (#389) + +1.7.3 / 2011-07-16 +=================== + + * fixed; MongooseArray#indexOf now works with ObjectIds + * fixed; validation scope now set properly (#418) + * fixed; added missing colors dependency (#398) + +1.7.2 / 2011-07-13 +=================== + + * changed; node-mongodb-native driver to v0.9.6.7 + +1.7.1 / 2011-07-12 +=================== + + * changed; roll back node-mongodb-native driver to v0.9.6.4 + +1.7.0 / 2011-07-12 +=================== + + * fixed; collection name misspelling [mathrawka] + * fixed; 2nd param is required for ReplSetServers [kevinmarvin] + * fixed; MongooseArray behaves properly with Object.keys + * changed; node-mongodb-native driver to v0.9.6.6 + * fixed/changed; Mongodb segfault when passed invalid ObjectId (#407) + - This means invalid data passed to the ObjectId constructor will now error + +1.6.0 / 2011-07-07 +=================== + + * changed; .save() errors are now emitted on the instances db instead of the instance 9782463fc + * fixed; errors occurring when creating indexes now properly emit on db + * added; $maxDistance support to MongooseArrays + * fixed; RegExps now work with $all + * changed; node-mongodb-native driver to v0.9.6.4 + * fixed; model names are now accessible via .modelName + * added; Query#slaveOk support + +1.5.0 / 2011-06-27 +=================== + + * changed; saving without a callback no longer ignores the error (@bnoguchi) + * changed; hook-js version bump to 0.1.9 + * changed; node-mongodb-native version bumped to 0.9.6.1 - When .remove() doesn't + return an error, null is no longer passed. + * fixed; two memory leaks (@justmoon) + * added; sparse index support + * added; more ObjectId conditionals (gt, lt, gte, lte) (@phillyqueso) + * added; options are now passed in model#remote (@JerryLuke) + +1.4.0 / 2011-06-10 +=================== + + * bumped hooks-js dependency (fixes issue passing null as first arg to next()) + * fixed; document#inspect now works properly with nested docs + * fixed; 'set' now works as a schema attribute (GH-365) + * fixed; _id is now set properly within pre-init hooks (GH-289) + * added; Query#distinct / Model#distinct support (GH-155) + * fixed; embedded docs now can use instance methods (GH-249) + * fixed; can now overwrite strings conflicting with schema type + +1.3.7 / 2011-06-03 +=================== + + * added MongooseArray#splice support + * fixed; 'path' is now a valid Schema pathname + * improved hooks (utilizing https://github.com/bnoguchi/hooks-js) + * fixed; MongooseArray#$shift now works (never did) + * fixed; Document.modified no longer throws + * fixed; modifying subdoc property sets modified paths for subdoc and parent doc + * fixed; marking subdoc path as modified properly persists the value to the db + * fixed; RexExps can again be saved ( #357 ) + +1.3.6 / 2011-05-18 +=================== + + * fixed; corrected casting for queries against array types + * added; Document#set now accepts Document instances + +1.3.5 / 2011-05-17 +=================== + + * fixed; $ne queries work properly with single vals + * added; #inspect() methods to improve console.log output + +1.3.4 / 2011-05-17 +=================== + + * fixed; find by Date works as expected (#336) + * added; geospatial 2d index support + * added; support for $near (#309) + * updated; node-mongodb-native driver + * fixed; updating numbers work (#342) + * added; better error msg when try to remove an embedded doc without an _id (#307) + * added; support for 'on-the-fly' schemas (#227) + * changed; virtual id getters can now be skipped + * fixed; .index() called on subdoc schema now works as expected + * fixed; db.setProfile() now buffers until the db is open (#340) + +1.3.3 / 2011-04-27 +=================== + + * fixed; corrected query casting on nested mixed types + +1.3.2 / 2011-04-27 +=================== + + * fixed; query hints now retain key order + +1.3.1 / 2011-04-27 +=================== + + * fixed; setting a property on an embedded array no longer overwrites entire array (GH-310) + * fixed; setting nested properties works when sibling prop is named "type" + * fixed; isModified is now much finer grained when .set() is used (GH-323) + * fixed; mongoose.model() and connection.model() now return the Model (GH-308, GH-305) + * fixed; can now use $gt, $lt, $gte, $lte with String schema types (GH-317) + * fixed; .lowercase() -> .toLowerCase() in pluralize() + * fixed; updating an embedded document by index works (GH-334) + * changed; .save() now passes the instance to the callback (GH-294, GH-264) + * added; can now query system.profile and system.indexes collections + * added; db.model('system.profile') is now included as a default Schema + * added; db.setProfiling(level, ms, callback) + * added; Query#hint() support + * added; more tests + * updated node-mongodb-native to 0.9.3 + +1.3.0 / 2011-04-19 +=================== + + * changed; save() callbacks now fire only once on failed validation + * changed; Errors returned from save() callbacks now instances of ValidationError + * fixed; MongooseArray#indexOf now works properly + +1.2.0 / 2011-04-11 +=================== + + * changed; MongooseNumber now casts empty string to null + +1.1.25 / 2011-04-08 +=================== + + * fixed; post init now fires at proper time + +1.1.24 / 2011-04-03 +=================== + + * fixed; pushing an array onto an Array works on existing docs + +1.1.23 / 2011-04-01 +=================== + + * Added Model#model + +1.1.22 / 2011-03-31 +=================== + + * Fixed; $in queries on mixed types now work + +1.1.21 / 2011-03-31 +=================== + + * Fixed; setting object root to null/undefined works + +1.1.20 / 2011-03-31 +=================== + + * Fixed; setting multiple props on null field works + +1.1.19 / 2011-03-31 +=================== + + * Fixed; no longer using $set on paths to an unexisting fields + +1.1.18 / 2011-03-30 +=================== + + * Fixed; non-mixed type object setters work after initd from null + +1.1.17 / 2011-03-30 +=================== + + * Fixed; nested object property access works when root initd with null value + +1.1.16 / 2011-03-28 +=================== + + * Fixed; empty arrays are now saved + +1.1.15 / 2011-03-28 +=================== + + * Fixed; `null` and `undefined` are set atomically. + +1.1.14 / 2011-03-28 +=================== + + * Changed; more forgiving date casting, accepting '' as null. + +1.1.13 / 2011-03-26 +=================== + + * Fixed setting values as `undefined`. + +1.1.12 / 2011-03-26 +=================== + + * Fixed; nested objects now convert to JSON properly + * Fixed; setting nested objects directly now works + * Update node-mongodb-native + +1.1.11 / 2011-03-25 +=================== + + * Fixed for use of `type` as a key. + +1.1.10 / 2011-03-23 +=================== + + * Changed; Make sure to only ensure indexes while connected + +1.1.9 / 2011-03-2 +================== + + * Fixed; Mixed can now default to empty arrays + * Fixed; keys by the name 'type' are now valid + * Fixed; null values retrieved from the database are hydrated as null values. + * Fixed repeated atomic operations when saving a same document twice. + +1.1.8 / 2011-03-23 +================== + + * Fixed 'id' overriding. [bnoguchi] + +1.1.7 / 2011-03-22 +================== + + * Fixed RegExp query casting when querying against an Array of Strings [bnoguchi] + * Fixed getters/setters for nested virtualsl. [bnoguchi] + +1.1.6 / 2011-03-22 +================== + + * Only doValidate when path exists in Schema [aheckmann] + * Allow function defaults for Array types [aheckmann] + * Fix validation hang [aheckmann] + * Fix setting of isRequired of SchemaType [aheckmann] + * Fix SchemaType#required(false) filter [aheckmann] + * More backwards compatibility [aheckmann] + * More tests [aheckmann] + +1.1.5 / 2011-03-14 +================== + + * Added support for `uri, db, fn` and `uri, fn` signatures for replica sets. + * Improved/extended replica set tests. + +1.1.4 / 2011-03-09 +================== + + * Fixed; running an empty Query doesn't throw. [aheckmann] + * Changed; Promise#addBack returns promise. [aheckmann] + * Added streaming cursor support. [aheckmann] + * Changed; Query#update defaults to use$SetOnSave now. [brian] + * Added more docs. + +1.1.3 / 2011-03-04 +================== + + * Added Promise#resolve [aheckmann] + * Fixed backward compatibility with nulls [aheckmann] + * Changed; Query#{run,exec} return promises [aheckmann] + +1.1.2 / 2011-03-03 +================== + + * Restored Query#exec and added notion of default operation [brian] + * Fixed ValidatorError messages [brian] + +1.1.1 / 2011-03-01 +================== + + * Added SchemaType String `lowercase`, `uppercase`, `trim`. + * Public exports (`Model`, `Document`) and tests. + * Added ObjectId casting support for `Document`s. + +1.1.0 / 2011-02-25 +================== + + * Added support for replica sets. + +1.0.16 / 2011-02-18 +=================== + + * Added $nin as another whitelisted $conditional for SchemaArray [brian] + * Changed #with to #where [brian] + * Added ability to use $in conditional with Array types [brian] + +1.0.15 / 2011-02-18 +=================== + + * Added `id` virtual getter for documents to easily access the hexString of + the `_id`. + +1.0.14 / 2011-02-17 +=================== + + * Fix for arrays within subdocuments [brian] + +1.0.13 / 2011-02-16 +=================== + + * Fixed embedded documents saving. + +1.0.12 / 2011-02-14 +=================== + + * Minor refactorings [brian] + +1.0.11 / 2011-02-14 +=================== + + * Query refactor and $ne, $slice, $or, $size, $elemMatch, $nin, $exists support [brian] + * Named scopes sugar [brian] + +1.0.10 / 2011-02-11 +=================== + + * Updated node-mongodb-native driver [thanks John Allen] + +1.0.9 / 2011-02-09 +================== + + * Fixed single member arrays as defaults [brian] + +1.0.8 / 2011-02-09 +================== + + * Fixed for collection-level buffering of commands [gitfy] + * Fixed `Document#toJSON` [dalejefferson] + * Fixed `Connection` authentication [robrighter] + * Fixed clash of accessors in getters/setters [eirikurn] + * Improved `Model#save` promise handling + +1.0.7 / 2011-02-05 +================== + + * Fixed memory leak warnings for test suite on 0.3 + * Fixed querying documents that have an array that contain at least one + specified member. [brian] + * Fixed default value for Array types (fixes GH-210). [brian] + * Fixed example code. + +1.0.6 / 2011-02-03 +================== + + * Fixed `post` middleware + * Fixed; it's now possible to instantiate a model even when one of the paths maps + to an undefined value [brian] + +1.0.5 / 2011-02-02 +================== + + * Fixed; combo $push and $pushAll auto-converts into a $pushAll [brian] + * Fixed; combo $pull and $pullAll auto-converts to a single $pullAll [brian] + * Fixed; $pullAll now removes said members from array before save (so it acts just + like pushAll) [brian] + * Fixed; multiple $pulls and $pushes become a single $pullAll and $pushAll. + Moreover, $pull now modifies the array before save to reflect the immediate + change [brian] + * Added tests for nested shortcut getters [brian] + * Added tests that show that Schemas with nested Arrays don't apply defaults + [brian] + +1.0.4 / 2011-02-02 +================== + + * Added MongooseNumber#toString + * Added MongooseNumber unit tests + +1.0.3 / 2011-02-02 +================== + + * Make sure safe mode works with Model#save + * Changed Schema options: safe mode is now the default + * Updated node-mongodb-native to HEAD + +1.0.2 / 2011-02-02 +================== + + * Added a Model.create shortcut for creating documents. [brian] + * Fixed; we can now instantiate models with hashes that map to at least one + null value. [brian] + * Fixed Schema with more than 2 nested levels. [brian] + +1.0.1 / 2011-02-02 +================== + + * Improved `MongooseNumber`, works almost like the native except for `typeof` + not being `'number'`. diff --git a/5-3/node_modules/mongoose/README.md b/5-3/node_modules/mongoose/README.md new file mode 100644 index 0000000..0f9e958 --- /dev/null +++ b/5-3/node_modules/mongoose/README.md @@ -0,0 +1,317 @@ +# Mongoose + +Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. + +[![Build Status](https://api.travis-ci.org/Automattic/mongoose.png?branch=master)](https://travis-ci.org/Automattic/mongoose) +[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Automattic/mongoose?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose) + +## Documentation + +[mongoosejs.com](http://mongoosejs.com/) + +## Support + + - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose) + - [bug reports](https://github.com/Automattic/mongoose/issues/) + - [help forum](http://groups.google.com/group/mongoose-orm) + - [MongoDB support](https://docs.mongodb.org/manual/support/) + - (irc) #mongoosejs on freenode + +## Plugins + +Check out the [plugins search site](http://plugins.mongoosejs.com/) to see hundreds of related modules from the community. + +Build your own Mongoose plugin through [generator-mongoose-plugin](https://github.com/huei90/generator-mongoose-plugin). + +## Contributors + +View all 100+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors). Stand up and be counted as a [contributor](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md) too! + +## Live Examples + + +## Installation + +First install [node.js](http://nodejs.org/) and [mongodb](https://www.mongodb.org/downloads). Then: + +```sh +$ npm install mongoose +``` + +## Stability + +The current stable branch is [master](https://github.com/Automattic/mongoose/tree/master). The [3.8.x](https://github.com/Automattic/mongoose/tree/3.8.x) branch contains legacy support for the 3.x release series, which is no longer under active development as of September 2015. The [3.8.x docs](http://mongoosejs.com/docs/3.8.x/) are still available. + +## Overview + +### Connecting to MongoDB + +First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`. + +Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`. + +```js +var mongoose = require('mongoose'); + +mongoose.connect('mongodb://localhost/my_database'); +``` + +Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`. + +**Note:** _If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed._ + +**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc. + +### Defining a Model + +Models are defined through the `Schema` interface. + +```js +var Schema = mongoose.Schema, + ObjectId = Schema.ObjectId; + +var BlogPost = new Schema({ + author : ObjectId, + title : String, + body : String, + date : Date +}); +``` + +Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of: + +* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync) +* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default) +* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get) +* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set) +* [Indexes](http://mongoosejs.com/docs/guide.html#indexes) +* [Middleware](http://mongoosejs.com/docs/middleware.html) +* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition +* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition +* [Plugins](http://mongoosejs.com/docs/plugins.html) +* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html) + +The following example shows some of these features: + +```js +var Comment = new Schema({ + name: { type: String, default: 'hahaha' }, + age: { type: Number, min: 18, index: true }, + bio: { type: String, match: /[a-z]/ }, + date: { type: Date, default: Date.now }, + buff: Buffer +}); + +// a setter +Comment.path('name').set(function (v) { + return capitalize(v); +}); + +// middleware +Comment.pre('save', function (next) { + notify(this.get('email')); + next(); +}); +``` + +Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup. + +### Accessing a Model + +Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function + +```js +var myModel = mongoose.model('ModelName'); +``` + +Or just do it all at once + +```js +var MyModel = mongoose.model('ModelName', mySchema); +``` + +The first argument is the _singular_ name of the collection your model is for. **Mongoose automatically looks for the _plural_ version of your model name.** For example, if you use + +```js +var MyModel = mongoose.model('Ticket', mySchema); +``` + +Then Mongoose will create the model for your __tickets__ collection, not your __ticket__ collection. + +Once we have our model, we can then instantiate it, and save it: + +```js +var instance = new MyModel(); +instance.my.key = 'hello'; +instance.save(function (err) { + // +}); +``` + +Or we can find documents from the same collection + +```js +MyModel.find({}, function (err, docs) { + // docs.forEach +}); +``` + +You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html). + +**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created: + +```js +var conn = mongoose.createConnection('your connection string'), + MyModel = conn.model('ModelName', schema), + m = new MyModel; +m.save(); // works +``` + +vs + +```js +var conn = mongoose.createConnection('your connection string'), + MyModel = mongoose.model('ModelName', schema), + m = new MyModel; +m.save(); // does not work b/c the default connection object was never connected +``` + +### Embedded Documents + +In the first example snippet, we defined a key in the Schema that looks like: + +``` +comments: [Comment] +``` + +Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as: + +```js +// retrieve my model +var BlogPost = mongoose.model('BlogPost'); + +// create a blog post +var post = new BlogPost(); + +// create a comment +post.comments.push({ title: 'My comment' }); + +post.save(function (err) { + if (!err) console.log('Success!'); +}); +``` + +The same goes for removing them: + +```js +BlogPost.findById(myId, function (err, post) { + if (!err) { + post.comments[0].remove(); + post.save(function (err) { + // do something + }); + } +}); +``` + +Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap! + + +### Middleware + +See the [docs](http://mongoosejs.com/docs/middleware.html) page. + +#### Intercepting and mutating method arguments + +You can intercept method arguments via middleware. + +For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value: + +```js +schema.pre('set', function (next, path, val, typel) { + // `this` is the current Document + this.emit('set', path, val); + + // Pass control to the next pre + next(); +}); +``` + +Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`: + +```js +.pre(method, function firstPre (next, methodArg1, methodArg2) { + // Mutate methodArg1 + next("altered-" + methodArg1.toString(), methodArg2); +}); + +// pre declaration is chainable +.pre(method, function secondPre (next, methodArg1, methodArg2) { + console.log(methodArg1); + // => 'altered-originalValOfMethodArg1' + + console.log(methodArg2); + // => 'originalValOfMethodArg2' + + // Passing no arguments to `next` automatically passes along the current argument values + // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)` + // and also equivalent to, with the example method arg + // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')` + next(); +}); +``` + +#### Schema gotcha + +`type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation: + +```js +new Schema({ + broken: { type: Boolean }, + asset : { + name: String, + type: String // uh oh, it broke. asset will be interpreted as String + } +}); + +new Schema({ + works: { type: Boolean }, + asset: { + name: String, + type: { type: String } // works. asset is an object with a type property + } +}); +``` + +### Driver access + +The driver being used defaults to [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) and is directly accessible through `YourModel.collection`. **Note**: using the driver directly bypasses all Mongoose power-tools like validation, getters, setters, hooks, etc. + +## API Docs + +Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](https://github.com/tj/dox) +and [acquit](https://github.com/vkarpov15/acquit). + +## License + +Copyright (c) 2010 LearnBoost <dev@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/5-3/node_modules/mongoose/examples/README.md b/5-3/node_modules/mongoose/examples/README.md new file mode 100644 index 0000000..cb32898 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/README.md @@ -0,0 +1,41 @@ +This directory contains runnable sample mongoose programs. + +To run: + + - first install [Node.js](http://nodejs.org/) + - from the root of the project, execute `npm install -d` + - in the example directory, run `npm install -d` + - from the command line, execute: `node example.js`, replacing "example.js" with the name of a program. + + +Goal is to show: + +- ~~global schemas~~ +- ~~GeoJSON schemas / use (with crs)~~ +- text search (once MongoDB removes the "Experimental/beta" label) +- ~~lean queries~~ +- ~~statics~~ +- methods and statics on subdocs +- custom types +- ~~querybuilder~~ +- ~~promises~~ +- accessing driver collection, db +- ~~connecting to replica sets~~ +- connecting to sharded clusters +- enabling a fail fast mode +- on the fly schemas +- storing files +- ~~map reduce~~ +- ~~aggregation~~ +- advanced hooks +- using $elemMatch to return a subset of an array +- query casting +- upserts +- pagination +- express + mongoose session handling +- ~~group by (use aggregation)~~ +- authentication +- schema migration techniques +- converting documents to plain objects (show transforms) +- how to $unset + diff --git a/5-3/node_modules/mongoose/examples/aggregate/aggregate.js b/5-3/node_modules/mongoose/examples/aggregate/aggregate.js new file mode 100644 index 0000000..ccafd49 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/aggregate/aggregate.js @@ -0,0 +1,103 @@ + +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)), + gender: 'Male', + likes: ['movies', 'games', 'dogs'] + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)), + gender: 'Female', + likes: ['movies', 'birds', 'cats'] + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)), + gender: 'Male', + likes: ['tv', 'games', 'rabbits'] + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)), + gender: 'Female', + likes: ['books', 'cats', 'dogs'] + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), + gender: 'Male', + likes: ['glasses', 'wine', 'the night'] + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) throw err; + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handle error + } + + // run an aggregate query that will get all of the people who like a given + // item. To see the full documentation on ways to use the aggregate + // framework, see http://docs.mongodb.org/manual/core/aggregation/ + Person.aggregate( + // select the fields we want to deal with + {$project: {name: 1, likes: 1}}, + // unwind 'likes', which will create a document for each like + {$unwind: '$likes'}, + // group everything by the like and then add each name with that like to + // the set for the like + {$group: { + _id: {likes: '$likes'}, + likers: {$addToSet: '$name'} + }}, + function(err, result) { + if (err) throw err; + console.log(result); + /* [ + { _id: { likes: 'the night' }, likers: [ 'alucard' ] }, + { _id: { likes: 'wine' }, likers: [ 'alucard' ] }, + { _id: { likes: 'books' }, likers: [ 'lilly' ] }, + { _id: { likes: 'glasses' }, likers: [ 'alucard' ] }, + { _id: { likes: 'birds' }, likers: [ 'mary' ] }, + { _id: { likes: 'rabbits' }, likers: [ 'bob' ] }, + { _id: { likes: 'cats' }, likers: [ 'lilly', 'mary' ] }, + { _id: { likes: 'dogs' }, likers: [ 'lilly', 'bill' ] }, + { _id: { likes: 'tv' }, likers: [ 'bob' ] }, + { _id: { likes: 'games' }, likers: [ 'bob', 'bill' ] }, + { _id: { likes: 'movies' }, likers: [ 'mary', 'bill' ] } + ] */ + + cleanup(); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/aggregate/package.json b/5-3/node_modules/mongoose/examples/aggregate/package.json new file mode 100644 index 0000000..53ed2e1 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/aggregate/package.json @@ -0,0 +1,14 @@ +{ + "name": "aggregate-example", + "private": "true", + "version": "0.0.0", + "description": "deps for aggregate example", + "main": "aggregate.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-3/node_modules/mongoose/examples/aggregate/person.js b/5-3/node_modules/mongoose/examples/aggregate/person.js new file mode 100644 index 0000000..607bb07 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/aggregate/person.js @@ -0,0 +1,17 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date, + gender: String, + likes: [String] + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-3/node_modules/mongoose/examples/doc-methods.js b/5-3/node_modules/mongoose/examples/doc-methods.js new file mode 100644 index 0000000..1f648b9 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/doc-methods.js @@ -0,0 +1,77 @@ + +var mongoose = require('mongoose'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Schema + */ + +var CharacterSchema = Schema({ + name: { + type: String, + required: true + }, + health: { + type: Number, + min: 0, + max: 100 + } +}); + +/** + * Methods + */ + +CharacterSchema.methods.attack = function() { + console.log('%s is attacking', this.name); +}; + +/** + * Character model + */ + +var Character = mongoose.model('Character', CharacterSchema); + +/** + * Connect to the database on localhost with + * the default port (27017) + */ + +var dbname = 'mongoose-example-doc-methods-' + ((Math.random() * 10000) | 0); +var uri = 'mongodb://localhost/' + dbname; + +console.log('connecting to %s', uri); + +mongoose.connect(uri, function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + example(); +}); + +/** + * Use case + */ + +function example() { + Character.create({name: 'Link', health: 100}, function(err, link) { + if (err) return done(err); + console.log('found', link); + link.attack(); // 'Link is attacking' + done(); + }); +} + +/** + * Clean up + */ + +function done(err) { + if (err) console.error(err); + mongoose.connection.db.dropDatabase(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/express/README.md b/5-3/node_modules/mongoose/examples/express/README.md new file mode 100644 index 0000000..7ba07b8 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/express/README.md @@ -0,0 +1 @@ +Mongoose + Express examples diff --git a/5-3/node_modules/mongoose/examples/express/connection-sharing/README.md b/5-3/node_modules/mongoose/examples/express/connection-sharing/README.md new file mode 100644 index 0000000..fc709a3 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/express/connection-sharing/README.md @@ -0,0 +1,6 @@ + +To run: + +- Execute `npm install` from this directory +- Execute `node app.js` +- Navigate to `localhost:8000` diff --git a/5-3/node_modules/mongoose/examples/express/connection-sharing/app.js b/5-3/node_modules/mongoose/examples/express/connection-sharing/app.js new file mode 100644 index 0000000..8fb2fee --- /dev/null +++ b/5-3/node_modules/mongoose/examples/express/connection-sharing/app.js @@ -0,0 +1,17 @@ + +var express = require('express'); +var mongoose = require('../../../lib'); + +var uri = 'mongodb://localhost/mongoose-shared-connection'; +global.db = mongoose.createConnection(uri); + +var routes = require('./routes'); + +var app = express(); +app.get('/', routes.home); +app.get('/insert', routes.insert); +app.get('/name', routes.modelName); + +app.listen(8000, function() { + console.log('listening on http://localhost:8000'); +}); diff --git a/5-3/node_modules/mongoose/examples/express/connection-sharing/modelA.js b/5-3/node_modules/mongoose/examples/express/connection-sharing/modelA.js new file mode 100644 index 0000000..78f9ff6 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/express/connection-sharing/modelA.js @@ -0,0 +1,5 @@ +var Schema = require('../../../lib').Schema; +var mySchema = Schema({name: String}); + +/* global db */ +module.exports = db.model('MyModel', mySchema); diff --git a/5-3/node_modules/mongoose/examples/express/connection-sharing/package.json b/5-3/node_modules/mongoose/examples/express/connection-sharing/package.json new file mode 100644 index 0000000..e326165 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/express/connection-sharing/package.json @@ -0,0 +1,14 @@ +{ + "name": "connection-sharing", + "private": "true", + "version": "0.0.0", + "description": "ERROR: No README.md file found!", + "main": "app.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "express": "3.1.1" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-3/node_modules/mongoose/examples/express/connection-sharing/routes.js b/5-3/node_modules/mongoose/examples/express/connection-sharing/routes.js new file mode 100644 index 0000000..35e4f8f --- /dev/null +++ b/5-3/node_modules/mongoose/examples/express/connection-sharing/routes.js @@ -0,0 +1,20 @@ + +var model = require('./modelA'); + +exports.home = function(req, res, next) { + model.find(function(err, docs) { + if (err) return next(err); + res.send(docs); + }); +}; + +exports.modelName = function(req, res) { + res.send('my model name is ' + model.modelName); +}; + +exports.insert = function(req, res, next) { + model.create({name: 'inserting ' + Date.now()}, function(err, doc) { + if (err) return next(err); + res.send(doc); + }); +}; diff --git a/5-3/node_modules/mongoose/examples/geospatial/geoJSONSchema.js b/5-3/node_modules/mongoose/examples/geospatial/geoJSONSchema.js new file mode 100644 index 0000000..f950dea --- /dev/null +++ b/5-3/node_modules/mongoose/examples/geospatial/geoJSONSchema.js @@ -0,0 +1,22 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + // NOTE : This object must conform *precisely* to the geoJSON specification + // you cannot embed a geoJSON doc inside a model or anything like that- IT + // MUST BE VANILLA + var LocationObject = new Schema({ + loc: { + type: {type: String}, + coordinates: [] + } + }); + // define the index + LocationObject.index({loc: '2dsphere'}); + + mongoose.model('Location', LocationObject); +}; diff --git a/5-3/node_modules/mongoose/examples/geospatial/geoJSONexample.js b/5-3/node_modules/mongoose/examples/geospatial/geoJSONexample.js new file mode 100644 index 0000000..8e5dd2b --- /dev/null +++ b/5-3/node_modules/mongoose/examples/geospatial/geoJSONexample.js @@ -0,0 +1,56 @@ +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./geoJSONSchema.js')(); + +var Location = mongoose.model('Location'); + +// define some dummy data +// note: the type can be Point, LineString, or Polygon +var data = [ + {loc: {type: 'Point', coordinates: [-20.0, 5.0]}}, + {loc: {type: 'Point', coordinates: [6.0, 10.0]}}, + {loc: {type: 'Point', coordinates: [34.0, -50.0]}}, + {loc: {type: 'Point', coordinates: [-100.0, 70.0]}}, + {loc: {type: 'Point', coordinates: [38.0, 38.0]}} +]; + + +mongoose.connect('mongodb://localhost/locations', function(err) { + if (err) { + throw err; + } + + Location.on('index', function(err) { + if (err) { + throw err; + } + // create all of the dummy locations + async.each(data, function(item, cb) { + Location.create(item, cb); + }, function(err) { + if (err) { + throw err; + } + // create the location we want to search for + var coords = {type: 'Point', coordinates: [-5, 5]}; + // search for it + Location.find({loc: {$near: coords}}).limit(1).exec(function(err, res) { + if (err) { + throw err; + } + console.log('Closest to %s is %s', JSON.stringify(coords), res); + cleanup(); + }); + }); + }); +}); + +function cleanup() { + Location.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/geospatial/geospatial.js b/5-3/node_modules/mongoose/examples/geospatial/geospatial.js new file mode 100644 index 0000000..6e4b439 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/geospatial/geospatial.js @@ -0,0 +1,100 @@ +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)), + gender: 'Male', + likes: ['movies', 'games', 'dogs'], + loc: [0, 0] + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)), + gender: 'Female', + likes: ['movies', 'birds', 'cats'], + loc: [1, 1] + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)), + gender: 'Male', + likes: ['tv', 'games', 'rabbits'], + loc: [3, 3] + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)), + gender: 'Female', + likes: ['books', 'cats', 'dogs'], + loc: [6, 6] + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), + gender: 'Male', + likes: ['glasses', 'wine', 'the night'], + loc: [10, 10] + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) { + throw err; + } + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handler error + } + + // let's find the closest person to bob + Person.find({name: 'bob'}, function(err, res) { + if (err) { + throw err; + } + + res[0].findClosest(function(err, closest) { + if (err) { + throw err; + } + + console.log('%s is closest to %s', res[0].name, closest); + + + // we can also just query straight off of the model. For more + // information about geospatial queries and indexes, see + // http://docs.mongodb.org/manual/applications/geospatial-indexes/ + var coords = [7, 7]; + Person.find({loc: {$nearSphere: coords}}).limit(1).exec(function(err, res) { + console.log('Closest to %s is %s', coords, res); + cleanup(); + }); + }); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/geospatial/package.json b/5-3/node_modules/mongoose/examples/geospatial/package.json new file mode 100644 index 0000000..75c2a0e --- /dev/null +++ b/5-3/node_modules/mongoose/examples/geospatial/package.json @@ -0,0 +1,14 @@ +{ + "name": "geospatial-example", + "private": "true", + "version": "0.0.0", + "description": "deps for geospatial example", + "main": "geospatial.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-3/node_modules/mongoose/examples/geospatial/person.js b/5-3/node_modules/mongoose/examples/geospatial/person.js new file mode 100644 index 0000000..e816637 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/geospatial/person.js @@ -0,0 +1,27 @@ +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date, + gender: String, + likes: [String], + // define the geospatial field + loc: {type: [Number], index: '2d'} + }); + + // define a method to find the closest person + PersonSchema.methods.findClosest = function(cb) { + return this.model('Person').find({ + loc: {$nearSphere: this.loc}, + name: {$ne: this.name} + }).limit(1).exec(cb); + }; + + mongoose.model('Person', PersonSchema); +}; diff --git a/5-3/node_modules/mongoose/examples/globalschemas/gs_example.js b/5-3/node_modules/mongoose/examples/globalschemas/gs_example.js new file mode 100644 index 0000000..af9ff11 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/globalschemas/gs_example.js @@ -0,0 +1,47 @@ +var mongoose = require('../../lib'); + + +// import the global schema, this can be done in any file that needs the model +require('./person.js')(); + +// grab the person model object +var Person = mongoose.model('Person'); + +// connect to a server to do a quick write / read example + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) { + throw err; + } + + Person.create({ + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)) + }, function(err, bill) { + if (err) { + throw err; + } + console.log('People added to db: %s', bill.toString()); + Person.find({}, function(err, people) { + if (err) { + throw err; + } + + people.forEach(function(person) { + console.log('People in the db: %s', person.toString()); + }); + + // make sure to clean things up after we're done + setTimeout(function() { + cleanup(); + }, 2000); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/globalschemas/person.js b/5-3/node_modules/mongoose/examples/globalschemas/person.js new file mode 100644 index 0000000..39ae725 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/globalschemas/person.js @@ -0,0 +1,14 @@ +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-3/node_modules/mongoose/examples/lean/lean.js b/5-3/node_modules/mongoose/examples/lean/lean.js new file mode 100644 index 0000000..c3e682e --- /dev/null +++ b/5-3/node_modules/mongoose/examples/lean/lean.js @@ -0,0 +1,84 @@ + +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)), + gender: 'Male', + likes: ['movies', 'games', 'dogs'] + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)), + gender: 'Female', + likes: ['movies', 'birds', 'cats'] + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)), + gender: 'Male', + likes: ['tv', 'games', 'rabbits'] + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)), + gender: 'Female', + likes: ['books', 'cats', 'dogs'] + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), + gender: 'Male', + likes: ['glasses', 'wine', 'the night'] + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) throw err; + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handle error + } + + // lean queries return just plain javascript objects, not + // MongooseDocuments. This makes them good for high performance read + // situations + + // when using .lean() the default is true, but you can explicitly set the + // value by passing in a boolean value. IE. .lean(false) + var q = Person.find({age: {$lt: 1000}}).sort('age').limit(2).lean(); + q.exec(function(err, results) { + if (err) throw err; + console.log('Are the results MongooseDocuments?: %s', results[0] instanceof mongoose.Document); + + console.log(results); + cleanup(); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/lean/package.json b/5-3/node_modules/mongoose/examples/lean/package.json new file mode 100644 index 0000000..6ee511d --- /dev/null +++ b/5-3/node_modules/mongoose/examples/lean/package.json @@ -0,0 +1,14 @@ +{ + "name": "lean-example", + "private": "true", + "version": "0.0.0", + "description": "deps for lean example", + "main": "lean.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-3/node_modules/mongoose/examples/lean/person.js b/5-3/node_modules/mongoose/examples/lean/person.js new file mode 100644 index 0000000..b0bd2ed --- /dev/null +++ b/5-3/node_modules/mongoose/examples/lean/person.js @@ -0,0 +1,16 @@ +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date, + gender: String, + likes: [String] + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-3/node_modules/mongoose/examples/mapreduce/mapreduce.js b/5-3/node_modules/mongoose/examples/mapreduce/mapreduce.js new file mode 100644 index 0000000..593d73a --- /dev/null +++ b/5-3/node_modules/mongoose/examples/mapreduce/mapreduce.js @@ -0,0 +1,100 @@ +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)), + gender: 'Male' + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)), + gender: 'Female' + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)), + gender: 'Male' + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)), + gender: 'Female' + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)), + gender: 'Male' + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) throw err; + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handle error + } + + // alright, simple map reduce example. We will find the total ages of each + // gender + + // create the options object + var o = {}; + + o.map = function() { + // in this function, 'this' refers to the current document being + // processed. Return the (gender, age) tuple using + /* global emit */ + emit(this.gender, this.age); + }; + + // the reduce function receives the array of ages that are grouped by the + // id, which in this case is the gender + o.reduce = function(id, ages) { + return Array.sum(ages); + }; + + // other options that can be specified + + // o.query = { age : { $lt : 1000 }}; // the query object + // o.limit = 3; // max number of documents + // o.keeptemp = true; // default is false, specifies whether to keep temp data + // o.finalize = someFunc; // function called after reduce + // o.scope = {}; // the scope variable exposed to map/reduce/finalize + // o.jsMode = true; // default is false, force execution to stay in JS + o.verbose = true; // default is false, provide stats on the job + // o.out = {}; // objects to specify where output goes, by default is + // returned, but can also be stored in a new collection + // see: http://mongoosejs.com/docs/api.html#model_Model.mapReduce + Person.mapReduce(o, function(err, results, stats) { + console.log('map reduce took %d ms', stats.processtime); + console.log(results); + cleanup(); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/mapreduce/package.json b/5-3/node_modules/mongoose/examples/mapreduce/package.json new file mode 100644 index 0000000..4240068 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/mapreduce/package.json @@ -0,0 +1,14 @@ +{ + "name": "map-reduce-example", + "private": "true", + "version": "0.0.0", + "description": "deps for map reduce example", + "main": "mapreduce.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-3/node_modules/mongoose/examples/mapreduce/person.js b/5-3/node_modules/mongoose/examples/mapreduce/person.js new file mode 100644 index 0000000..9e2f084 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/mapreduce/person.js @@ -0,0 +1,16 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date, + gender: String + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-3/node_modules/mongoose/examples/population/population-across-three-collections.js b/5-3/node_modules/mongoose/examples/population/population-across-three-collections.js new file mode 100644 index 0000000..fe6de72 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/population/population-across-three-collections.js @@ -0,0 +1,134 @@ + +var assert = require('assert'); +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; +var ObjectId = mongoose.Types.ObjectId; + +/** + * Connect to the db + */ + +var dbname = 'testing_populateAdInfinitum_' + require('../../lib/utils').random(); +mongoose.connect('localhost', dbname); +mongoose.connection.on('error', function() { + console.error('connection error', arguments); +}); + +/** + * Schemas + */ + +var user = new Schema({ + name: String, + friends: [{ + type: Schema.ObjectId, + ref: 'User' + }] +}); +var User = mongoose.model('User', user); + +var blogpost = Schema({ + title: String, + tags: [String], + author: { + type: Schema.ObjectId, + ref: 'User' + } +}); +var BlogPost = mongoose.model('BlogPost', blogpost); + +/** + * example + */ + +mongoose.connection.on('open', function() { + /** + * Generate data + */ + + var userIds = [new ObjectId, new ObjectId, new ObjectId, new ObjectId]; + var users = []; + + users.push({ + _id: userIds[0], + name: 'mary', + friends: [userIds[1], userIds[2], userIds[3]] + }); + users.push({ + _id: userIds[1], + name: 'bob', + friends: [userIds[0], userIds[2], userIds[3]] + }); + users.push({ + _id: userIds[2], + name: 'joe', + friends: [userIds[0], userIds[1], userIds[3]] + }); + users.push({ + _id: userIds[3], + name: 'sally', + friends: [userIds[0], userIds[1], userIds[2]] + }); + + User.create(users, function(err) { + assert.ifError(err); + + var blogposts = []; + blogposts.push({ + title: 'blog 1', + tags: ['fun', 'cool'], + author: userIds[3] + }); + blogposts.push({ + title: 'blog 2', + tags: ['cool'], + author: userIds[1] + }); + blogposts.push({ + title: 'blog 3', + tags: ['fun', 'odd'], + author: userIds[2] + }); + + BlogPost.create(blogposts, function(err) { + assert.ifError(err); + + /** + * Population + */ + + BlogPost + .find({tags: 'fun'}) + .lean() + .populate('author') + .exec(function(err, docs) { + assert.ifError(err); + + /** + * Populate the populated documents + */ + + var opts = { + path: 'author.friends', + select: 'name', + options: {limit: 2} + }; + + BlogPost.populate(docs, opts, function(err, docs) { + assert.ifError(err); + console.log('populated'); + var s = require('util').inspect(docs, {depth: null, colors: true}); + console.log(s); + done(); + }); + }); + }); + }); +}); + +function done(err) { + if (err) console.error(err.stack); + mongoose.connection.db.dropDatabase(function() { + mongoose.connection.close(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/population/population-basic.js b/5-3/node_modules/mongoose/examples/population/population-basic.js new file mode 100644 index 0000000..252cc53 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/population/population-basic.js @@ -0,0 +1,103 @@ + +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Console schema + */ + +var consoleSchema = Schema({ + name: String, + manufacturer: String, + released: Date +}); +var Console = mongoose.model('Console', consoleSchema); + +/** + * Game schema + */ + +var gameSchema = Schema({ + name: String, + developer: String, + released: Date, + consoles: [{ + type: Schema.Types.ObjectId, + ref: 'Console' + }] +}); +var Game = mongoose.model('Game', gameSchema); + +/** + * Connect to the console database on localhost with + * the default port (27017) + */ + +mongoose.connect('mongodb://localhost/console', function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + createData(); +}); + +/** + * Data generation + */ + +function createData() { + Console.create( + { + name: 'Nintendo 64', + manufacturer: 'Nintendo', + released: 'September 29, 1996' + }, + function(err, nintendo64) { + if (err) return done(err); + + Game.create({ + name: 'Legend of Zelda: Ocarina of Time', + developer: 'Nintendo', + released: new Date('November 21, 1998'), + consoles: [nintendo64] + }, + function(err) { + if (err) return done(err); + example(); + }); + } + ); +} + +/** + * Population + */ + +function example() { + Game + .findOne({name: /^Legend of Zelda/}) + .populate('consoles') + .exec(function(err, ocinara) { + if (err) return done(err); + + console.log( + '"%s" was released for the %s on %s', + ocinara.name, + ocinara.consoles[0].name, + ocinara.released.toLocaleDateString() + ); + + done(); + }); +} + +function done(err) { + if (err) console.error(err); + Console.remove(function() { + Game.remove(function() { + mongoose.disconnect(); + }); + }); +} diff --git a/5-3/node_modules/mongoose/examples/population/population-of-existing-doc.js b/5-3/node_modules/mongoose/examples/population/population-of-existing-doc.js new file mode 100644 index 0000000..c7eadfe --- /dev/null +++ b/5-3/node_modules/mongoose/examples/population/population-of-existing-doc.js @@ -0,0 +1,109 @@ + +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Console schema + */ + +var consoleSchema = Schema({ + name: String, + manufacturer: String, + released: Date +}); +var Console = mongoose.model('Console', consoleSchema); + +/** + * Game schema + */ + +var gameSchema = Schema({ + name: String, + developer: String, + released: Date, + consoles: [{ + type: Schema.Types.ObjectId, + ref: 'Console' + }] +}); +var Game = mongoose.model('Game', gameSchema); + +/** + * Connect to the console database on localhost with + * the default port (27017) + */ + +mongoose.connect('mongodb://localhost/console', function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + createData(); +}); + +/** + * Data generation + */ + +function createData() { + Console.create( + { + name: 'Nintendo 64', + manufacturer: 'Nintendo', + released: 'September 29, 1996' + }, + function(err, nintendo64) { + if (err) return done(err); + + Game.create({ + name: 'Legend of Zelda: Ocarina of Time', + developer: 'Nintendo', + released: new Date('November 21, 1998'), + consoles: [nintendo64] + }, + function(err) { + if (err) return done(err); + example(); + }); + } + ); +} + +/** + * Population + */ + +function example() { + Game + .findOne({name: /^Legend of Zelda/}) + .exec(function(err, ocinara) { + if (err) return done(err); + + console.log('"%s" console _id: %s', ocinara.name, ocinara.consoles[0]); + + // population of existing document + ocinara.populate('consoles', function(err) { + if (err) return done(err); + + console.log( + '"%s" was released for the %s on %s', + ocinara.name, + ocinara.consoles[0].name, + ocinara.released.toLocaleDateString() + ); + + done(); + }); + }); +} + +function done(err) { + if (err) console.error(err); + Console.remove(function() { + Game.remove(function() { + mongoose.disconnect(); + }); + }); +} diff --git a/5-3/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js b/5-3/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js new file mode 100644 index 0000000..61b4e85 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js @@ -0,0 +1,124 @@ + +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Console schema + */ + +var consoleSchema = Schema({ + name: String, + manufacturer: String, + released: Date +}); +var Console = mongoose.model('Console', consoleSchema); + +/** + * Game schema + */ + +var gameSchema = Schema({ + name: String, + developer: String, + released: Date, + consoles: [{ + type: Schema.Types.ObjectId, + ref: 'Console' + }] +}); +var Game = mongoose.model('Game', gameSchema); + +/** + * Connect to the console database on localhost with + * the default port (27017) + */ + +mongoose.connect('mongodb://localhost/console', function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + createData(); +}); + +/** + * Data generation + */ + +function createData() { + Console.create( + { + name: 'Nintendo 64', + manufacturer: 'Nintendo', + released: 'September 29, 1996' + }, + { + name: 'Super Nintendo', + manufacturer: 'Nintendo', + released: 'August 23, 1991' + }, + function(err, nintendo64, superNintendo) { + if (err) return done(err); + + Game.create( + { + name: 'Legend of Zelda: Ocarina of Time', + developer: 'Nintendo', + released: new Date('November 21, 1998'), + consoles: [nintendo64] + }, + { + name: 'Mario Kart', + developer: 'Nintendo', + released: 'September 1, 1992', + consoles: [superNintendo] + }, + function(err) { + if (err) return done(err); + example(); + } + ); + } + ); +} + +/** + * Population + */ + +function example() { + Game + .find({}) + .exec(function(err, games) { + if (err) return done(err); + + console.log('found %d games', games.length); + + var options = {path: 'consoles', select: 'name released -_id'}; + Game.populate(games, options, function(err, games) { + if (err) return done(err); + + games.forEach(function(game) { + console.log( + '"%s" was released for the %s on %s', + game.name, + game.consoles[0].name, + game.released.toLocaleDateString() + ); + }); + + done(); + }); + }); +} + +function done(err) { + if (err) console.error(err); + Console.remove(function() { + Game.remove(function() { + mongoose.disconnect(); + }); + }); +} diff --git a/5-3/node_modules/mongoose/examples/population/population-options.js b/5-3/node_modules/mongoose/examples/population/population-options.js new file mode 100644 index 0000000..59cfd1e --- /dev/null +++ b/5-3/node_modules/mongoose/examples/population/population-options.js @@ -0,0 +1,138 @@ + +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Console schema + */ + +var consoleSchema = Schema({ + name: String, + manufacturer: String, + released: Date +}); +var Console = mongoose.model('Console', consoleSchema); + +/** + * Game schema + */ + +var gameSchema = Schema({ + name: String, + developer: String, + released: Date, + consoles: [{ + type: Schema.Types.ObjectId, + ref: 'Console' + }] +}); +var Game = mongoose.model('Game', gameSchema); + +/** + * Connect to the console database on localhost with + * the default port (27017) + */ + +mongoose.connect('mongodb://localhost/console', function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + createData(); +}); + +/** + * Data generation + */ + +function createData() { + Console.create( + { + name: 'Nintendo 64', + manufacturer: 'Nintendo', + released: 'September 29, 1996' + }, + { + name: 'Super Nintendo', + manufacturer: 'Nintendo', + released: 'August 23, 1991' + }, + { + name: 'XBOX 360', + manufacturer: 'Microsoft', + released: 'November 22, 2005' + }, + function(err, nintendo64, superNintendo, xbox360) { + if (err) return done(err); + + Game.create( + { + name: 'Legend of Zelda: Ocarina of Time', + developer: 'Nintendo', + released: new Date('November 21, 1998'), + consoles: [nintendo64] + }, + { + name: 'Mario Kart', + developer: 'Nintendo', + released: 'September 1, 1992', + consoles: [superNintendo] + }, + { + name: 'Perfect Dark Zero', + developer: 'Rare', + released: 'November 17, 2005', + consoles: [xbox360] + }, + function(err) { + if (err) return done(err); + example(); + } + ); + } + ); +} + +/** + * Population + */ + +function example() { + Game + .find({}) + .populate({ + path: 'consoles', + match: {manufacturer: 'Nintendo'}, + select: 'name', + options: {comment: 'population'} + }) + .exec(function(err, games) { + if (err) return done(err); + + games.forEach(function(game) { + console.log( + '"%s" was released for the %s on %s', + game.name, + game.consoles.length ? game.consoles[0].name : '??', + game.released.toLocaleDateString() + ); + }); + + return done(); + }); +} + +/** + * Clean up + */ + +function done(err) { + if (err) console.error(err); + Console.remove(function() { + Game.remove(function() { + mongoose.disconnect(); + }); + }); +} diff --git a/5-3/node_modules/mongoose/examples/population/population-plain-objects.js b/5-3/node_modules/mongoose/examples/population/population-plain-objects.js new file mode 100644 index 0000000..ba849dc --- /dev/null +++ b/5-3/node_modules/mongoose/examples/population/population-plain-objects.js @@ -0,0 +1,106 @@ + +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +console.log('Running mongoose version %s', mongoose.version); + +/** + * Console schema + */ + +var consoleSchema = Schema({ + name: String, + manufacturer: String, + released: Date +}); +var Console = mongoose.model('Console', consoleSchema); + +/** + * Game schema + */ + +var gameSchema = Schema({ + name: String, + developer: String, + released: Date, + consoles: [{ + type: Schema.Types.ObjectId, + ref: 'Console' + }] +}); +var Game = mongoose.model('Game', gameSchema); + +/** + * Connect to the console database on localhost with + * the default port (27017) + */ + +mongoose.connect('mongodb://localhost/console', function(err) { + // if we failed to connect, abort + if (err) throw err; + + // we connected ok + createData(); +}); + +/** + * Data generation + */ + +function createData() { + Console.create( + { + name: 'Nintendo 64', + manufacturer: 'Nintendo', + released: 'September 29, 1996' + }, + function(err, nintendo64) { + if (err) return done(err); + + Game.create( + { + name: 'Legend of Zelda: Ocarina of Time', + developer: 'Nintendo', + released: new Date('November 21, 1998'), + consoles: [nintendo64] + }, + function(err) { + if (err) return done(err); + example(); + } + ); + } + ); +} + +/** + * Population + */ + +function example() { + Game + .findOne({name: /^Legend of Zelda/}) + .populate('consoles') + .lean() // just return plain objects, not documents wrapped by mongoose + .exec(function(err, ocinara) { + if (err) return done(err); + + console.log( + '"%s" was released for the %s on %s', + ocinara.name, + ocinara.consoles[0].name, + ocinara.released.toLocaleDateString() + ); + + done(); + }); +} + +function done(err) { + if (err) console.error(err); + Console.remove(function() { + Game.remove(function() { + mongoose.disconnect(); + }); + }); +} diff --git a/5-3/node_modules/mongoose/examples/promises/package.json b/5-3/node_modules/mongoose/examples/promises/package.json new file mode 100644 index 0000000..1983250 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/promises/package.json @@ -0,0 +1,14 @@ +{ + "name": "promise-example", + "private": "true", + "version": "0.0.0", + "description": "deps for promise example", + "main": "promise.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-3/node_modules/mongoose/examples/promises/person.js b/5-3/node_modules/mongoose/examples/promises/person.js new file mode 100644 index 0000000..40e2bf1 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/promises/person.js @@ -0,0 +1,15 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-3/node_modules/mongoose/examples/promises/promise.js b/5-3/node_modules/mongoose/examples/promises/promise.js new file mode 100644 index 0000000..fd1ff7a --- /dev/null +++ b/5-3/node_modules/mongoose/examples/promises/promise.js @@ -0,0 +1,94 @@ +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)) + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)) + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)) + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)) + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)) + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) { + throw err; + } + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handle error + } + + // create a promise (get one from the query builder) + var prom = Person.find({age: {$lt: 1000}}).exec(); + + // add a callback on the promise. This will be called on both error and + // complete + prom.addBack(function() { + console.log('completed'); + }); + + // add a callback that is only called on complete (success) events + prom.addCallback(function() { + console.log('Successful Completion!'); + }); + + // add a callback that is only called on err (rejected) events + prom.addErrback(function() { + console.log('Fail Boat'); + }); + + // you can chain things just like in the promise/A+ spec + // note: each then() is returning a new promise, so the above methods + // that we defined will all fire after the initial promise is fulfilled + prom.then(function(people) { + // just getting the stuff for the next query + var ids = people.map(function(p) { + return p._id; + }); + + // return the next promise + return Person.find({_id: {$nin: ids}}).exec(); + }).then(function(oldest) { + console.log('Oldest person is: %s', oldest); + }).then(cleanup); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/querybuilder/package.json b/5-3/node_modules/mongoose/examples/querybuilder/package.json new file mode 100644 index 0000000..1a3450a --- /dev/null +++ b/5-3/node_modules/mongoose/examples/querybuilder/package.json @@ -0,0 +1,14 @@ +{ + "name": "query-builder-example", + "private": "true", + "version": "0.0.0", + "description": "deps for query builder example", + "main": "querybuilder.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-3/node_modules/mongoose/examples/querybuilder/person.js b/5-3/node_modules/mongoose/examples/querybuilder/person.js new file mode 100644 index 0000000..40e2bf1 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/querybuilder/person.js @@ -0,0 +1,15 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-3/node_modules/mongoose/examples/querybuilder/querybuilder.js b/5-3/node_modules/mongoose/examples/querybuilder/querybuilder.js new file mode 100644 index 0000000..723a357 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/querybuilder/querybuilder.js @@ -0,0 +1,79 @@ + +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)) + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)) + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)) + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)) + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)) + } +]; + + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) throw err; + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) throw err; + + // when querying data, instead of providing a callback, you can instead + // leave that off and get a query object returned + var query = Person.find({age: {$lt: 1000}}); + + // this allows you to continue applying modifiers to it + query.sort('birthday'); + query.select('name'); + + // you can chain them together as well + // a full list of methods can be found: + // http://mongoosejs.com/docs/api.html#query-js + query.where('age').gt(21); + + // finally, when ready to execute the query, call the exec() function + query.exec(function(err, results) { + if (err) throw err; + + console.log(results); + + cleanup(); + }); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/replicasets/package.json b/5-3/node_modules/mongoose/examples/replicasets/package.json new file mode 100644 index 0000000..927dfd2 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/replicasets/package.json @@ -0,0 +1,14 @@ +{ + "name": "replica-set-example", + "private": "true", + "version": "0.0.0", + "description": "deps for replica set example", + "main": "querybuilder.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "dependencies": { "async": "*" }, + "repository": "", + "author": "", + "license": "BSD" +} diff --git a/5-3/node_modules/mongoose/examples/replicasets/person.js b/5-3/node_modules/mongoose/examples/replicasets/person.js new file mode 100644 index 0000000..40e2bf1 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/replicasets/person.js @@ -0,0 +1,15 @@ + +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date + }); + mongoose.model('Person', PersonSchema); +}; diff --git a/5-3/node_modules/mongoose/examples/replicasets/replica-sets.js b/5-3/node_modules/mongoose/examples/replicasets/replica-sets.js new file mode 100644 index 0000000..6aa27b5 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/replicasets/replica-sets.js @@ -0,0 +1,71 @@ + +// import async to make control flow simplier +var async = require('async'); + +// import the rest of the normal stuff +var mongoose = require('../../lib'); + +require('./person.js')(); + +var Person = mongoose.model('Person'); + +// define some dummy data +var data = [ + { + name: 'bill', + age: 25, + birthday: new Date().setFullYear((new Date().getFullYear() - 25)) + }, + { + name: 'mary', + age: 30, + birthday: new Date().setFullYear((new Date().getFullYear() - 30)) + }, + { + name: 'bob', + age: 21, + birthday: new Date().setFullYear((new Date().getFullYear() - 21)) + }, + { + name: 'lilly', + age: 26, + birthday: new Date().setFullYear((new Date().getFullYear() - 26)) + }, + { + name: 'alucard', + age: 1000, + birthday: new Date().setFullYear((new Date().getFullYear() - 1000)) + } +]; + + +// to connect to a replica set, pass in the comma delimited uri and optionally +// any connection options such as the rs_name. +var opts = { + replSet: {rs_name: 'rs0'} +}; +mongoose.connect('mongodb://localhost:27018/persons,localhost:27019,localhost:27020', opts, function(err) { + if (err) throw err; + + // create all of the dummy people + async.each(data, function(item, cb) { + Person.create(item, cb); + }, function(err) { + if (err) { + // handle error + } + + // create and delete some data + var prom = Person.find({age: {$lt: 1000}}).exec(); + + prom.then(function(people) { + console.log('young people: %s', people); + }).then(cleanup); + }); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/examples/schema/schema.js b/5-3/node_modules/mongoose/examples/schema/schema.js new file mode 100644 index 0000000..5bc99ae --- /dev/null +++ b/5-3/node_modules/mongoose/examples/schema/schema.js @@ -0,0 +1,119 @@ +/** + * Module dependencies. + */ + +var mongoose = require('../../lib'), + Schema = mongoose.Schema; + +/** + * Schema definition + */ + +// recursive embedded-document schema + +var Comment = new Schema(); + +Comment.add({ + title: { + type: String, + index: true + }, + date: Date, + body: String, + comments: [Comment] +}); + +var BlogPost = new Schema({ + title: { + type: String, + index: true + }, + slug: { + type: String, + lowercase: true, + trim: true + }, + date: Date, + buf: Buffer, + comments: [Comment], + creator: Schema.ObjectId +}); + +var Person = new Schema({ + name: { + first: String, + last: String + }, + email: { + type: String, + required: true, + index: { + unique: true, + sparse: true + } + }, + alive: Boolean +}); + +/** + * Accessing a specific schema type by key + */ + +BlogPost.path('date') +.default(function() { + return new Date(); +}) +.set(function(v) { + return v === 'now' ? new Date() : v; +}); + +/** + * Pre hook. + */ + +BlogPost.pre('save', function(next, done) { + /* global emailAuthor */ + emailAuthor(done); // some async function + next(); +}); + +/** + * Methods + */ + +BlogPost.methods.findCreator = function(callback) { + return this.db.model('Person').findById(this.creator, callback); +}; + +BlogPost.statics.findByTitle = function(title, callback) { + return this.find({title: title}, callback); +}; + +BlogPost.methods.expressiveQuery = function(creator, date, callback) { + return this.find('creator', creator).where('date').gte(date).run(callback); +}; + +/** + * Plugins + */ + +function slugGenerator(options) { + options = options || {}; + var key = options.key || 'title'; + + return function slugGenerator(schema) { + schema.path(key).set(function(v) { + this.slug = v.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/-+/g, ''); + return v; + }); + }; +} + +BlogPost.plugin(slugGenerator()); + +/** + * Define model. + */ + +mongoose.model('BlogPost', BlogPost); +mongoose.model('Person', Person); diff --git a/5-3/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js b/5-3/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js new file mode 100644 index 0000000..284b478 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js @@ -0,0 +1,27 @@ + +// modules +var mongoose = require('../../../lib'); +var Schema = mongoose.Schema; + +// parse json +var raw = require('./schema.json'); + +// create a schema +var timeSignatureSchema = Schema(raw); + +// compile the model +var TimeSignature = mongoose.model('TimeSignatures', timeSignatureSchema); + +// create a TimeSignature document +var threeFour = new TimeSignature({ + count: 3, + unit: 4, + description: '3/4', + additive: false, + created: new Date, + links: ['http://en.wikipedia.org/wiki/Time_signature'], + user_id: '518d31a0ef32bbfa853a9814' +}); + +// print its description +console.log(threeFour); diff --git a/5-3/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json b/5-3/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json new file mode 100644 index 0000000..5afc626 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json @@ -0,0 +1,9 @@ +{ + "count": "number", + "unit": "number", + "description": "string", + "links": ["string"], + "created": "date", + "additive": "boolean", + "user_id": "ObjectId" +} diff --git a/5-3/node_modules/mongoose/examples/statics/person.js b/5-3/node_modules/mongoose/examples/statics/person.js new file mode 100644 index 0000000..a93b8c6 --- /dev/null +++ b/5-3/node_modules/mongoose/examples/statics/person.js @@ -0,0 +1,20 @@ +// import the necessary modules +var mongoose = require('../../lib'); +var Schema = mongoose.Schema; + +// create an export function to encapsulate the model creation +module.exports = function() { + // define schema + var PersonSchema = new Schema({ + name: String, + age: Number, + birthday: Date + }); + + // define a static + PersonSchema.statics.findPersonByName = function(name, cb) { + this.find({name: new RegExp(name, 'i')}, cb); + }; + + mongoose.model('Person', PersonSchema); +}; diff --git a/5-3/node_modules/mongoose/examples/statics/statics.js b/5-3/node_modules/mongoose/examples/statics/statics.js new file mode 100644 index 0000000..610b2aa --- /dev/null +++ b/5-3/node_modules/mongoose/examples/statics/statics.js @@ -0,0 +1,41 @@ +var mongoose = require('../../lib'); + + +// import the schema +require('./person.js')(); + +// grab the person model object +var Person = mongoose.model('Person'); + +// connect to a server to do a quick write / read example + +mongoose.connect('mongodb://localhost/persons', function(err) { + if (err) { + throw err; + } + + Person.create({name: 'bill', age: 25, birthday: new Date().setFullYear((new Date().getFullYear() - 25))}, + function(err, bill) { + if (err) { + throw err; + } + console.log('People added to db: %s', bill.toString()); + + // using the static + Person.findPersonByName('bill', function(err, result) { + if (err) { + throw err; + } + + console.log(result); + cleanup(); + }); + } + ); +}); + +function cleanup() { + Person.remove(function() { + mongoose.disconnect(); + }); +} diff --git a/5-3/node_modules/mongoose/index.js b/5-3/node_modules/mongoose/index.js new file mode 100644 index 0000000..e7e6278 --- /dev/null +++ b/5-3/node_modules/mongoose/index.js @@ -0,0 +1,7 @@ + +/** + * Export lib/mongoose + * + */ + +module.exports = require('./lib/'); diff --git a/5-3/node_modules/mongoose/lib/ES6Promise.js b/5-3/node_modules/mongoose/lib/ES6Promise.js new file mode 100644 index 0000000..13371ac --- /dev/null +++ b/5-3/node_modules/mongoose/lib/ES6Promise.js @@ -0,0 +1,26 @@ +/** + * ES6 Promise wrapper constructor. + * + * Promises are returned from executed queries. Example: + * + * var query = Candy.find({ bar: true }); + * var promise = query.exec(); + * + * DEPRECATED. Mongoose 5.0 will use native promises by default (or bluebird, + * if native promises are not present) but still + * support plugging in your own ES6-compatible promises library. Mongoose 5.0 + * will **not** support mpromise. + * + * @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature + * @api public + */ + +function ES6Promise() { + throw new Error('Can\'t use ES6 promise with mpromise style constructor'); +} + +ES6Promise.use = function(Promise) { + ES6Promise.ES6 = Promise; +}; + +module.exports = ES6Promise; diff --git a/5-3/node_modules/mongoose/lib/aggregate.js b/5-3/node_modules/mongoose/lib/aggregate.js new file mode 100644 index 0000000..fd2c2fc --- /dev/null +++ b/5-3/node_modules/mongoose/lib/aggregate.js @@ -0,0 +1,623 @@ +/*! + * Module dependencies + */ + +var util = require('util'); +var utils = require('./utils'); +var PromiseProvider = require('./promise_provider'); +var Query = require('./query'); +var read = Query.prototype.read; + +/** + * Aggregate constructor used for building aggregation pipelines. + * + * ####Example: + * + * new Aggregate(); + * new Aggregate({ $project: { a: 1, b: 1 } }); + * new Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); + * new Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); + * + * Returned when calling Model.aggregate(). + * + * ####Example: + * + * Model + * .aggregate({ $match: { age: { $gte: 21 }}}) + * .unwind('tags') + * .exec(callback) + * + * ####Note: + * + * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). + * - Requires MongoDB >= 2.1 + * - Mongoose does **not** cast pipeline stages. `new Aggregate({ $match: { _id: '00000000000000000000000a' } });` will not work unless `_id` is a string in the database. Use `new Aggregate({ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } });` instead. + * + * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ + * @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate + * @param {Object|Array} [ops] aggregation operator(s) or operator array + * @api public + */ + +function Aggregate() { + this._pipeline = []; + this._model = undefined; + this.options = undefined; + + if (arguments.length === 1 && util.isArray(arguments[0])) { + this.append.apply(this, arguments[0]); + } else { + this.append.apply(this, arguments); + } +} + +/** + * Binds this aggregate to a model. + * + * @param {Model} model the model to which the aggregate is to be bound + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.model = function(model) { + this._model = model; + return this; +}; + +/** + * Appends new operators to this aggregate pipeline + * + * ####Examples: + * + * aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); + * + * // or pass an array + * var pipeline = [{ $match: { daw: 'Logic Audio X' }} ]; + * aggregate.append(pipeline); + * + * @param {Object} ops operator(s) to append + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.append = function() { + var args = (arguments.length === 1 && util.isArray(arguments[0])) + ? arguments[0] + : utils.args(arguments); + + if (!args.every(isOperator)) { + throw new Error('Arguments must be aggregate pipeline operators'); + } + + this._pipeline = this._pipeline.concat(args); + + return this; +}; + +/** + * Appends a new $project operator to this aggregate pipeline. + * + * Mongoose query [selection syntax](#query_Query-select) is also supported. + * + * ####Examples: + * + * // include a, include b, exclude _id + * aggregate.project("a b -_id"); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * aggregate.project({a: 1, b: 1, _id: 0}); + * + * // reshaping documents + * aggregate.project({ + * newField: '$b.nested' + * , plusTen: { $add: ['$val', 10]} + * , sub: { + * name: '$a' + * } + * }) + * + * // etc + * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); + * + * @param {Object|String} arg field specification + * @see projection http://docs.mongodb.org/manual/reference/aggregation/project/ + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.project = function(arg) { + var fields = {}; + + if (typeof arg === 'object' && !util.isArray(arg)) { + Object.keys(arg).forEach(function(field) { + fields[field] = arg[field]; + }); + } else if (arguments.length === 1 && typeof arg === 'string') { + arg.split(/\s+/).forEach(function(field) { + if (!field) { + return; + } + var include = field[0] === '-' ? 0 : 1; + if (include === 0) { + field = field.substring(1); + } + fields[field] = include; + }); + } else { + throw new Error('Invalid project() argument. Must be string or object'); + } + + return this.append({$project: fields}); +}; + +/** + * Appends a new custom $group operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.group({ _id: "$department" }); + * + * @see $group http://docs.mongodb.org/manual/reference/aggregation/group/ + * @method group + * @memberOf Aggregate + * @param {Object} arg $group operator contents + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new custom $match operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.match({ department: { $in: [ "sales", "engineering" } } }); + * + * @see $match http://docs.mongodb.org/manual/reference/aggregation/match/ + * @method match + * @memberOf Aggregate + * @param {Object} arg $match operator contents + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new $skip operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.skip(10); + * + * @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/ + * @method skip + * @memberOf Aggregate + * @param {Number} num number of records to skip before next stage + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new $limit operator to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.limit(10); + * + * @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/ + * @method limit + * @memberOf Aggregate + * @param {Number} num maximum number of records to pass to the next stage + * @return {Aggregate} + * @api public + */ + +/** + * Appends a new $geoNear operator to this aggregate pipeline. + * + * ####NOTE: + * + * **MUST** be used as the first operator in the pipeline. + * + * ####Examples: + * + * aggregate.near({ + * near: [40.724, -73.997], + * distanceField: "dist.calculated", // required + * maxDistance: 0.008, + * query: { type: "public" }, + * includeLocs: "dist.location", + * uniqueDocs: true, + * num: 5 + * }); + * + * @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/ + * @method near + * @memberOf Aggregate + * @param {Object} parameters + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.near = function(arg) { + var op = {}; + op.$geoNear = arg; + return this.append(op); +}; + +/*! + * define methods + */ + +'group match skip limit out'.split(' ').forEach(function($operator) { + Aggregate.prototype[$operator] = function(arg) { + var op = {}; + op['$' + $operator] = arg; + return this.append(op); + }; +}); + +/** + * Appends new custom $unwind operator(s) to this aggregate pipeline. + * + * Note that the `$unwind` operator requires the path name to start with '$'. + * Mongoose will prepend '$' if the specified field doesn't start '$'. + * + * ####Examples: + * + * aggregate.unwind("tags"); + * aggregate.unwind("a", "b", "c"); + * + * @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/ + * @param {String} fields the field(s) to unwind + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.unwind = function() { + var args = utils.args(arguments); + + return this.append.apply(this, args.map(function(arg) { + return {$unwind: (arg && arg.charAt(0) === '$') ? arg : '$' + arg}; + })); +}; + +/** + * Appends new custom $lookup operator(s) to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' }); + * + * @see $lookup https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/#pipe._S_lookup + * @param {Object} options to $lookup as described in the above link + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.lookup = function(options) { + return this.append({$lookup: options}); +}; + +/** + * Appends new custom $sample operator(s) to this aggregate pipeline. + * + * ####Examples: + * + * aggregate.sample(3); // Add a pipeline that picks 3 random documents + * + * @see $sample https://docs.mongodb.org/manual/reference/operator/aggregation/sample/#pipe._S_sample + * @param {Number} size number of random documents to pick + * @return {Aggregate} + * @api public + */ + +Aggregate.prototype.sample = function(size) { + return this.append({$sample: {size: size}}); +}; + +/** + * Appends a new $sort operator to this aggregate pipeline. + * + * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + * + * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + * + * ####Examples: + * + * // these are equivalent + * aggregate.sort({ field: 'asc', test: -1 }); + * aggregate.sort('field -test'); + * + * @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/ + * @param {Object|String} arg + * @return {Aggregate} this + * @api public + */ + +Aggregate.prototype.sort = function(arg) { + // TODO refactor to reuse the query builder logic + + var sort = {}; + + if (arg.constructor.name === 'Object') { + var desc = ['desc', 'descending', -1]; + Object.keys(arg).forEach(function(field) { + sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1; + }); + } else if (arguments.length === 1 && typeof arg === 'string') { + arg.split(/\s+/).forEach(function(field) { + if (!field) { + return; + } + var ascend = field[0] === '-' ? -1 : 1; + if (ascend === -1) { + field = field.substring(1); + } + sort[field] = ascend; + }); + } else { + throw new TypeError('Invalid sort() argument. Must be a string or object.'); + } + + return this.append({$sort: sort}); +}; + +/** + * Sets the readPreference option for the aggregation query. + * + * ####Example: + * + * Model.aggregate(..).read('primaryPreferred').exec(callback) + * + * @param {String} pref one of the listed preference options or their aliases + * @param {Array} [tags] optional tags for this query + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + */ + +Aggregate.prototype.read = function(pref, tags) { + if (!this.options) { + this.options = {}; + } + read.call(this, pref, tags); + return this; +}; + +/** + * Execute the aggregation with explain + * + * ####Example: + * + * Model.aggregate(..).explain(callback) + * + * @param {Function} callback + * @return {Promise} + */ + +Aggregate.prototype.explain = function(callback) { + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + if (!_this._pipeline.length) { + var err = new Error('Aggregate has empty pipeline'); + if (callback) { + callback(err); + } + reject(err); + return; + } + + prepareDiscriminatorPipeline(_this); + + _this._model + .collection + .aggregate(_this._pipeline, _this.options || {}) + .explain(function(error, result) { + if (error) { + if (callback) { + callback(error); + } + reject(error); + return; + } + + if (callback) { + callback(null, result); + } + resolve(result); + }); + }); +}; + +/** + * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) + * + * ####Example: + * + * Model.aggregate(..).allowDiskUse(true).exec(callback) + * + * @param {Boolean} value Should tell server it can use hard drive to store data during aggregation. + * @param {Array} [tags] optional tags for this query + * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ + */ + +Aggregate.prototype.allowDiskUse = function(value) { + if (!this.options) { + this.options = {}; + } + this.options.allowDiskUse = value; + return this; +}; + +/** + * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). + * Note the different syntax below: .exec() returns a cursor object, and no callback + * is necessary. + * + * ####Example: + * + * var cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec(); + * cursor.each(function(error, doc) { + * // use doc + * }); + * + * @param {Object} options set the cursor batch size + * @see mongodb http://mongodb.github.io/node-mongodb-native/2.0/api/AggregationCursor.html + */ + +Aggregate.prototype.cursor = function(options) { + if (!this.options) { + this.options = {}; + } + this.options.cursor = options || {}; + return this; +}; + +/** + * Executes the aggregate pipeline on the currently bound Model. + * + * ####Example: + * + * aggregate.exec(callback); + * + * // Because a promise is returned, the `callback` is optional. + * var promise = aggregate.exec(); + * promise.then(..); + * + * @see Promise #promise_Promise + * @param {Function} [callback] + * @return {Promise} + * @api public + */ + +Aggregate.prototype.exec = function(callback) { + if (!this._model) { + throw new Error('Aggregate not bound to any Model'); + } + var _this = this; + var Promise = PromiseProvider.get(); + + if (this.options && this.options.cursor) { + if (this.options.cursor.async) { + return new Promise.ES6(function(resolve) { + if (!_this._model.collection.buffer) { + process.nextTick(function() { + var cursor = _this._model.collection. + aggregate(_this._pipeline, _this.options || {}); + resolve(cursor); + callback && callback(cursor); + }); + return; + } + _this._model.collection.emitter.once('queue', function() { + var cursor = _this._model.collection. + aggregate(_this._pipeline, _this.options || {}); + resolve(cursor); + callback && callback(null, cursor); + }); + }); + } + return this._model.collection. + aggregate(this._pipeline, this.options || {}); + } + + return new Promise.ES6(function(resolve, reject) { + if (!_this._pipeline.length) { + var err = new Error('Aggregate has empty pipeline'); + if (callback) { + callback(err); + } + reject(err); + return; + } + + prepareDiscriminatorPipeline(_this); + + _this._model + .collection + .aggregate(_this._pipeline, _this.options || {}, function(error, result) { + if (error) { + if (callback) { + callback(error); + } + reject(error); + return; + } + + if (callback) { + callback(null, result); + } + resolve(result); + }); + }); +}; + +/*! + * Helpers + */ + +/** + * Checks whether an object is likely a pipeline operator + * + * @param {Object} obj object to check + * @return {Boolean} + * @api private + */ + +function isOperator(obj) { + var k; + + if (typeof obj !== 'object') { + return false; + } + + k = Object.keys(obj); + + return k.length === 1 && k + .some(function(key) { + return key[0] === '$'; + }); +} + +/*! + * Adds the appropriate `$match` pipeline step to the top of an aggregate's + * pipeline, should it's model is a non-root discriminator type. This is + * analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`. + * + * @param {Aggregate} aggregate Aggregate to prepare + */ + +function prepareDiscriminatorPipeline(aggregate) { + var schema = aggregate._model.schema, + discriminatorMapping = schema && schema.discriminatorMapping; + + if (discriminatorMapping && !discriminatorMapping.isRoot) { + var originalPipeline = aggregate._pipeline, + discriminatorKey = discriminatorMapping.key, + discriminatorValue = discriminatorMapping.value; + + // If the first pipeline stage is a match and it doesn't specify a `__t` + // key, add the discriminator key to it. This allows for potential + // aggregation query optimizations not to be disturbed by this feature. + if (originalPipeline[0] && originalPipeline[0].$match && !originalPipeline[0].$match[discriminatorKey]) { + originalPipeline[0].$match[discriminatorKey] = discriminatorValue; + // `originalPipeline` is a ref, so there's no need for + // aggregate._pipeline = originalPipeline + } else if (originalPipeline[0] && originalPipeline[0].$geoNear) { + originalPipeline[0].$geoNear.query = + originalPipeline[0].$geoNear.query || {}; + originalPipeline[0].$geoNear.query[discriminatorKey] = discriminatorValue; + } else { + var match = {}; + match[discriminatorKey] = discriminatorValue; + aggregate._pipeline = [{$match: match}].concat(originalPipeline); + } + } +} + + +/*! + * Exports + */ + +module.exports = Aggregate; diff --git a/5-3/node_modules/mongoose/lib/browser.js b/5-3/node_modules/mongoose/lib/browser.js new file mode 100644 index 0000000..74a7b6e --- /dev/null +++ b/5-3/node_modules/mongoose/lib/browser.js @@ -0,0 +1,99 @@ +/* eslint-env browser */ + +/** + * The [MongooseError](#error_MongooseError) constructor. + * + * @method Error + * @api public + */ + +exports.Error = require('./error'); + +/** + * The Mongoose [Schema](#schema_Schema) constructor + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var Schema = mongoose.Schema; + * var CatSchema = new Schema(..); + * + * @method Schema + * @api public + */ + +exports.Schema = require('./schema'); + +/** + * The various Mongoose Types. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var array = mongoose.Types.Array; + * + * ####Types: + * + * - [ObjectId](#types-objectid-js) + * - [Buffer](#types-buffer-js) + * - [SubDocument](#types-embedded-js) + * - [Array](#types-array-js) + * - [DocumentArray](#types-documentarray-js) + * + * Using this exposed access to the `ObjectId` type, we can construct ids on demand. + * + * var ObjectId = mongoose.Types.ObjectId; + * var id1 = new ObjectId; + * + * @property Types + * @api public + */ +exports.Types = require('./types'); + +/** + * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor + * + * @method VirtualType + * @api public + */ +exports.VirtualType = require('./virtualtype'); + +/** + * The various Mongoose SchemaTypes. + * + * ####Note: + * + * _Alias of mongoose.Schema.Types for backwards compatibility._ + * + * @property SchemaTypes + * @see Schema.SchemaTypes #schema_Schema.Types + * @api public + */ + +exports.SchemaType = require('./schematype.js'); + +/** + * Internal utils + * + * @property utils + * @api private + */ + +exports.utils = require('./utils.js'); + +/** + * The Mongoose browser [Document](#document-js) constructor. + * + * @method Document + * @api public + */ +exports.Document = require('./document_provider.js')(); + +/*! + * Module exports. + */ + +if (typeof window !== 'undefined') { + window.mongoose = module.exports; + window.Buffer = Buffer; +} diff --git a/5-3/node_modules/mongoose/lib/browserDocument.js b/5-3/node_modules/mongoose/lib/browserDocument.js new file mode 100644 index 0000000..6c87d19 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/browserDocument.js @@ -0,0 +1,103 @@ +/*! + * Module dependencies. + */ + +var NodeJSDocument = require('./document'), + EventEmitter = require('events').EventEmitter, + MongooseError = require('./error'), + Schema = require('./schema'), + ObjectId = require('./types/objectid'), + utils = require('./utils'), + ValidationError = MongooseError.ValidationError, + InternalCache = require('./internal'); + +/** + * Document constructor. + * + * @param {Object} obj the values to set + * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data + * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose. + * @event `save`: Emitted when the document is successfully saved + * @api private + */ + +function Document(obj, schema, fields, skipId, skipInit) { + if (!(this instanceof Document)) { + return new Document(obj, schema, fields, skipId, skipInit); + } + + + if (utils.isObject(schema) && !schema.instanceOfSchema) { + schema = new Schema(schema); + } + + // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id + schema = this.schema || schema; + + // Generate ObjectId if it is missing, but it requires a scheme + if (!this.schema && schema.options._id) { + obj = obj || {}; + + if (obj._id === undefined) { + obj._id = new ObjectId(); + } + } + + if (!schema) { + throw new MongooseError.MissingSchemaError(); + } + + this.$__setSchema(schema); + + this.$__ = new InternalCache; + this.$__.emitter = new EventEmitter(); + this.isNew = true; + this.errors = undefined; + + // var schema = this.schema; + + if (typeof fields === 'boolean') { + this.$__.strictMode = fields; + fields = undefined; + } else { + this.$__.strictMode = this.schema.options && this.schema.options.strict; + this.$__.selected = fields; + } + + var required = this.schema.requiredPaths(); + for (var i = 0; i < required.length; ++i) { + this.$__.activePaths.require(required[i]); + } + + this.$__.emitter.setMaxListeners(0); + this._doc = this.$__buildDoc(obj, fields, skipId); + + if (!skipInit && obj) { + this.init(obj); + } + + this.$__registerHooksFromSchema(); + + // apply methods + for (var m in schema.methods) { + this[m] = schema.methods[m]; + } + // apply statics + for (var s in schema.statics) { + this[s] = schema.statics[s]; + } +} + +/*! + * Inherit from the NodeJS document + */ +Document.prototype = Object.create(NodeJSDocument.prototype); +Document.prototype.constructor = Document; + +/*! + * Module exports. + */ +Document.ValidationError = ValidationError; +module.exports = exports = Document; diff --git a/5-3/node_modules/mongoose/lib/cast.js b/5-3/node_modules/mongoose/lib/cast.js new file mode 100644 index 0000000..9c63ee3 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/cast.js @@ -0,0 +1,204 @@ +/*! + * Module dependencies. + */ + +var utils = require('./utils'); +var Types = require('./schema/index'); + +/** + * Handles internal casting for queries + * + * @param {Schema} schema + * @param {Object} obj Object to cast + * @api private + */ +module.exports = function cast(schema, obj) { + var paths = Object.keys(obj), + i = paths.length, + any$conditionals, + schematype, + nested, + path, + type, + val; + + while (i--) { + path = paths[i]; + val = obj[path]; + + if (path === '$or' || path === '$nor' || path === '$and') { + var k = val.length; + + while (k--) { + val[k] = cast(schema, val[k]); + } + } else if (path === '$where') { + type = typeof val; + + if (type !== 'string' && type !== 'function') { + throw new Error('Must have a string or function for $where'); + } + + if (type === 'function') { + obj[path] = val.toString(); + } + + continue; + } else if (path === '$elemMatch') { + val = cast(schema, val); + } else { + if (!schema) { + // no casting for Mixed types + continue; + } + + schematype = schema.path(path); + + if (!schematype) { + // Handle potential embedded array queries + var split = path.split('.'), + j = split.length, + pathFirstHalf, + pathLastHalf, + remainingConds; + + // Find the part of the var path that is a path of the Schema + while (j--) { + pathFirstHalf = split.slice(0, j).join('.'); + schematype = schema.path(pathFirstHalf); + if (schematype) { + break; + } + } + + // If a substring of the input path resolves to an actual real path... + if (schematype) { + // Apply the casting; similar code for $elemMatch in schema/array.js + if (schematype.caster && schematype.caster.schema) { + remainingConds = {}; + pathLastHalf = split.slice(j).join('.'); + remainingConds[pathLastHalf] = val; + obj[path] = cast(schematype.caster.schema, remainingConds)[pathLastHalf]; + } else { + obj[path] = val; + } + continue; + } + + if (utils.isObject(val)) { + // handle geo schemas that use object notation + // { loc: { long: Number, lat: Number } + + var geo = val.$near ? '$near' : + val.$nearSphere ? '$nearSphere' : + val.$within ? '$within' : + val.$geoIntersects ? '$geoIntersects' : ''; + + if (!geo) { + continue; + } + + var numbertype = new Types.Number('__QueryCasting__'); + var value = val[geo]; + + if (val.$maxDistance) { + val.$maxDistance = numbertype.castForQuery(val.$maxDistance); + } + + if (geo === '$within') { + var withinType = value.$center + || value.$centerSphere + || value.$box + || value.$polygon; + + if (!withinType) { + throw new Error('Bad $within paramater: ' + JSON.stringify(val)); + } + + value = withinType; + } else if (geo === '$near' && + typeof value.type === 'string' && Array.isArray(value.coordinates)) { + // geojson; cast the coordinates + value = value.coordinates; + } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') && + value.$geometry && typeof value.$geometry.type === 'string' && + Array.isArray(value.$geometry.coordinates)) { + // geojson; cast the coordinates + value = value.$geometry.coordinates; + } + + _cast(value, numbertype); + } + } else if (val === null || val === undefined) { + obj[path] = null; + continue; + } else if (val.constructor.name === 'Object') { + any$conditionals = Object.keys(val).some(function(k) { + return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; + }); + + if (!any$conditionals) { + obj[path] = schematype.castForQuery(val); + } else { + var ks = Object.keys(val), + $cond; + + k = ks.length; + + while (k--) { + $cond = ks[k]; + nested = val[$cond]; + + if ($cond === '$exists') { + if (typeof nested !== 'boolean') { + throw new Error('$exists parameter must be Boolean'); + } + continue; + } + + if ($cond === '$type') { + if (typeof nested !== 'number') { + throw new Error('$type parameter must be Number'); + } + continue; + } + + if ($cond === '$not') { + cast(schema, nested); + } else { + val[$cond] = schematype.castForQuery($cond, nested); + } + } + } + } else { + obj[path] = schematype.castForQuery(val); + } + } + } + + return obj; +}; + +function _cast(val, numbertype) { + if (Array.isArray(val)) { + val.forEach(function(item, i) { + if (Array.isArray(item) || utils.isObject(item)) { + return _cast(item, numbertype); + } + val[i] = numbertype.castForQuery(item); + }); + } else { + var nearKeys = Object.keys(val); + var nearLen = nearKeys.length; + while (nearLen--) { + var nkey = nearKeys[nearLen]; + var item = val[nkey]; + if (Array.isArray(item) || utils.isObject(item)) { + _cast(item, numbertype); + val[nkey] = item; + } else { + val[nkey] = numbertype.castForQuery(item); + } + } + } +} diff --git a/5-3/node_modules/mongoose/lib/collection.js b/5-3/node_modules/mongoose/lib/collection.js new file mode 100644 index 0000000..3aee0aa --- /dev/null +++ b/5-3/node_modules/mongoose/lib/collection.js @@ -0,0 +1,206 @@ +/*! + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var STATES = require('./connectionstate'); + +/** + * Abstract Collection constructor + * + * This is the base class that drivers inherit from and implement. + * + * @param {String} name name of the collection + * @param {Connection} conn A MongooseConnection instance + * @param {Object} opts optional collection options + * @api public + */ + +function Collection(name, conn, opts) { + if (opts === void 0) { + opts = {}; + } + if (opts.capped === void 0) { + opts.capped = {}; + } + + opts.bufferCommands = undefined === opts.bufferCommands + ? true + : opts.bufferCommands; + + if (typeof opts.capped === 'number') { + opts.capped = {size: opts.capped}; + } + + this.opts = opts; + this.name = name; + this.collectionName = name; + this.conn = conn; + this.queue = []; + this.buffer = this.opts.bufferCommands; + this.emitter = new EventEmitter(); + + if (STATES.connected === this.conn.readyState) { + this.onOpen(); + } +} + +/** + * The collection name + * + * @api public + * @property name + */ + +Collection.prototype.name; + +/** + * The collection name + * + * @api public + * @property collectionName + */ + +Collection.prototype.collectionName; + +/** + * The Connection instance + * + * @api public + * @property conn + */ + +Collection.prototype.conn; + +/** + * Called when the database connects + * + * @api private + */ + +Collection.prototype.onOpen = function() { + this.buffer = false; + this.doQueue(); +}; + +/** + * Called when the database disconnects + * + * @api private + */ + +Collection.prototype.onClose = function() { + if (this.opts.bufferCommands) { + this.buffer = true; + } +}; + +/** + * Queues a method for later execution when its + * database connection opens. + * + * @param {String} name name of the method to queue + * @param {Array} args arguments to pass to the method when executed + * @api private + */ + +Collection.prototype.addQueue = function(name, args) { + this.queue.push([name, args]); + return this; +}; + +/** + * Executes all queued methods and clears the queue. + * + * @api private + */ + +Collection.prototype.doQueue = function() { + for (var i = 0, l = this.queue.length; i < l; i++) { + this[this.queue[i][0]].apply(this, this.queue[i][1]); + } + this.queue = []; + var _this = this; + process.nextTick(function() { + _this.emitter.emit('queue'); + }); + return this; +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.ensureIndex = function() { + throw new Error('Collection#ensureIndex unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.findAndModify = function() { + throw new Error('Collection#findAndModify unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.findOne = function() { + throw new Error('Collection#findOne unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.find = function() { + throw new Error('Collection#find unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.insert = function() { + throw new Error('Collection#insert unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.save = function() { + throw new Error('Collection#save unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.update = function() { + throw new Error('Collection#update unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.getIndexes = function() { + throw new Error('Collection#getIndexes unimplemented by driver'); +}; + +/** + * Abstract method that drivers must implement. + */ + +Collection.prototype.mapReduce = function() { + throw new Error('Collection#mapReduce unimplemented by driver'); +}; + +/*! + * Module exports. + */ + +module.exports = Collection; diff --git a/5-3/node_modules/mongoose/lib/connection.js b/5-3/node_modules/mongoose/lib/connection.js new file mode 100644 index 0000000..e2fa003 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/connection.js @@ -0,0 +1,787 @@ +/*! + * Module dependencies. + */ + +var utils = require('./utils'), + EventEmitter = require('events').EventEmitter, + driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native', + Schema = require('./schema'), + Collection = require(driver + '/collection'), + STATES = require('./connectionstate'), + MongooseError = require('./error'), + muri = require('muri'), + PromiseProvider = require('./promise_provider'); + +/*! + * Protocol prefix regexp. + * + * @api private + */ + +var rgxProtocol = /^(?:.)+:\/\//; + +/*! + * A list of authentication mechanisms that don't require a password for authentication. + * This is used by the authMechanismDoesNotRequirePassword method. + * + * @api private + */ +var authMechanismsWhichDontRequirePassword = [ + 'MONGODB-X509' +]; + +/** + * Connection constructor + * + * For practical reasons, a Connection equals a Db. + * + * @param {Mongoose} base a mongoose instance + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `connecting`: Emitted when `connection.{open,openSet}()` is executed on this connection. + * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios. + * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models. + * @event `disconnecting`: Emitted when `connection.close()` was executed. + * @event `disconnected`: Emitted after getting disconnected from the db. + * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models. + * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection. + * @event `error`: Emitted when an error occurs on this connection. + * @event `fullsetup`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. + * @api public + */ + +function Connection(base) { + this.base = base; + this.collections = {}; + this.models = {}; + this.config = {autoIndex: true}; + this.replica = false; + this.hosts = null; + this.host = null; + this.port = null; + this.user = null; + this.pass = null; + this.name = null; + this.options = null; + this.otherDbs = []; + this._readyState = STATES.disconnected; + this._closeCalled = false; + this._hasOpened = false; +} + +/*! + * Inherit from EventEmitter + */ + +Connection.prototype.__proto__ = EventEmitter.prototype; + +/** + * Connection ready state + * + * - 0 = disconnected + * - 1 = connected + * - 2 = connecting + * - 3 = disconnecting + * + * Each state change emits its associated event name. + * + * ####Example + * + * conn.on('connected', callback); + * conn.on('disconnected', callback); + * + * @property readyState + * @api public + */ + +Object.defineProperty(Connection.prototype, 'readyState', { + get: function() { + return this._readyState; + }, + set: function(val) { + if (!(val in STATES)) { + throw new Error('Invalid connection state: ' + val); + } + + if (this._readyState !== val) { + this._readyState = val; + // loop over the otherDbs on this connection and change their state + for (var i = 0; i < this.otherDbs.length; i++) { + this.otherDbs[i].readyState = val; + } + + if (STATES.connected === val) { + this._hasOpened = true; + } + + this.emit(STATES[val]); + } + } +}); + +/** + * A hash of the collections associated with this connection + * + * @property collections + */ + +Connection.prototype.collections; + +/** + * The mongodb.Db instance, set when the connection is opened + * + * @property db + */ + +Connection.prototype.db; + +/** + * A hash of the global options that are associated with this connection + * + * @property global + */ + +Connection.prototype.config; + +/** + * Opens the connection to MongoDB. + * + * `options` is a hash with the following possible properties: + * + * config - passed to the connection config instance + * db - passed to the connection db instance + * server - passed to the connection server instance(s) + * replset - passed to the connection ReplSet instance + * user - username for authentication + * pass - password for authentication + * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) + * + * ####Notes: + * + * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden. + * Mongoose defaults the server `auto_reconnect` options to true which can be overridden. + * See the node-mongodb-native driver instance for options that it understands. + * + * _Options passed take precedence over options included in connection strings._ + * + * @param {String} connection_string mongodb://uri or the host to which you are connecting + * @param {String} [database] database name + * @param {Number} [port] database port + * @param {Object} [options] options + * @param {Function} [callback] + * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native + * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate + * @api public + */ + +Connection.prototype.open = function(host, database, port, options, callback) { + var parsed; + + if (typeof database === 'string') { + switch (arguments.length) { + case 2: + port = 27017; + break; + case 3: + switch (typeof port) { + case 'function': + callback = port; + port = 27017; + break; + case 'object': + options = port; + port = 27017; + break; + } + break; + case 4: + if (typeof options === 'function') { + callback = options; + options = {}; + } + } + } else { + switch (typeof database) { + case 'function': + callback = database; + database = undefined; + break; + case 'object': + options = database; + database = undefined; + callback = port; + break; + } + + if (!rgxProtocol.test(host)) { + host = 'mongodb://' + host; + } + + try { + parsed = muri(host); + } catch (err) { + this.error(err, callback); + return this; + } + + database = parsed.db; + host = parsed.hosts[0].host || parsed.hosts[0].ipc; + port = parsed.hosts[0].port || 27017; + } + + this.options = this.parseOptions(options, parsed && parsed.options); + + // make sure we can open + if (STATES.disconnected !== this.readyState) { + var err = new Error('Trying to open unclosed connection.'); + err.state = this.readyState; + this.error(err, callback); + return this; + } + + if (!host) { + this.error(new Error('Missing hostname.'), callback); + return this; + } + + if (!database) { + this.error(new Error('Missing database name.'), callback); + return this; + } + + // authentication + if (this.optionsProvideAuthenticationData(options)) { + this.user = options.user; + this.pass = options.pass; + } else if (parsed && parsed.auth) { + this.user = parsed.auth.user; + this.pass = parsed.auth.pass; + + // Check hostname for user/pass + } else if (/@/.test(host) && /:/.test(host.split('@')[0])) { + host = host.split('@'); + var auth = host.shift().split(':'); + host = host.pop(); + this.user = auth[0]; + this.pass = auth[1]; + } else { + this.user = this.pass = undefined; + } + + // global configuration options + if (options && options.config) { + this.config.autoIndex = options.config.autoIndex !== false; + } + + this.name = database; + this.host = host; + this.port = port; + + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _this._open(!!callback, function(error) { + callback && callback(error); + if (error) { + reject(error); + return; + } + resolve(); + }); + }); +}; + +/** + * Opens the connection to a replica set. + * + * ####Example: + * + * var db = mongoose.createConnection(); + * db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019"); + * + * The database name and/or auth need only be included in one URI. + * The `options` is a hash which is passed to the internal driver connection object. + * + * Valid `options` + * + * db - passed to the connection db instance + * server - passed to the connection server instance(s) + * replset - passed to the connection ReplSetServer instance + * user - username for authentication + * pass - password for authentication + * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) + * mongos - Boolean - if true, enables High Availability support for mongos + * + * _Options passed take precedence over options included in connection strings._ + * + * ####Notes: + * + * _If connecting to multiple mongos servers, set the `mongos` option to true._ + * + * conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb); + * + * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden. + * Mongoose defaults the server `auto_reconnect` options to true which can be overridden. + * See the node-mongodb-native driver instance for options that it understands. + * + * _Options passed take precedence over options included in connection strings._ + * + * @param {String} uris comma-separated mongodb:// `URI`s + * @param {String} [database] database name if not included in `uris` + * @param {Object} [options] passed to the internal driver + * @param {Function} [callback] + * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native + * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate + * @api public + */ + +Connection.prototype.openSet = function(uris, database, options, callback) { + if (!rgxProtocol.test(uris)) { + uris = 'mongodb://' + uris; + } + + switch (arguments.length) { + case 3: + switch (typeof database) { + case 'string': + this.name = database; + break; + case 'object': + callback = options; + options = database; + database = null; + break; + } + + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 2: + switch (typeof database) { + case 'string': + this.name = database; + break; + case 'function': + callback = database; + database = null; + break; + case 'object': + options = database; + database = null; + break; + } + } + + var parsed; + try { + parsed = muri(uris); + } catch (err) { + this.error(err, callback); + return this; + } + + if (!this.name) { + this.name = parsed.db; + } + + this.hosts = parsed.hosts; + this.options = this.parseOptions(options, parsed && parsed.options); + this.replica = true; + + if (!this.name) { + this.error(new Error('No database name provided for replica set'), callback); + return this; + } + + // authentication + if (this.optionsProvideAuthenticationData(options)) { + this.user = options.user; + this.pass = options.pass; + } else if (parsed && parsed.auth) { + this.user = parsed.auth.user; + this.pass = parsed.auth.pass; + } else { + this.user = this.pass = undefined; + } + + // global configuration options + if (options && options.config) { + this.config.autoIndex = options.config.autoIndex !== false; + } + + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _this._open(!!callback, function(error) { + callback && callback(error); + if (error) { + reject(error); + return; + } + resolve(); + }); + }); +}; + +/** + * error + * + * Graceful error handling, passes error to callback + * if available, else emits error on the connection. + * + * @param {Error} err + * @param {Function} callback optional + * @api private + */ + +Connection.prototype.error = function(err, callback) { + if (callback) { + return callback(err); + } + this.emit('error', err); +}; + +/** + * Handles opening the connection with the appropriate method based on connection type. + * + * @param {Function} callback + * @api private + */ + +Connection.prototype._open = function(emit, callback) { + this.readyState = STATES.connecting; + this._closeCalled = false; + + var _this = this; + + var method = this.replica + ? 'doOpenSet' + : 'doOpen'; + + // open connection + this[method](function(err) { + if (err) { + _this.readyState = STATES.disconnected; + if (_this._hasOpened) { + if (callback) { + callback(err); + } + } else { + _this.error(err, emit && callback); + } + return; + } + + _this.onOpen(callback); + }); +}; + +/** + * Called when the connection is opened + * + * @api private + */ + +Connection.prototype.onOpen = function(callback) { + var _this = this; + + function open(err, isAuth) { + if (err) { + _this.readyState = isAuth ? STATES.unauthorized : STATES.disconnected; + if (_this._hasOpened) { + if (callback) { + callback(err); + } + } else { + _this.error(err, callback); + } + return; + } + + _this.readyState = STATES.connected; + + // avoid having the collection subscribe to our event emitter + // to prevent 0.3 warning + for (var i in _this.collections) { + _this.collections[i].onOpen(); + } + + callback && callback(); + _this.emit('open'); + } + + // re-authenticate + if (this.shouldAuthenticate()) { + _this.db.authenticate(_this.user, _this.pass, _this.options.auth, function(err) { + open(err, true); + }); + } else { + open(); + } +}; + +/** + * Closes the connection + * + * @param {Function} [callback] optional + * @return {Connection} self + * @api public + */ + +Connection.prototype.close = function(callback) { + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _this._close(function(error) { + callback && callback(error); + if (error) { + reject(error); + return; + } + resolve(); + }); + }); +}; + +/** + * Handles closing the connection + * + * @param {Function} callback + * @api private + */ +Connection.prototype._close = function(callback) { + var _this = this; + this._closeCalled = true; + + switch (this.readyState) { + case 0: // disconnected + callback && callback(); + break; + + case 1: // connected + case 4: // unauthorized + this.readyState = STATES.disconnecting; + this.doClose(function(err) { + if (err) { + _this.error(err, callback); + } else { + _this.onClose(); + callback && callback(); + } + }); + break; + + case 2: // connecting + this.once('open', function() { + _this.close(callback); + }); + break; + + case 3: // disconnecting + if (!callback) { + break; + } + this.once('close', function() { + callback(); + }); + break; + } + + return this; +}; + +/** + * Called when the connection closes + * + * @api private + */ + +Connection.prototype.onClose = function() { + this.readyState = STATES.disconnected; + + // avoid having the collection subscribe to our event emitter + // to prevent 0.3 warning + for (var i in this.collections) { + this.collections[i].onClose(); + } + + this.emit('close'); +}; + +/** + * Retrieves a collection, creating it if not cached. + * + * Not typically needed by applications. Just talk to your collection through your model. + * + * @param {String} name of the collection + * @param {Object} [options] optional collection options + * @return {Collection} collection instance + * @api public + */ + +Connection.prototype.collection = function(name, options) { + if (!(name in this.collections)) { + this.collections[name] = new Collection(name, this, options); + } + return this.collections[name]; +}; + +/** + * Defines or retrieves a model. + * + * var mongoose = require('mongoose'); + * var db = mongoose.createConnection(..); + * db.model('Venue', new Schema(..)); + * var Ticket = db.model('Ticket', new Schema(..)); + * var Venue = db.model('Venue'); + * + * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ + * + * ####Example: + * + * var schema = new Schema({ name: String }, { collection: 'actor' }); + * + * // or + * + * schema.set('collection', 'actor'); + * + * // or + * + * var collectionName = 'actor' + * var M = conn.model('Actor', schema, collectionName) + * + * @param {String} name the model name + * @param {Schema} [schema] a schema. necessary when defining a model + * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name + * @see Mongoose#model #index_Mongoose-model + * @return {Model} The compiled model + * @api public + */ + +Connection.prototype.model = function(name, schema, collection) { + // collection name discovery + if (typeof schema === 'string') { + collection = schema; + schema = false; + } + + if (utils.isObject(schema) && !schema.instanceOfSchema) { + schema = new Schema(schema); + } + + if (this.models[name] && !collection) { + // model exists but we are not subclassing with custom collection + if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { + throw new MongooseError.OverwriteModelError(name); + } + return this.models[name]; + } + + var opts = {cache: false, connection: this}; + var model; + + if (schema && schema.instanceOfSchema) { + // compile a model + model = this.base.model(name, schema, collection, opts); + + // only the first model with this name is cached to allow + // for one-offs with custom collection names etc. + if (!this.models[name]) { + this.models[name] = model; + } + + model.init(); + return model; + } + + if (this.models[name] && collection) { + // subclassing current model with alternate collection + model = this.models[name]; + schema = model.prototype.schema; + var sub = model.__subclass(this, schema, collection); + // do not cache the sub model + return sub; + } + + // lookup model in mongoose module + model = this.base.models[name]; + + if (!model) { + throw new MongooseError.MissingSchemaError(name); + } + + if (this === model.prototype.db + && (!collection || collection === model.collection.name)) { + // model already uses this connection. + + // only the first model with this name is cached to allow + // for one-offs with custom collection names etc. + if (!this.models[name]) { + this.models[name] = model; + } + + return model; + } + this.models[name] = model.__subclass(this, schema, collection); + return this.models[name]; +}; + +/** + * Returns an array of model names created on this connection. + * @api public + * @return {Array} + */ + +Connection.prototype.modelNames = function() { + return Object.keys(this.models); +}; + +/** + * @brief Returns if the connection requires authentication after it is opened. Generally if a + * username and password are both provided than authentication is needed, but in some cases a + * password is not required. + * @api private + * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false. + */ +Connection.prototype.shouldAuthenticate = function() { + return (this.user !== null && this.user !== void 0) && + ((this.pass !== null || this.pass !== void 0) || this.authMechanismDoesNotRequirePassword()); +}; + +/** + * @brief Returns a boolean value that specifies if the current authentication mechanism needs a + * password to authenticate according to the auth objects passed into the open/openSet methods. + * @api private + * @return {Boolean} true if the authentication mechanism specified in the options object requires + * a password, otherwise false. + */ +Connection.prototype.authMechanismDoesNotRequirePassword = function() { + if (this.options && this.options.auth) { + return authMechanismsWhichDontRequirePassword.indexOf(this.options.auth.authMechanism) >= 0; + } + return true; +}; + +/** + * @brief Returns a boolean value that specifies if the provided objects object provides enough + * data to authenticate with. Generally this is true if the username and password are both specified + * but in some authentication methods, a password is not required for authentication so only a username + * is required. + * @param {Object} [options] the options object passed into the open/openSet methods. + * @api private + * @return {Boolean} true if the provided options object provides enough data to authenticate with, + * otherwise false. + */ +Connection.prototype.optionsProvideAuthenticationData = function(options) { + return (options) && + (options.user) && + ((options.pass) || this.authMechanismDoesNotRequirePassword()); +}; + +/*! + * Module exports. + */ + +Connection.STATES = STATES; +module.exports = Connection; diff --git a/5-3/node_modules/mongoose/lib/connectionstate.js b/5-3/node_modules/mongoose/lib/connectionstate.js new file mode 100644 index 0000000..b9d1baf --- /dev/null +++ b/5-3/node_modules/mongoose/lib/connectionstate.js @@ -0,0 +1,27 @@ + +/*! + * Connection states + */ + +var STATES = module.exports = exports = Object.create(null); + +var disconnected = 'disconnected'; +var connected = 'connected'; +var connecting = 'connecting'; +var disconnecting = 'disconnecting'; +var unauthorized = 'unauthorized'; +var uninitialized = 'uninitialized'; + +STATES[0] = disconnected; +STATES[1] = connected; +STATES[2] = connecting; +STATES[3] = disconnecting; +STATES[4] = unauthorized; +STATES[99] = uninitialized; + +STATES[disconnected] = 0; +STATES[connected] = 1; +STATES[connecting] = 2; +STATES[disconnecting] = 3; +STATES[unauthorized] = 4; +STATES[uninitialized] = 99; diff --git a/5-3/node_modules/mongoose/lib/document.js b/5-3/node_modules/mongoose/lib/document.js new file mode 100644 index 0000000..f9da698 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/document.js @@ -0,0 +1,2412 @@ +/*! + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter, + MongooseError = require('./error'), + MixedSchema = require('./schema/mixed'), + Schema = require('./schema'), + ObjectExpectedError = require('./error/objectExpected'), + StrictModeError = require('./error/strict'), + ValidatorError = require('./schematype').ValidatorError, + utils = require('./utils'), + clone = utils.clone, + isMongooseObject = utils.isMongooseObject, + inspect = require('util').inspect, + ValidationError = MongooseError.ValidationError, + InternalCache = require('./internal'), + deepEqual = utils.deepEqual, + hooks = require('hooks-fixed'), + PromiseProvider = require('./promise_provider'), + DocumentArray, + MongooseArray, + Embedded; + +/** + * Document constructor. + * + * @param {Object} obj the values to set + * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data + * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose. + * @event `save`: Emitted when the document is successfully saved + * @api private + */ + +function Document(obj, fields, skipId) { + this.$__ = new InternalCache; + this.$__.emitter = new EventEmitter(); + this.isNew = true; + this.errors = undefined; + + var schema = this.schema; + + if (typeof fields === 'boolean') { + this.$__.strictMode = fields; + fields = undefined; + } else { + this.$__.strictMode = schema.options && schema.options.strict; + this.$__.selected = fields; + } + + var required = schema.requiredPaths(true); + for (var i = 0; i < required.length; ++i) { + this.$__.activePaths.require(required[i]); + } + + this.$__.emitter.setMaxListeners(0); + this._doc = this.$__buildDoc(obj, fields, skipId); + + if (obj) { + this.set(obj, undefined, true); + } + + if (!schema.options.strict && obj) { + var _this = this, + keys = Object.keys(this._doc); + + keys.forEach(function(key) { + if (!(key in schema.tree)) { + defineKey(key, null, _this); + } + }); + } + + this.$__registerHooksFromSchema(); +} + +/*! + * Document exposes the NodeJS event emitter API, so you can use + * `on`, `once`, etc. + */ +utils.each( + ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', + 'removeAllListeners', 'addListener'], + function(emitterFn) { + Document.prototype[emitterFn] = function() { + return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); + }; + }); + +Document.prototype.constructor = Document; + +/** + * The documents schema. + * + * @api public + * @property schema + */ + +Document.prototype.schema; + +/** + * Boolean flag specifying if the document is new. + * + * @api public + * @property isNew + */ + +Document.prototype.isNew; + +/** + * The string version of this documents _id. + * + * ####Note: + * + * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. + * + * new Schema({ name: String }, { id: false }); + * + * @api public + * @see Schema options /docs/guide.html#options + * @property id + */ + +Document.prototype.id; + +/** + * Hash containing current validation errors. + * + * @api public + * @property errors + */ + +Document.prototype.errors; + +/** + * Builds the default doc structure + * + * @param {Object} obj + * @param {Object} [fields] + * @param {Boolean} [skipId] + * @return {Object} + * @api private + * @method $__buildDoc + * @memberOf Document + */ + +Document.prototype.$__buildDoc = function(obj, fields, skipId) { + var doc = {}; + var exclude = null; + var keys; + var ki; + var _this = this; + + // determine if this doc is a result of a query with + // excluded fields + if (fields && utils.getFunctionName(fields.constructor) === 'Object') { + keys = Object.keys(fields); + ki = keys.length; + + if (ki === 1 && keys[0] === '_id') { + exclude = !!fields[keys[ki]]; + } else { + while (ki--) { + if (keys[ki] !== '_id' && + (!fields[keys[ki]] || typeof fields[keys[ki]] !== 'object')) { + exclude = !fields[keys[ki]]; + break; + } + } + } + } + + var paths = Object.keys(this.schema.paths), + plen = paths.length, + ii = 0; + + for (; ii < plen; ++ii) { + var p = paths[ii]; + + if (p === '_id') { + if (skipId) { + continue; + } + if (obj && '_id' in obj) { + continue; + } + } + + var type = this.schema.paths[p]; + var path = p.split('.'); + var len = path.length; + var last = len - 1; + var curPath = ''; + var doc_ = doc; + var i = 0; + var included = false; + + for (; i < len; ++i) { + var piece = path[i], + def; + + curPath += piece; + + // support excluding intermediary levels + if (exclude === true) { + if (curPath in fields) { + break; + } + } else if (fields && curPath in fields) { + included = true; + } + + if (i === last) { + if (fields && exclude !== null) { + if (exclude === true) { + // apply defaults to all non-excluded fields + if (p in fields) { + continue; + } + + def = type.getDefault(_this, true); + if (typeof def !== 'undefined') { + doc_[piece] = def; + _this.$__.activePaths.default(p); + } + } else if (included) { + // selected field + def = type.getDefault(_this, true); + if (typeof def !== 'undefined') { + doc_[piece] = def; + _this.$__.activePaths.default(p); + } + } + } else { + def = type.getDefault(_this, true); + if (typeof def !== 'undefined') { + doc_[piece] = def; + _this.$__.activePaths.default(p); + } + } + } else { + doc_ = doc_[piece] || (doc_[piece] = {}); + curPath += '.'; + } + } + } + + return doc; +}; + +/** + * Initializes the document without setters or marking anything modified. + * + * Called internally after a document is returned from mongodb. + * + * @param {Object} doc document returned by mongo + * @param {Function} fn callback + * @api public + */ + +Document.prototype.init = function(doc, opts, fn) { + // do not prefix this method with $__ since its + // used by public hooks + + if (typeof opts === 'function') { + fn = opts; + opts = null; + } + + this.isNew = false; + + // handle docs with populated paths + // If doc._id is not null or undefined + if (doc._id !== null && doc._id !== undefined && + opts && opts.populated && opts.populated.length) { + var id = String(doc._id); + for (var i = 0; i < opts.populated.length; ++i) { + var item = opts.populated[i]; + this.populated(item.path, item._docs[id], item); + } + } + + init(this, doc, this._doc); + this.$__storeShard(); + + this.emit('init', this); + if (fn) { + fn(null); + } + return this; +}; + +/*! + * Init helper. + * + * @param {Object} self document instance + * @param {Object} obj raw mongodb doc + * @param {Object} doc object we are initializing + * @api private + */ + +function init(self, obj, doc, prefix) { + prefix = prefix || ''; + + var keys = Object.keys(obj), + len = keys.length, + schema, + path, + i; + + while (len--) { + i = keys[len]; + path = prefix + i; + schema = self.schema.path(path); + + if (!schema && utils.isObject(obj[i]) && + (!obj[i].constructor || utils.getFunctionName(obj[i].constructor) === 'Object')) { + // assume nested object + if (!doc[i]) { + doc[i] = {}; + } + init(self, obj[i], doc[i], path + '.'); + } else { + if (obj[i] === null) { + doc[i] = null; + } else if (obj[i] !== undefined) { + if (schema) { + try { + doc[i] = schema.cast(obj[i], self, true); + } catch (e) { + self.invalidate(e.path, new ValidatorError({ + path: e.path, + message: e.message, + type: 'cast', + value: e.value + })); + } + } else { + doc[i] = obj[i]; + } + } + // mark as hydrated + if (!self.isModified(path)) { + self.$__.activePaths.init(path); + } + } + } +} + +/** + * Stores the current values of the shard keys. + * + * ####Note: + * + * _Shard key values do not / are not allowed to change._ + * + * @api private + * @method $__storeShard + * @memberOf Document + */ + +Document.prototype.$__storeShard = function() { + // backwards compat + var key = this.schema.options.shardKey || this.schema.options.shardkey; + if (!(key && utils.getFunctionName(key.constructor) === 'Object')) { + return; + } + + var orig = this.$__.shardval = {}, + paths = Object.keys(key), + len = paths.length, + val; + + for (var i = 0; i < len; ++i) { + val = this.getValue(paths[i]); + if (isMongooseObject(val)) { + orig[paths[i]] = val.toObject({depopulate: true}); + } else if (val !== null && val !== undefined && val.valueOf && + // Explicitly don't take value of dates + (!val.constructor || utils.getFunctionName(val.constructor) !== 'Date')) { + orig[paths[i]] = val.valueOf(); + } else { + orig[paths[i]] = val; + } + } +}; + +/*! + * Set up middleware support + */ + +for (var k in hooks) { + Document.prototype[k] = Document[k] = hooks[k]; +} + +/** + * Sends an update command with this document `_id` as the query selector. + * + * ####Example: + * + * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); + * + * ####Valid options: + * + * - same as in [Model.update](#model_Model.update) + * + * @see Model.update #model_Model.update + * @param {Object} doc + * @param {Object} options + * @param {Function} callback + * @return {Query} + * @api public + */ + +Document.prototype.update = function update() { + var args = utils.args(arguments); + args.unshift({_id: this._id}); + return this.constructor.update.apply(this.constructor, args); +}; + +/** + * Sets the value of a path, or many paths. + * + * ####Example: + * + * // path, value + * doc.set(path, value) + * + * // object + * doc.set({ + * path : value + * , path2 : { + * path : value + * } + * }) + * + * // on-the-fly cast to number + * doc.set(path, value, Number) + * + * // on-the-fly cast to string + * doc.set(path, value, String) + * + * // changing strict mode behavior + * doc.set(path, value, { strict: false }); + * + * @param {String|Object} path path or object of key/vals to set + * @param {Any} val the value to set + * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes + * @param {Object} [options] optionally specify options that modify the behavior of the set + * @api public + */ + +Document.prototype.set = function(path, val, type, options) { + if (type && utils.getFunctionName(type.constructor) === 'Object') { + options = type; + type = undefined; + } + + var merge = options && options.merge, + adhoc = type && type !== true, + constructing = type === true, + adhocs; + + var strict = options && 'strict' in options + ? options.strict + : this.$__.strictMode; + + if (adhoc) { + adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); + adhocs[path] = Schema.interpretAsType(path, type, this.schema.options); + } + + if (typeof path !== 'string') { + // new Document({ key: val }) + + if (path === null || path === void 0) { + var _ = path; + path = val; + val = _; + } else { + var prefix = val + ? val + '.' + : ''; + + if (path instanceof Document) { + if (path.$__isNested) { + path = path.toObject(); + } else { + path = path._doc; + } + } + + var keys = Object.keys(path), + i = keys.length, + pathtype, + key; + + while (i--) { + key = keys[i]; + var pathName = prefix + key; + pathtype = this.schema.pathType(pathName); + + if (path[key] !== null + && path[key] !== undefined + // need to know if plain object - no Buffer, ObjectId, ref, etc + && utils.isObject(path[key]) + && (!path[key].constructor || utils.getFunctionName(path[key].constructor) === 'Object') + && pathtype !== 'virtual' + && pathtype !== 'real' + && !(this.$__path(pathName) instanceof MixedSchema) + && !(this.schema.paths[pathName] && + this.schema.paths[pathName].options && + this.schema.paths[pathName].options.ref)) { + this.set(path[key], prefix + key, constructing); + } else if (strict) { + if (pathtype === 'real' || pathtype === 'virtual') { + // Check for setting single embedded schema to document (gh-3535) + if (this.schema.paths[pathName] && + this.schema.paths[pathName].$isSingleNested && + path[key] instanceof Document) { + path[key] = path[key].toObject({virtuals: false}); + } + this.set(prefix + key, path[key], constructing); + } else if (pathtype === 'nested' && path[key] instanceof Document) { + this.set(prefix + key, + path[key].toObject({virtuals: false}), constructing); + } else if (strict === 'throw') { + if (pathtype === 'nested') { + throw new ObjectExpectedError(key, path[key]); + } else { + throw new StrictModeError(key); + } + } + } else if (undefined !== path[key]) { + this.set(prefix + key, path[key], constructing); + } + } + + return this; + } + } + + // ensure _strict is honored for obj props + // docschema = new Schema({ path: { nest: 'string' }}) + // doc.set('path', obj); + var pathType = this.schema.pathType(path); + if (pathType === 'nested' && val) { + if (utils.isObject(val) && + (!val.constructor || utils.getFunctionName(val.constructor) === 'Object')) { + if (!merge) { + this.setValue(path, null); + } + this.set(val, path, constructing); + return this; + } + this.invalidate(path, new MongooseError.CastError('Object', val, path)); + return this; + } + + var schema; + var parts = path.split('.'); + + if (pathType === 'adhocOrUndefined' && strict) { + // check for roots that are Mixed types + var mixed; + + for (i = 0; i < parts.length; ++i) { + var subpath = parts.slice(0, i + 1).join('.'); + schema = this.schema.path(subpath); + if (schema instanceof MixedSchema) { + // allow changes to sub paths of mixed types + mixed = true; + break; + } + } + + if (!mixed) { + if (strict === 'throw') { + throw new StrictModeError(path); + } + return this; + } + } else if (pathType === 'virtual') { + schema = this.schema.virtualpath(path); + schema.applySetters(val, this); + return this; + } else { + schema = this.$__path(path); + } + + var pathToMark; + + // When using the $set operator the path to the field must already exist. + // Else mongodb throws: "LEFT_SUBFIELD only supports Object" + + if (parts.length <= 1) { + pathToMark = path; + } else { + for (i = 0; i < parts.length; ++i) { + subpath = parts.slice(0, i + 1).join('.'); + if (this.isDirectModified(subpath) // earlier prefixes that are already + // marked as dirty have precedence + || this.get(subpath) === null) { + pathToMark = subpath; + break; + } + } + + if (!pathToMark) { + pathToMark = path; + } + } + + // if this doc is being constructed we should not trigger getters + var priorVal = constructing + ? undefined + : this.getValue(path); + + if (!schema) { + this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); + return this; + } + + var shouldSet = true; + try { + // If the user is trying to set a ref path to a document with + // the correct model name, treat it as populated + var didPopulate = false; + if (schema.options && + schema.options.ref && + val instanceof Document && + schema.options.ref === val.constructor.modelName) { + if (this.ownerDocument) { + this.ownerDocument().populated(this.$__fullPath(path), + val._id, {model: val.constructor}); + } else { + this.populated(path, val._id, {model: val.constructor}); + } + didPopulate = true; + } + + if (schema.options && + Array.isArray(schema.options.type) && + schema.options.type.length && + schema.options.type[0].ref && + Array.isArray(val) && + val.length > 0 && + val[0] instanceof Document && + val[0].constructor.modelName && + schema.options.type[0].ref === val[0].constructor.modelName) { + if (this.ownerDocument) { + this.ownerDocument().populated(this.$__fullPath(path), + val.map(function(v) { + return v._id; + }), + {model: val[0].constructor}); + } else { + this.populated(path, val + .map(function(v) { + return v._id; + }), + {model: val[0].constructor}); + } + didPopulate = true; + } + val = schema.applySetters(val, this, false, priorVal); + + if (!didPopulate && this.$__.populated) { + delete this.$__.populated[path]; + } + + this.$markValid(path); + } catch (e) { + var reason; + if (!(e instanceof MongooseError.CastError)) { + reason = e; + } + this.invalidate(path, + new MongooseError.CastError(schema.instance, val, path, reason)); + shouldSet = false; + } + + if (shouldSet) { + this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); + } + + return this; +}; + +/** + * Determine if we should mark this change as modified. + * + * @return {Boolean} + * @api private + * @method $__shouldModify + * @memberOf Document + */ + +Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) { + if (this.isNew) { + return true; + } + + if (undefined === val && !this.isSelected(path)) { + // when a path is not selected in a query, its initial + // value will be undefined. + return true; + } + + if (undefined === val && path in this.$__.activePaths.states.default) { + // we're just unsetting the default value which was never saved + return false; + } + + if (!deepEqual(val, priorVal || this.get(path))) { + return true; + } + + if (!constructing && + val !== null && + val !== undefined && + path in this.$__.activePaths.states.default && + deepEqual(val, schema.getDefault(this, constructing))) { + // a path with a default was $unset on the server + // and the user is setting it to the same value again + return true; + } + return false; +}; + +/** + * Handles the actual setting of the value and marking the path modified if appropriate. + * + * @api private + * @method $__set + * @memberOf Document + */ + +Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) { + Embedded = Embedded || require('./types/embedded'); + + var shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts, + schema, val, priorVal); + var _this = this; + + if (shouldModify) { + this.markModified(pathToMark, val); + + // handle directly setting arrays (gh-1126) + MongooseArray || (MongooseArray = require('./types/array')); + if (val && val.isMongooseArray) { + val._registerAtomic('$set', val); + + // Small hack for gh-1638: if we're overwriting the entire array, ignore + // paths that were modified before the array overwrite + this.$__.activePaths.forEach(function(modifiedPath) { + if (modifiedPath.indexOf(path + '.') === 0) { + _this.$__.activePaths.ignore(modifiedPath); + } + }); + } + } + + var obj = this._doc, + i = 0, + l = parts.length; + + for (; i < l; i++) { + var next = i + 1, + last = next === l; + + if (last) { + obj[parts[i]] = val; + } else { + if (obj[parts[i]] && utils.getFunctionName(obj[parts[i]].constructor) === 'Object') { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) { + obj = obj[parts[i]]; + } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { + obj = obj[parts[i]]; + } else { + obj = obj[parts[i]] = {}; + } + } + } +}; + +/** + * Gets a raw value from a path (no getters) + * + * @param {String} path + * @api private + */ + +Document.prototype.getValue = function(path) { + return utils.getValue(path, this._doc); +}; + +/** + * Sets a raw value for a path (no casting, setters, transformations) + * + * @param {String} path + * @param {Object} value + * @api private + */ + +Document.prototype.setValue = function(path, val) { + utils.setValue(path, val, this._doc); + return this; +}; + +/** + * Returns the value of a path. + * + * ####Example + * + * // path + * doc.get('age') // 47 + * + * // dynamic casting to a string + * doc.get('age', String) // "47" + * + * @param {String} path + * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes + * @api public + */ + +Document.prototype.get = function(path, type) { + var adhoc; + if (type) { + adhoc = Schema.interpretAsType(path, type, this.schema.options); + } + + var schema = this.$__path(path) || this.schema.virtualpath(path), + pieces = path.split('.'), + obj = this._doc; + + for (var i = 0, l = pieces.length; i < l; i++) { + obj = obj === null || obj === void 0 + ? undefined + : obj[pieces[i]]; + } + + if (adhoc) { + obj = adhoc.cast(obj); + } + + // Check if this path is populated - don't apply getters if it is, + // because otherwise its a nested object. See gh-3357 + if (schema && !this.populated(path)) { + obj = schema.applyGetters(obj, this); + } + + return obj; +}; + +/** + * Returns the schematype for the given `path`. + * + * @param {String} path + * @api private + * @method $__path + * @memberOf Document + */ + +Document.prototype.$__path = function(path) { + var adhocs = this.$__.adhocPaths, + adhocType = adhocs && adhocs[path]; + + if (adhocType) { + return adhocType; + } + return this.schema.path(path); +}; + +/** + * Marks the path as having pending changes to write to the db. + * + * _Very helpful when using [Mixed](./schematypes.html#mixed) types._ + * + * ####Example: + * + * doc.mixed.type = 'changed'; + * doc.markModified('mixed.type'); + * doc.save() // changes to mixed.type are now persisted + * + * @param {String} path the path to mark modified + * @api public + */ + +Document.prototype.markModified = function(path) { + this.$__.activePaths.modify(path); +}; + +/** + * Returns the list of paths that have been modified. + * + * @return {Array} + * @api public + */ + +Document.prototype.modifiedPaths = function() { + var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); + + return directModifiedPaths.reduce(function(list, path) { + var parts = path.split('.'); + return list.concat(parts.reduce(function(chains, part, i) { + return chains.concat(parts.slice(0, i).concat(part).join('.')); + }, [])); + }, []); +}; + +/** + * Returns true if this document was modified, else false. + * + * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. + * + * ####Example + * + * doc.set('documents.0.title', 'changed'); + * doc.isModified() // true + * doc.isModified('documents') // true + * doc.isModified('documents.0.title') // true + * doc.isDirectModified('documents') // false + * + * @param {String} [path] optional + * @return {Boolean} + * @api public + */ + +Document.prototype.isModified = function(path) { + return path + ? !!~this.modifiedPaths().indexOf(path) + : this.$__.activePaths.some('modify'); +}; + +/** + * Checks if a path is set to its default. + * + * ####Example + * + * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} }); + * var m = new MyModel(); + * m.$isDefault('name'); // true + * + * @param {String} [path] + * @return {Boolean} + * @method $isDefault + * @api public + */ + +Document.prototype.$isDefault = function(path) { + return (path in this.$__.activePaths.states.default); +}; + +/** + * Returns true if `path` was directly set and modified, else false. + * + * ####Example + * + * doc.set('documents.0.title', 'changed'); + * doc.isDirectModified('documents.0.title') // true + * doc.isDirectModified('documents') // false + * + * @param {String} path + * @return {Boolean} + * @api public + */ + +Document.prototype.isDirectModified = function(path) { + return (path in this.$__.activePaths.states.modify); +}; + +/** + * Checks if `path` was initialized. + * + * @param {String} path + * @return {Boolean} + * @api public + */ + +Document.prototype.isInit = function(path) { + return (path in this.$__.activePaths.states.init); +}; + +/** + * Checks if `path` was selected in the source query which initialized this document. + * + * ####Example + * + * Thing.findOne().select('name').exec(function (err, doc) { + * doc.isSelected('name') // true + * doc.isSelected('age') // false + * }) + * + * @param {String} path + * @return {Boolean} + * @api public + */ + +Document.prototype.isSelected = function isSelected(path) { + if (this.$__.selected) { + if (path === '_id') { + return this.$__.selected._id !== 0; + } + + var paths = Object.keys(this.$__.selected), + i = paths.length, + inclusive = false, + cur; + + if (i === 1 && paths[0] === '_id') { + // only _id was selected. + return this.$__.selected._id === 0; + } + + while (i--) { + cur = paths[i]; + if (cur === '_id') { + continue; + } + inclusive = !!this.$__.selected[cur]; + break; + } + + if (path in this.$__.selected) { + return inclusive; + } + + i = paths.length; + var pathDot = path + '.'; + + while (i--) { + cur = paths[i]; + if (cur === '_id') { + continue; + } + + if (cur.indexOf(pathDot) === 0) { + return inclusive; + } + + if (pathDot.indexOf(cur + '.') === 0) { + return inclusive; + } + } + + return !inclusive; + } + + return true; +}; + +/** + * Executes registered validation rules for this document. + * + * ####Note: + * + * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. + * + * ####Example: + * + * doc.validate(function (err) { + * if (err) handleError(err); + * else // validation passed + * }); + * + * @param {Object} optional options internal options + * @param {Function} optional callback called after validation completes, passing an error if one occurred + * @return {Promise} Promise + * @api public + */ + +Document.prototype.validate = function(options, callback) { + var _this = this; + var Promise = PromiseProvider.get(); + if (typeof options === 'function') { + callback = options; + options = null; + } + + if (options && options.__noPromise) { + this.$__validate(callback); + return; + } + + return new Promise.ES6(function(resolve, reject) { + _this.$__validate(function(error) { + callback && callback(error); + if (error) { + reject(error); + return; + } + resolve(); + }); + }); +}; + +/*! + * ignore + */ + +Document.prototype.$__validate = function(callback) { + var _this = this; + var _complete = function() { + var err = _this.$__.validationError; + _this.$__.validationError = undefined; + _this.emit('validate', _this); + if (err) { + for (var key in err.errors) { + // Make sure cast errors persist + if (!_this.__parent && err.errors[key] instanceof MongooseError.CastError) { + _this.invalidate(key, err.errors[key]); + } + } + + return err; + } + }; + + // only validate required fields when necessary + var paths = Object.keys(this.$__.activePaths.states.require).filter(function(path) { + if (!_this.isSelected(path) && !_this.isModified(path)) { + return false; + } + return true; + }); + + paths = paths.concat(Object.keys(this.$__.activePaths.states.init)); + paths = paths.concat(Object.keys(this.$__.activePaths.states.modify)); + paths = paths.concat(Object.keys(this.$__.activePaths.states.default)); + + if (paths.length === 0) { + process.nextTick(function() { + var err = _complete(); + if (err) { + callback(err); + return; + } + callback(); + }); + } + + var validating = {}, + total = 0; + + // gh-661: if a whole array is modified, make sure to run validation on all + // the children as well + for (var i = 0; i < paths.length; ++i) { + var path = paths[i]; + var val = _this.getValue(path); + if (val && val.isMongooseArray && !Buffer.isBuffer(val) && !val.isMongooseDocumentArray) { + var numElements = val.length; + for (var j = 0; j < numElements; ++j) { + paths.push(path + '.' + j); + } + } + } + + var complete = function() { + var err = _complete(); + if (err) { + callback(err); + return; + } + callback(); + }; + + var validatePath = function(path) { + if (validating[path]) { + return; + } + + validating[path] = true; + total++; + + process.nextTick(function() { + var p = _this.schema.path(path); + if (!p) { + return --total || complete(); + } + + // If user marked as invalid or there was a cast error, don't validate + if (!_this.$isValid(path)) { + --total || complete(); + return; + } + + var val = _this.getValue(path); + p.doValidate(val, function(err) { + if (err) { + _this.invalidate(path, err, undefined, true); + } + --total || complete(); + }, _this); + }); + }; + + paths.forEach(validatePath); +}; + +/** + * Executes registered validation rules (skipping asynchronous validators) for this document. + * + * ####Note: + * + * This method is useful if you need synchronous validation. + * + * ####Example: + * + * var err = doc.validateSync(); + * if ( err ){ + * handleError( err ); + * } else { + * // validation passed + * } + * + * @param {Array|string} pathsToValidate only validate the given paths + * @return {MongooseError|undefined} MongooseError if there are errors during validation, or undefined if there is no error. + * @api public + */ + +Document.prototype.validateSync = function(pathsToValidate) { + var _this = this; + + if (typeof pathsToValidate === 'string') { + pathsToValidate = pathsToValidate.split(' '); + } + + // only validate required fields when necessary + var paths = Object.keys(this.$__.activePaths.states.require).filter(function(path) { + if (!_this.isSelected(path) && !_this.isModified(path)) { + return false; + } + return true; + }); + + paths = paths.concat(Object.keys(this.$__.activePaths.states.init)); + paths = paths.concat(Object.keys(this.$__.activePaths.states.modify)); + paths = paths.concat(Object.keys(this.$__.activePaths.states.default)); + + if (pathsToValidate && pathsToValidate.length) { + var tmp = []; + for (var i = 0; i < paths.length; ++i) { + if (pathsToValidate.indexOf(paths[i]) !== -1) { + tmp.push(paths[i]); + } + } + paths = tmp; + } + + var validating = {}; + + paths.forEach(function(path) { + if (validating[path]) { + return; + } + + validating[path] = true; + + var p = _this.schema.path(path); + if (!p) { + return; + } + if (!_this.$isValid(path)) { + return; + } + + var val = _this.getValue(path); + var err = p.doValidateSync(val, _this); + if (err) { + _this.invalidate(path, err, undefined, true); + } + }); + + var err = _this.$__.validationError; + _this.$__.validationError = undefined; + _this.emit('validate', _this); + + if (err) { + for (var key in err.errors) { + // Make sure cast errors persist + if (err.errors[key] instanceof MongooseError.CastError) { + _this.invalidate(key, err.errors[key]); + } + } + } + + return err; +}; + +/** + * Marks a path as invalid, causing validation to fail. + * + * The `errorMsg` argument will become the message of the `ValidationError`. + * + * The `value` argument (if passed) will be available through the `ValidationError.value` property. + * + * doc.invalidate('size', 'must be less than 20', 14); + + * doc.validate(function (err) { + * console.log(err) + * // prints + * { message: 'Validation failed', + * name: 'ValidationError', + * errors: + * { size: + * { message: 'must be less than 20', + * name: 'ValidatorError', + * path: 'size', + * type: 'user defined', + * value: 14 } } } + * }) + * + * @param {String} path the field to invalidate + * @param {String|Error} errorMsg the error which states the reason `path` was invalid + * @param {Object|String|Number|any} value optional invalid value + * @api public + */ + +Document.prototype.invalidate = function(path, err, val) { + if (!this.$__.validationError) { + this.$__.validationError = new ValidationError(this); + } + + if (this.$__.validationError.errors[path]) { + return; + } + + if (!err || typeof err === 'string') { + err = new ValidatorError({ + path: path, + message: err, + type: 'user defined', + value: val + }); + } + + if (this.$__.validationError === err) { + return; + } + + this.$__.validationError.errors[path] = err; +}; + +/** + * Marks a path as valid, removing existing validation errors. + * + * @param {String} path the field to mark as valid + * @api private + * @method $markValid + * @receiver Document + */ + +Document.prototype.$markValid = function(path) { + if (!this.$__.validationError || !this.$__.validationError.errors[path]) { + return; + } + + delete this.$__.validationError.errors[path]; + if (Object.keys(this.$__.validationError.errors).length === 0) { + this.$__.validationError = null; + } +}; + +/** + * Checks if a path is invalid + * + * @param {String} path the field to check + * @method $isValid + * @api private + * @receiver Document + */ + +Document.prototype.$isValid = function(path) { + return !this.$__.validationError || !this.$__.validationError.errors[path]; +}; + +/** + * Resets the internal modified state of this document. + * + * @api private + * @return {Document} + * @method $__reset + * @memberOf Document + */ + +Document.prototype.$__reset = function reset() { + var _this = this; + DocumentArray || (DocumentArray = require('./types/documentarray')); + + this.$__.activePaths + .map('init', 'modify', function(i) { + return _this.getValue(i); + }) + .filter(function(val) { + return val && val instanceof Array && val.isMongooseDocumentArray && val.length; + }) + .forEach(function(array) { + var i = array.length; + while (i--) { + var doc = array[i]; + if (!doc) { + continue; + } + doc.$__reset(); + } + }); + + // clear atomics + this.$__dirty().forEach(function(dirt) { + var type = dirt.value; + if (type && type._atomics) { + type._atomics = {}; + } + }); + + // Clear 'dirty' cache + this.$__.activePaths.clear('modify'); + this.$__.activePaths.clear('default'); + this.$__.validationError = undefined; + this.errors = undefined; + _this = this; + this.schema.requiredPaths().forEach(function(path) { + _this.$__.activePaths.require(path); + }); + + return this; +}; + +/** + * Returns this documents dirty paths / vals. + * + * @api private + * @method $__dirty + * @memberOf Document + */ + +Document.prototype.$__dirty = function() { + var _this = this; + + var all = this.$__.activePaths.map('modify', function(path) { + return { + path: path, + value: _this.getValue(path), + schema: _this.$__path(path) + }; + }); + + // gh-2558: if we had to set a default and the value is not undefined, + // we have to save as well + all = all.concat(this.$__.activePaths.map('default', function(path) { + if (path === '_id' || !_this.getValue(path)) { + return; + } + return { + path: path, + value: _this.getValue(path), + schema: _this.$__path(path) + }; + })); + + // Sort dirty paths in a flat hierarchy. + all.sort(function(a, b) { + return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0)); + }); + + // Ignore "foo.a" if "foo" is dirty already. + var minimal = [], + lastPath, + top; + + all.forEach(function(item) { + if (!item) { + return; + } + if (item.path.indexOf(lastPath) !== 0) { + lastPath = item.path + '.'; + minimal.push(item); + top = item; + } else { + // special case for top level MongooseArrays + if (top.value && top.value._atomics && top.value.hasAtomics()) { + // the `top` array itself and a sub path of `top` are being modified. + // the only way to honor all of both modifications is through a $set + // of entire array. + top.value._atomics = {}; + top.value._atomics.$set = top.value; + } + } + }); + + top = lastPath = null; + return minimal; +}; + +/*! + * Compiles schemas. + */ + +function compile(tree, proto, prefix, options) { + var keys = Object.keys(tree), + i = keys.length, + limb, + key; + + while (i--) { + key = keys[i]; + limb = tree[key]; + + defineKey(key, + ((utils.getFunctionName(limb.constructor) === 'Object' + && Object.keys(limb).length) + && (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type)) + ? limb + : null) + , proto + , prefix + , keys + , options); + } +} + +// gets descriptors for all properties of `object` +// makes all properties non-enumerable to match previous behavior to #2211 +function getOwnPropertyDescriptors(object) { + var result = {}; + + Object.getOwnPropertyNames(object).forEach(function(key) { + result[key] = Object.getOwnPropertyDescriptor(object, key); + result[key].enumerable = true; + }); + + return result; +} + +/*! + * Defines the accessor named prop on the incoming prototype. + */ + +function defineKey(prop, subprops, prototype, prefix, keys, options) { + var path = (prefix ? prefix + '.' : '') + prop; + prefix = prefix || ''; + + if (subprops) { + Object.defineProperty(prototype, prop, { + enumerable: true, + configurable: true, + get: function() { + var _this = this; + if (!this.$__.getters) { + this.$__.getters = {}; + } + + if (!this.$__.getters[path]) { + var nested = Object.create(Object.getPrototypeOf(this), getOwnPropertyDescriptors(this)); + + // save scope for nested getters/setters + if (!prefix) { + nested.$__.scope = this; + } + + // shadow inherited getters from sub-objects so + // thing.nested.nested.nested... doesn't occur (gh-366) + var i = 0, + len = keys.length; + + for (; i < len; ++i) { + // over-write the parents getter without triggering it + Object.defineProperty(nested, keys[i], { + enumerable: false, // It doesn't show up. + writable: true, // We can set it later. + configurable: true, // We can Object.defineProperty again. + value: undefined // It shadows its parent. + }); + } + + Object.defineProperty(nested, 'toObject', { + enumerable: true, + configurable: true, + writable: false, + value: function() { + return _this.get(path); + } + }); + + Object.defineProperty(nested, 'toJSON', { + enumerable: true, + configurable: true, + writable: false, + value: function() { + return _this.get(path); + } + }); + + Object.defineProperty(nested, '$__isNested', { + enumerable: true, + configurable: true, + writable: false, + value: true + }); + + compile(subprops, nested, path, options); + this.$__.getters[path] = nested; + } + + return this.$__.getters[path]; + }, + set: function(v) { + if (v instanceof Document) { + v = v.toObject(); + } + return (this.$__.scope || this).set(path, v); + } + }); + } else { + Object.defineProperty(prototype, prop, { + enumerable: true, + configurable: true, + get: function() { + return this.get.call(this.$__.scope || this, path); + }, + set: function(v) { + return this.set.call(this.$__.scope || this, path, v); + } + }); + } +} + +/** + * Assigns/compiles `schema` into this documents prototype. + * + * @param {Schema} schema + * @api private + * @method $__setSchema + * @memberOf Document + */ + +Document.prototype.$__setSchema = function(schema) { + compile(schema.tree, this, undefined, schema.options); + this.schema = schema; +}; + + +/** + * Get active path that were changed and are arrays + * + * @api private + * @method $__getArrayPathsToValidate + * @memberOf Document + */ + +Document.prototype.$__getArrayPathsToValidate = function() { + DocumentArray || (DocumentArray = require('./types/documentarray')); + + // validate all document arrays. + return this.$__.activePaths + .map('init', 'modify', function(i) { + return this.getValue(i); + }.bind(this)) + .filter(function(val) { + return val && val instanceof Array && val.isMongooseDocumentArray && val.length; + }).reduce(function(seed, array) { + return seed.concat(array); + }, []) + .filter(function(doc) { + return doc; + }); +}; + + +/** + * Get all subdocs (by bfs) + * + * @api private + * @method $__getAllSubdocs + * @memberOf Document + */ + +Document.prototype.$__getAllSubdocs = function() { + DocumentArray || (DocumentArray = require('./types/documentarray')); + Embedded = Embedded || require('./types/embedded'); + + function docReducer(seed, path) { + var val = this[path]; + + if (val instanceof Embedded) { + seed.push(val); + } + if (val && val.$isSingleNested) { + seed = Object.keys(val._doc).reduce(docReducer.bind(val._doc), seed); + seed.push(val); + } + if (val && val.isMongooseDocumentArray) { + val.forEach(function _docReduce(doc) { + if (!doc || !doc._doc) { + return; + } + if (doc instanceof Embedded) { + seed.push(doc); + } + seed = Object.keys(doc._doc).reduce(docReducer.bind(doc._doc), seed); + }); + } else if (val instanceof Document && val.$__isNested) { + val = val.toObject(); + if (val) { + seed = Object.keys(val).reduce(docReducer.bind(val), seed); + } + } + return seed; + } + + var subDocs = Object.keys(this._doc).reduce(docReducer.bind(this), []); + + return subDocs; +}; + +/** + * Executes methods queued from the Schema definition + * + * @api private + * @method $__registerHooksFromSchema + * @memberOf Document + */ + +Document.prototype.$__registerHooksFromSchema = function() { + Embedded = Embedded || require('./types/embedded'); + var Promise = PromiseProvider.get(); + + var _this = this; + var q = _this.schema && _this.schema.callQueue; + if (!q.length) { + return _this; + } + + // we are only interested in 'pre' hooks, and group by point-cut + var toWrap = q.reduce(function(seed, pair) { + if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { + _this[pair[0]].apply(_this, pair[1]); + return seed; + } + var args = [].slice.call(pair[1]); + var pointCut = pair[0] === 'on' ? 'post' : args[0]; + if (!(pointCut in seed)) { + seed[pointCut] = {post: [], pre: []}; + } + if (pair[0] === 'post') { + seed[pointCut].post.push(args); + } else if (pair[0] === 'on') { + seed[pointCut].push(args); + } else { + seed[pointCut].pre.push(args); + } + return seed; + }, {post: []}); + + // 'post' hooks are simpler + toWrap.post.forEach(function(args) { + _this.on.apply(_this, args); + }); + delete toWrap.post; + + // 'init' should be synchronous on subdocuments + if (toWrap.init && _this instanceof Embedded) { + if (toWrap.init.pre) { + toWrap.init.pre.forEach(function(args) { + _this.pre.apply(_this, args); + }); + } + if (toWrap.init.post) { + toWrap.init.post.forEach(function(args) { + _this.post.apply(_this, args); + }); + } + delete toWrap.init; + } else if (toWrap.set) { + // Set hooks also need to be sync re: gh-3479 + if (toWrap.set.pre) { + toWrap.set.pre.forEach(function(args) { + _this.pre.apply(_this, args); + }); + } + if (toWrap.set.post) { + toWrap.set.post.forEach(function(args) { + _this.post.apply(_this, args); + }); + } + delete toWrap.set; + } + + Object.keys(toWrap).forEach(function(pointCut) { + // this is so we can wrap everything into a promise; + var newName = ('$__original_' + pointCut); + if (!_this[pointCut]) { + return; + } + _this[newName] = _this[pointCut]; + _this[pointCut] = function wrappedPointCut() { + var args = [].slice.call(arguments); + var lastArg = args.pop(); + var fn; + + return new Promise.ES6(function(resolve, reject) { + if (lastArg && typeof lastArg !== 'function') { + args.push(lastArg); + } else { + fn = lastArg; + } + args.push(function(error, result) { + if (error) { + _this.$__handleReject(error); + fn && fn(error); + reject(error); + return; + } + + fn && fn.apply(null, [null].concat(Array.prototype.slice.call(arguments, 1))); + resolve(result); + }); + + _this[newName].apply(_this, args); + }); + }; + + toWrap[pointCut].pre.forEach(function(args) { + args[0] = newName; + _this.pre.apply(_this, args); + }); + toWrap[pointCut].post.forEach(function(args) { + args[0] = newName; + _this.post.apply(_this, args); + }); + }); + return _this; +}; + +Document.prototype.$__handleReject = function handleReject(err) { + // emit on the Model if listening + if (this.listeners('error').length) { + this.emit('error', err); + } else if (this.constructor.listeners && this.constructor.listeners('error').length) { + this.constructor.emit('error', err); + } else if (this.listeners && this.listeners('error').length) { + this.emit('error', err); + } +}; + +/** + * Internal helper for toObject() and toJSON() that doesn't manipulate options + * + * @api private + * @method $toObject + * @memberOf Document + */ + +Document.prototype.$toObject = function(options, json) { + var defaultOptions = {transform: true, json: json}; + + if (options && options.depopulate && !options._skipDepopulateTopLevel && this.$__.wasPopulated) { + // populated paths that we set to a document + return clone(this._id, options); + } + + // If we're calling toObject on a populated doc, we may want to skip + // depopulated on the top level + if (options && options._skipDepopulateTopLevel) { + options._skipDepopulateTopLevel = false; + } + + // When internally saving this document we always pass options, + // bypassing the custom schema options. + if (!(options && utils.getFunctionName(options.constructor) === 'Object') || + (options && options._useSchemaOptions)) { + if (json) { + options = this.schema.options.toJSON ? + clone(this.schema.options.toJSON) : + {}; + options.json = true; + options._useSchemaOptions = true; + } else { + options = this.schema.options.toObject ? + clone(this.schema.options.toObject) : + {}; + options.json = false; + options._useSchemaOptions = true; + } + } + + for (var key in defaultOptions) { + if (options[key] === undefined) { + options[key] = defaultOptions[key]; + } + } + + ('minimize' in options) || (options.minimize = this.schema.options.minimize); + + // remember the root transform function + // to save it from being overwritten by sub-transform functions + var originalTransform = options.transform; + + var ret = clone(this._doc, options) || {}; + + if (options.getters) { + applyGetters(this, ret, 'paths', options); + // applyGetters for paths will add nested empty objects; + // if minimize is set, we need to remove them. + if (options.minimize) { + ret = minimize(ret) || {}; + } + } + + if (options.virtuals || options.getters && options.virtuals !== false) { + applyGetters(this, ret, 'virtuals', options); + } + + if (options.versionKey === false && this.schema.options.versionKey) { + delete ret[this.schema.options.versionKey]; + } + + var transform = options.transform; + + // In the case where a subdocument has its own transform function, we need to + // check and see if the parent has a transform (options.transform) and if the + // child schema has a transform (this.schema.options.toObject) In this case, + // we need to adjust options.transform to be the child schema's transform and + // not the parent schema's + if (transform === true || + (this.schema.options.toObject && transform)) { + var opts = options.json ? this.schema.options.toJSON : this.schema.options.toObject; + + if (opts) { + transform = (typeof options.transform === 'function' ? options.transform : opts.transform); + } + } else { + options.transform = originalTransform; + } + + if (typeof transform === 'function') { + var xformed = transform(this, ret, options); + if (typeof xformed !== 'undefined') { + ret = xformed; + } + } + + return ret; +}; + +/** + * Converts this document into a plain javascript object, ready for storage in MongoDB. + * + * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. + * + * ####Options: + * + * - `getters` apply all getters (path and virtual getters) + * - `virtuals` apply virtual getters (can override `getters` option) + * - `minimize` remove empty objects (defaults to true) + * - `transform` a transform function to apply to the resulting document before returning + * - `depopulate` depopulate any populated paths, replacing them with their original refs (defaults to false) + * - `versionKey` whether to include the version key (defaults to true) + * - `retainKeyOrder` keep the order of object keys. If this is set to true, `Object.keys(new Doc({ a: 1, b: 2}).toObject())` will always produce `['a', 'b']` (defaults to false) + * + * ####Getters/Virtuals + * + * Example of only applying path getters + * + * doc.toObject({ getters: true, virtuals: false }) + * + * Example of only applying virtual getters + * + * doc.toObject({ virtuals: true }) + * + * Example of applying both path and virtual getters + * + * doc.toObject({ getters: true }) + * + * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. + * + * schema.set('toObject', { virtuals: true }) + * + * ####Transform + * + * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. + * + * Transform functions receive three arguments + * + * function (doc, ret, options) {} + * + * - `doc` The mongoose document which is being converted + * - `ret` The plain object representation which has been converted + * - `options` The options in use (either schema options or the options passed inline) + * + * ####Example + * + * // specify the transform schema option + * if (!schema.options.toObject) schema.options.toObject = {}; + * schema.options.toObject.transform = function (doc, ret, options) { + * // remove the _id of every document before returning the result + * delete ret._id; + * } + * + * // without the transformation in the schema + * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } + * + * // with the transformation + * doc.toObject(); // { name: 'Wreck-it Ralph' } + * + * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: + * + * if (!schema.options.toObject) schema.options.toObject = {}; + * schema.options.toObject.transform = function (doc, ret, options) { + * return { movie: ret.name } + * } + * + * // without the transformation in the schema + * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } + * + * // with the transformation + * doc.toObject(); // { movie: 'Wreck-it Ralph' } + * + * _Note: if a transform function returns `undefined`, the return value will be ignored._ + * + * Transformations may also be applied inline, overridding any transform set in the options: + * + * function xform (doc, ret, options) { + * return { inline: ret.name, custom: true } + * } + * + * // pass the transform as an inline option + * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } + * + * _Note: if you call `toObject` and pass any options, the transform declared in your schema options will __not__ be applied. To force its application pass `transform: true`_ + * + * if (!schema.options.toObject) schema.options.toObject = {}; + * schema.options.toObject.hide = '_id'; + * schema.options.toObject.transform = function (doc, ret, options) { + * if (options.hide) { + * options.hide.split(' ').forEach(function (prop) { + * delete ret[prop]; + * }); + * } + * } + * + * var doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); + * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } + * doc.toObject({ hide: 'secret _id' }); // { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } + * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } + * + * Transforms are applied _only to the document and are not applied to sub-documents_. + * + * Transforms, like all of these options, are also available for `toJSON`. + * + * See [schema options](/docs/guide.html#toObject) for some more details. + * + * _During save, no custom options are applied to the document before being sent to the database._ + * + * @param {Object} [options] + * @return {Object} js object + * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html + * @api public + */ + +Document.prototype.toObject = function(options) { + return this.$toObject(options); +}; + +/*! + * Minimizes an object, removing undefined values and empty objects + * + * @param {Object} object to minimize + * @return {Object} + */ + +function minimize(obj) { + var keys = Object.keys(obj), + i = keys.length, + hasKeys, + key, + val; + + while (i--) { + key = keys[i]; + val = obj[key]; + + if (utils.isObject(val)) { + obj[key] = minimize(val); + } + + if (undefined === obj[key]) { + delete obj[key]; + continue; + } + + hasKeys = true; + } + + return hasKeys + ? obj + : undefined; +} + +/*! + * Applies virtuals properties to `json`. + * + * @param {Document} self + * @param {Object} json + * @param {String} type either `virtuals` or `paths` + * @return {Object} `json` + */ + +function applyGetters(self, json, type, options) { + var schema = self.schema, + paths = Object.keys(schema[type]), + i = paths.length, + path; + + while (i--) { + path = paths[i]; + + var parts = path.split('.'), + plen = parts.length, + last = plen - 1, + branch = json, + part; + + for (var ii = 0; ii < plen; ++ii) { + part = parts[ii]; + if (ii === last) { + branch[part] = clone(self.get(path), options); + } else { + branch = branch[part] || (branch[part] = {}); + } + } + } + + return json; +} + +/** + * The return value of this method is used in calls to JSON.stringify(doc). + * + * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. + * + * schema.set('toJSON', { virtuals: true }) + * + * See [schema options](/docs/guide.html#toJSON) for details. + * + * @param {Object} options + * @return {Object} + * @see Document#toObject #document_Document-toObject + * @api public + */ + +Document.prototype.toJSON = function(options) { + return this.$toObject(options, true); +}; + +/** + * Helper for console.log + * + * @api public + */ + +Document.prototype.inspect = function(options) { + var opts = options && utils.getFunctionName(options.constructor) === 'Object' ? options : {}; + opts.minimize = false; + opts.retainKeyOrder = true; + return this.toObject(opts); +}; + +/** + * Helper for console.log + * + * @api public + * @method toString + */ + +Document.prototype.toString = function() { + return inspect(this.inspect()); +}; + +/** + * Returns true if the Document stores the same data as doc. + * + * Documents are considered equal when they have matching `_id`s, unless neither + * document has an `_id`, in which case this function falls back to using + * `deepEqual()`. + * + * @param {Document} doc a document to compare + * @return {Boolean} + * @api public + */ + +Document.prototype.equals = function(doc) { + var tid = this.get('_id'); + var docid = doc.get ? doc.get('_id') : doc; + if (!tid && !docid) { + return deepEqual(this, doc); + } + return tid && tid.equals + ? tid.equals(docid) + : tid === docid; +}; + +/** + * Populates document references, executing the `callback` when complete. + * + * ####Example: + * + * doc + * .populate('company') + * .populate({ + * path: 'notes', + * match: /airline/, + * select: 'text', + * model: 'modelName' + * options: opts + * }, function (err, user) { + * assert(doc._id === user._id) // the document itself is passed + * }) + * + * // summary + * doc.populate(path) // not executed + * doc.populate(options); // not executed + * doc.populate(path, callback) // executed + * doc.populate(options, callback); // executed + * doc.populate(callback); // executed + * + * + * ####NOTE: + * + * Population does not occur unless a `callback` is passed *or* you explicitly + * call `execPopulate()`. + * Passing the same path a second time will overwrite the previous path options. + * See [Model.populate()](#model_Model.populate) for explaination of options. + * + * @see Model.populate #model_Model.populate + * @param {String|Object} [path] The path to populate or an options object + * @param {Function} [callback] When passed, population is invoked + * @api public + * @return {Document} this + */ + +Document.prototype.populate = function populate() { + if (arguments.length === 0) { + return this; + } + + var pop = this.$__.populate || (this.$__.populate = {}); + var args = utils.args(arguments); + var fn; + + if (typeof args[args.length - 1] === 'function') { + fn = args.pop(); + } + + // allow `doc.populate(callback)` + if (args.length) { + // use hash to remove duplicate paths + var res = utils.populate.apply(null, args); + for (var i = 0; i < res.length; ++i) { + pop[res[i].path] = res[i]; + } + } + + if (fn) { + var paths = utils.object.vals(pop); + this.$__.populate = undefined; + paths.__noPromise = true; + this.constructor.populate(this, paths, fn); + } + + return this; +}; + +/** + * Explicitly executes population and returns a promise. Useful for ES6 + * integration. + * + * ####Example: + * + * var promise = doc. + * populate('company'). + * populate({ + * path: 'notes', + * match: /airline/, + * select: 'text', + * model: 'modelName' + * options: opts + * }). + * execPopulate(); + * + * // summary + * doc.execPopulate() + * + * + * @see Document.populate #Document_model.populate + * @api public + * @return {Promise} promise that resolves to the document when population is done + */ + +Document.prototype.execPopulate = function() { + var Promise = PromiseProvider.get(); + var _this = this; + return new Promise.ES6(function(resolve, reject) { + _this.populate(function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * Gets _id(s) used during population of the given `path`. + * + * ####Example: + * + * Model.findOne().populate('author').exec(function (err, doc) { + * console.log(doc.author.name) // Dr.Seuss + * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' + * }) + * + * If the path was not populated, undefined is returned. + * + * @param {String} path + * @return {Array|ObjectId|Number|Buffer|String|undefined} + * @api public + */ + +Document.prototype.populated = function(path, val, options) { + // val and options are internal + + if (val === null || val === void 0) { + if (!this.$__.populated) { + return undefined; + } + var v = this.$__.populated[path]; + if (v) { + return v.value; + } + return undefined; + } + + // internal + + if (val === true) { + if (!this.$__.populated) { + return undefined; + } + return this.$__.populated[path]; + } + + this.$__.populated || (this.$__.populated = {}); + this.$__.populated[path] = {value: val, options: options}; + return val; +}; + +/** + * Takes a populated field and returns it to its unpopulated state. + * + * ####Example: + * + * Model.findOne().populate('author').exec(function (err, doc) { + * console.log(doc.author.name); // Dr.Seuss + * console.log(doc.depopulate('author')); + * console.log(doc.author); // '5144cf8050f071d979c118a7' + * }) + * + * If the path was not populated, this is a no-op. + * + * @param {String} path + * @api public + */ + +Document.prototype.depopulate = function(path) { + var populatedIds = this.populated(path); + if (!populatedIds) { + return; + } + delete this.$__.populated[path]; + this.set(path, populatedIds); +}; + + +/** + * Returns the full path to this document. + * + * @param {String} [path] + * @return {String} + * @api private + * @method $__fullPath + * @memberOf Document + */ + +Document.prototype.$__fullPath = function(path) { + // overridden in SubDocuments + return path || ''; +}; + +/*! + * Module exports. + */ + +Document.ValidationError = ValidationError; +module.exports = exports = Document; diff --git a/5-3/node_modules/mongoose/lib/document_provider.js b/5-3/node_modules/mongoose/lib/document_provider.js new file mode 100644 index 0000000..10087cc --- /dev/null +++ b/5-3/node_modules/mongoose/lib/document_provider.js @@ -0,0 +1,21 @@ +'use strict'; + +/* eslint-env browser */ + +/*! + * Module dependencies. + */ +var Document = require('./document.js'); +var BrowserDocument = require('./browserDocument.js'); + +/** + * Returns the Document constructor for the current context + * + * @api private + */ +module.exports = function() { + if (typeof window !== 'undefined' && typeof document !== 'undefined' && document === window.document) { + return BrowserDocument; + } + return Document; +}; diff --git a/5-3/node_modules/mongoose/lib/drivers/SPEC.md b/5-3/node_modules/mongoose/lib/drivers/SPEC.md new file mode 100644 index 0000000..6464693 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/SPEC.md @@ -0,0 +1,4 @@ + +# Driver Spec + +TODO diff --git a/5-3/node_modules/mongoose/lib/drivers/browser/ReadPreference.js b/5-3/node_modules/mongoose/lib/drivers/browser/ReadPreference.js new file mode 100644 index 0000000..f20cd6c --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/browser/ReadPreference.js @@ -0,0 +1,5 @@ +/*! + * ignore + */ + +module.exports = function() {}; diff --git a/5-3/node_modules/mongoose/lib/drivers/browser/binary.js b/5-3/node_modules/mongoose/lib/drivers/browser/binary.js new file mode 100644 index 0000000..4d7a395 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/browser/binary.js @@ -0,0 +1,12 @@ + +/*! + * Module dependencies. + */ + +var Binary = require('bson').Binary; + +/*! + * Module exports. + */ + +module.exports = exports = Binary; diff --git a/5-3/node_modules/mongoose/lib/drivers/browser/index.js b/5-3/node_modules/mongoose/lib/drivers/browser/index.js new file mode 100644 index 0000000..fa5dbb4 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/browser/index.js @@ -0,0 +1,7 @@ +/*! + * Module exports. + */ + +exports.Binary = require('./binary'); +exports.ObjectId = require('./objectid'); +exports.ReadPreference = require('./ReadPreference'); diff --git a/5-3/node_modules/mongoose/lib/drivers/browser/objectid.js b/5-3/node_modules/mongoose/lib/drivers/browser/objectid.js new file mode 100644 index 0000000..e63c04a --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/browser/objectid.js @@ -0,0 +1,14 @@ + +/*! + * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId + * @constructor NodeMongoDbObjectId + * @see ObjectId + */ + +var ObjectId = require('bson').ObjectID; + +/*! + * ignore + */ + +module.exports = exports = ObjectId; diff --git a/5-3/node_modules/mongoose/lib/drivers/index.js b/5-3/node_modules/mongoose/lib/drivers/index.js new file mode 100644 index 0000000..5a842ba --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/index.js @@ -0,0 +1,17 @@ +/*! + * ignore + */ + +var driver; + +if (typeof window === 'undefined') { + driver = require(global.MONGOOSE_DRIVER_PATH || './node-mongodb-native'); +} else { + driver = require('./browser'); +} + +/*! + * ignore + */ + +module.exports = driver; diff --git a/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js new file mode 100644 index 0000000..e921d60 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js @@ -0,0 +1,45 @@ +/*! + * Module dependencies. + */ + +var mongodb = require('mongodb'); +var ReadPref = mongodb.ReadPreference; + +/*! + * Converts arguments to ReadPrefs the driver + * can understand. + * + * @param {String|Array} pref + * @param {Array} [tags] + */ + +module.exports = function readPref(pref, tags) { + if (Array.isArray(pref)) { + tags = pref[1]; + pref = pref[0]; + } + + if (pref instanceof ReadPref) { + return pref; + } + + switch (pref) { + case 'p': + pref = 'primary'; + break; + case 'pp': + pref = 'primaryPreferred'; + break; + case 's': + pref = 'secondary'; + break; + case 'sp': + pref = 'secondaryPreferred'; + break; + case 'n': + pref = 'nearest'; + break; + } + + return new ReadPref(pref, tags); +}; diff --git a/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js new file mode 100644 index 0000000..657efde --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js @@ -0,0 +1,8 @@ + +/*! + * Module dependencies. + */ + +var Binary = require('mongodb').Binary; + +module.exports = exports = Binary; diff --git a/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js new file mode 100644 index 0000000..5fc7319 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js @@ -0,0 +1,245 @@ +/*! + * Module dependencies. + */ + +var MongooseCollection = require('../../collection'), + Collection = require('mongodb').Collection, + utils = require('../../utils'); + +/** + * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation. + * + * All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management. + * + * @inherits Collection + * @api private + */ + +function NativeCollection() { + this.collection = null; + MongooseCollection.apply(this, arguments); +} + +/*! + * Inherit from abstract Collection. + */ + +NativeCollection.prototype.__proto__ = MongooseCollection.prototype; + +/** + * Called when the connection opens. + * + * @api private + */ + +NativeCollection.prototype.onOpen = function() { + var _this = this; + + // always get a new collection in case the user changed host:port + // of parent db instance when re-opening the connection. + + if (!_this.opts.capped.size) { + // non-capped + return _this.conn.db.collection(_this.name, callback); + } + + // capped + return _this.conn.db.collection(_this.name, function(err, c) { + if (err) return callback(err); + + // discover if this collection exists and if it is capped + _this.conn.db.listCollections({name: _this.name}).toArray(function(err, docs) { + if (err) { + return callback(err); + } + var doc = docs[0]; + var exists = !!doc; + + if (exists) { + if (doc.options && doc.options.capped) { + callback(null, c); + } else { + var msg = 'A non-capped collection exists with the name: ' + _this.name + '\n\n' + + ' To use this collection as a capped collection, please ' + + 'first convert it.\n' + + ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped'; + err = new Error(msg); + callback(err); + } + } else { + // create + var opts = utils.clone(_this.opts.capped); + opts.capped = true; + _this.conn.db.createCollection(_this.name, opts, callback); + } + }); + }); + + function callback(err, collection) { + if (err) { + // likely a strict mode error + _this.conn.emit('error', err); + } else { + _this.collection = collection; + MongooseCollection.prototype.onOpen.call(_this); + } + } +}; + +/** + * Called when the connection closes + * + * @api private + */ + +NativeCollection.prototype.onClose = function() { + MongooseCollection.prototype.onClose.call(this); +}; + +/*! + * Copy the collection methods and make them subject to queues + */ + +function iter(i) { + NativeCollection.prototype[i] = function() { + if (this.buffer) { + this.addQueue(i, arguments); + return; + } + + var collection = this.collection, + args = arguments, + _this = this, + debug = _this.conn.base.options.debug; + + if (debug) { + if (typeof debug === 'function') { + debug.apply(debug + , [_this.name, i].concat(utils.args(args, 0, args.length - 1))); + } else { + this.$print(_this.name, i, args); + } + } + + return collection[i].apply(collection, args); + }; +} + +for (var i in Collection.prototype) { + // Janky hack to work around gh-3005 until we can get rid of the mongoose + // collection abstraction + try { + if (typeof Collection.prototype[i] !== 'function') { + continue; + } + } catch (e) { + continue; + } + + iter(i); +} + +/** + * Debug print helper + * + * @api public + * @method $print + */ + +NativeCollection.prototype.$print = function(name, i, args) { + console.error( + '\x1B[0;36mMongoose:\x1B[0m %s.%s(%s) %s %s %s', + name, + i, + this.$format(args[0]), + this.$format(args[1]), + this.$format(args[2]), + this.$format(args[3])); +}; + +/** + * Formatter for debug print args + * + * @api public + * @method $format + */ + +NativeCollection.prototype.$format = function(arg) { + var type = typeof arg; + if (type === 'function' || type === 'undefined') return ''; + return format(arg); +}; + +/*! + * Debug print helper + */ + +function map(o) { + return format(o, true); +} +function formatObjectId(x, key) { + var representation = 'ObjectId("' + x[key].toHexString() + '")'; + x[key] = {inspect: function() { return representation; }}; +} +function formatDate(x, key) { + var representation = 'new Date("' + x[key].toUTCString() + '")'; + x[key] = {inspect: function() { return representation; }}; +} +function format(obj, sub) { + var x = utils.clone(obj, {retainKeyOrder: 1}); + var representation; + + if (x != null) { + if (x.constructor.name === 'Binary') { + x = '[object Buffer]'; + } else if (x.constructor.name === 'ObjectID') { + representation = 'ObjectId("' + x.toHexString() + '")'; + x = {inspect: function() { return representation; }}; + } else if (x.constructor.name === 'Date') { + representation = 'new Date("' + x.toUTCString() + '")'; + x = {inspect: function() { return representation; }}; + } else if (x.constructor.name === 'Object') { + var keys = Object.keys(x); + var numKeys = keys.length; + var key; + for (var i = 0; i < numKeys; ++i) { + key = keys[i]; + if (x[key]) { + if (x[key].constructor.name === 'Binary') { + x[key] = '[object Buffer]'; + } else if (x[key].constructor.name === 'Object') { + x[key] = format(x[key], true); + } else if (x[key].constructor.name === 'ObjectID') { + formatObjectId(x, key); + } else if (x[key].constructor.name === 'Date') { + formatDate(x, key); + } else if (Array.isArray(x[key])) { + x[key] = x[key].map(map); + } + } + } + } + if (sub) return x; + } + + return require('util') + .inspect(x, false, 10, true) + .replace(/\n/g, '') + .replace(/\s{2,}/g, ' '); +} + +/** + * Retreives information about this collections indexes. + * + * @param {Function} callback + * @method getIndexes + * @api public + */ + +NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation; + +/*! + * Module exports. + */ + +module.exports = NativeCollection; diff --git a/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js new file mode 100644 index 0000000..0e417f7 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js @@ -0,0 +1,357 @@ +/*! + * Module dependencies. + */ + +var MongooseConnection = require('../../connection'), + mongo = require('mongodb'), + Db = mongo.Db, + Server = mongo.Server, + Mongos = mongo.Mongos, + STATES = require('../../connectionstate'), + ReplSetServers = mongo.ReplSet; + +/** + * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation. + * + * @inherits Connection + * @api private + */ + +function NativeConnection() { + MongooseConnection.apply(this, arguments); + this._listening = false; +} + +/** + * Expose the possible connection states. + * @api public + */ + +NativeConnection.STATES = STATES; + +/*! + * Inherits from Connection. + */ + +NativeConnection.prototype.__proto__ = MongooseConnection.prototype; + +/** + * Opens the connection to MongoDB. + * + * @param {Function} fn + * @return {Connection} this + * @api private + */ + +NativeConnection.prototype.doOpen = function(fn) { + var server = new Server(this.host, this.port, this.options.server); + + if (this.options && this.options.mongos) { + var mongos = new Mongos([server], this.options.mongos); + this.db = new Db(this.name, mongos, this.options.db); + } else { + this.db = new Db(this.name, server, this.options.db); + } + + var _this = this; + this.db.open(function(err) { + if (err) return fn(err); + listen(_this); + fn(); + }); + + return this; +}; + +/** + * Switches to a different database using the same connection pool. + * + * Returns a new connection object, with the new db. + * + * @param {String} name The database name + * @return {Connection} New Connection Object + * @api public + */ + +NativeConnection.prototype.useDb = function(name) { + // we have to manually copy all of the attributes... + var newConn = new this.constructor(); + newConn.name = name; + newConn.base = this.base; + newConn.collections = {}; + newConn.models = {}; + newConn.replica = this.replica; + newConn.hosts = this.hosts; + newConn.host = this.host; + newConn.port = this.port; + newConn.user = this.user; + newConn.pass = this.pass; + newConn.options = this.options; + newConn._readyState = this._readyState; + newConn._closeCalled = this._closeCalled; + newConn._hasOpened = this._hasOpened; + newConn._listening = false; + + // First, when we create another db object, we are not guaranteed to have a + // db object to work with. So, in the case where we have a db object and it + // is connected, we can just proceed with setting everything up. However, if + // we do not have a db or the state is not connected, then we need to wait on + // the 'open' event of the connection before doing the rest of the setup + // the 'connected' event is the first time we'll have access to the db object + + var _this = this; + + if (this.db && this._readyState === STATES.connected) { + wireup(); + } else { + this.once('connected', wireup); + } + + function wireup() { + newConn.db = _this.db.db(name); + newConn.onOpen(); + // setup the events appropriately + listen(newConn); + } + + newConn.name = name; + + // push onto the otherDbs stack, this is used when state changes + this.otherDbs.push(newConn); + newConn.otherDbs.push(this); + + return newConn; +}; + +/*! + * Register listeners for important events and bubble appropriately. + */ + +function listen(conn) { + if (conn.db._listening) { + return; + } + conn.db._listening = true; + + conn.db.on('close', function() { + if (conn._closeCalled) return; + + // the driver never emits an `open` event. auto_reconnect still + // emits a `close` event but since we never get another + // `open` we can't emit close + if (conn.db.serverConfig.autoReconnect) { + conn.readyState = STATES.disconnected; + conn.emit('close'); + return; + } + conn.onClose(); + }); + conn.db.on('error', function(err) { + conn.emit('error', err); + }); + conn.db.on('reconnect', function() { + conn.readyState = STATES.connected; + conn.emit('reconnected'); + }); + conn.db.on('timeout', function(err) { + var error = new Error(err && err.err || 'connection timeout'); + conn.emit('error', error); + }); + conn.db.on('open', function(err, db) { + if (STATES.disconnected === conn.readyState && db && db.databaseName) { + conn.readyState = STATES.connected; + conn.emit('reconnected'); + } + }); + conn.db.on('parseError', function(err) { + conn.emit('parseError', err); + }); +} + +/** + * Opens a connection to a MongoDB ReplicaSet. + * + * See description of [doOpen](#NativeConnection-doOpen) for server options. In this case `options.replset` is also passed to ReplSetServers. + * + * @param {Function} fn + * @api private + * @return {Connection} this + */ + +NativeConnection.prototype.doOpenSet = function(fn) { + var servers = [], + _this = this; + + this.hosts.forEach(function(server) { + var host = server.host || server.ipc; + var port = server.port || 27017; + servers.push(new Server(host, port, _this.options.server)); + }); + + var server = this.options.mongos + ? new Mongos(servers, this.options.mongos) + : new ReplSetServers(servers, this.options.replset || this.options.replSet); + this.db = new Db(this.name, server, this.options.db); + + this.db.on('fullsetup', function() { + _this.emit('fullsetup'); + }); + + this.db.open(function(err) { + if (err) return fn(err); + fn(); + listen(_this); + }); + + return this; +}; + +/** + * Closes the connection + * + * @param {Function} fn + * @return {Connection} this + * @api private + */ + +NativeConnection.prototype.doClose = function(fn) { + this.db.close(fn); + return this; +}; + +/** + * Prepares default connection options for the node-mongodb-native driver. + * + * _NOTE: `passed` options take precedence over connection string options._ + * + * @param {Object} passed options that were passed directly during connection + * @param {Object} [connStrOptions] options that were passed in the connection string + * @api private + */ + +NativeConnection.prototype.parseOptions = function(passed, connStrOpts) { + var o = passed || {}; + o.db || (o.db = {}); + o.auth || (o.auth = {}); + o.server || (o.server = {}); + o.replset || (o.replset = o.replSet) || (o.replset = {}); + o.server.socketOptions || (o.server.socketOptions = {}); + o.replset.socketOptions || (o.replset.socketOptions = {}); + + var opts = connStrOpts || {}; + Object.keys(opts).forEach(function(name) { + switch (name) { + case 'ssl': + case 'poolSize': + if (typeof o.server[name] === 'undefined') { + o.server[name] = o.replset[name] = opts[name]; + } + break; + case 'slaveOk': + if (typeof o.server.slave_ok === 'undefined') { + o.server.slave_ok = opts[name]; + } + break; + case 'autoReconnect': + if (typeof o.server.auto_reconnect === 'undefined') { + o.server.auto_reconnect = opts[name]; + } + break; + case 'socketTimeoutMS': + case 'connectTimeoutMS': + if (typeof o.server.socketOptions[name] === 'undefined') { + o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name]; + } + break; + case 'authdb': + if (typeof o.auth.authdb === 'undefined') { + o.auth.authdb = opts[name]; + } + break; + case 'authSource': + if (typeof o.auth.authSource === 'undefined') { + o.auth.authSource = opts[name]; + } + break; + case 'retries': + case 'reconnectWait': + case 'rs_name': + if (typeof o.replset[name] === 'undefined') { + o.replset[name] = opts[name]; + } + break; + case 'replicaSet': + if (typeof o.replset.rs_name === 'undefined') { + o.replset.rs_name = opts[name]; + } + break; + case 'readSecondary': + if (typeof o.replset.read_secondary === 'undefined') { + o.replset.read_secondary = opts[name]; + } + break; + case 'nativeParser': + if (typeof o.db.native_parser === 'undefined') { + o.db.native_parser = opts[name]; + } + break; + case 'w': + case 'safe': + case 'fsync': + case 'journal': + case 'wtimeoutMS': + if (typeof o.db[name] === 'undefined') { + o.db[name] = opts[name]; + } + break; + case 'readPreference': + if (typeof o.db.readPreference === 'undefined') { + o.db.readPreference = opts[name]; + } + break; + case 'readPreferenceTags': + if (typeof o.db.read_preference_tags === 'undefined') { + o.db.read_preference_tags = opts[name]; + } + break; + } + }); + + if (!('auto_reconnect' in o.server)) { + o.server.auto_reconnect = true; + } + + // mongoose creates its own ObjectIds + o.db.forceServerObjectId = false; + + // default safe using new nomenclature + if (!('journal' in o.db || 'j' in o.db || + 'fsync' in o.db || 'safe' in o.db || 'w' in o.db)) { + o.db.w = 1; + } + + validate(o); + return o; +}; + +/*! + * Validates the driver db options. + * + * @param {Object} o + */ + +function validate(o) { + if (o.db.w === -1 || o.db.w === 0) { + if (o.db.journal || o.db.fsync || o.db.safe) { + throw new Error( + 'Invalid writeConcern: ' + + 'w set to -1 or 0 cannot be combined with safe|fsync|journal'); + } + } +} + +/*! + * Module exports. + */ + +module.exports = NativeConnection; diff --git a/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js new file mode 100644 index 0000000..fa5dbb4 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js @@ -0,0 +1,7 @@ +/*! + * Module exports. + */ + +exports.Binary = require('./binary'); +exports.ObjectId = require('./objectid'); +exports.ReadPreference = require('./ReadPreference'); diff --git a/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js new file mode 100644 index 0000000..69fc08f --- /dev/null +++ b/5-3/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js @@ -0,0 +1,14 @@ + +/*! + * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId + * @constructor NodeMongoDbObjectId + * @see ObjectId + */ + +var ObjectId = require('mongodb').ObjectId; + +/*! + * ignore + */ + +module.exports = exports = ObjectId; diff --git a/5-3/node_modules/mongoose/lib/error.js b/5-3/node_modules/mongoose/lib/error.js new file mode 100644 index 0000000..b084e76 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error.js @@ -0,0 +1,55 @@ + +/** + * MongooseError constructor + * + * @param {String} msg Error message + * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error + */ + +function MongooseError(msg) { + Error.call(this); + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.message = msg; + this.name = 'MongooseError'; +} + +/*! + * Inherits from Error. + */ + +MongooseError.prototype = Object.create(Error.prototype); +MongooseError.prototype.constructor = Error; + +/*! + * Module exports. + */ + +module.exports = exports = MongooseError; + +/** + * The default built-in validator error messages. + * + * @see Error.messages #error_messages_MongooseError-messages + * @api public + */ + +MongooseError.messages = require('./error/messages'); + +// backward compat +MongooseError.Messages = MongooseError.messages; + +/*! + * Expose subclasses + */ + +MongooseError.CastError = require('./error/cast'); +MongooseError.ValidationError = require('./error/validation'); +MongooseError.ValidatorError = require('./error/validator'); +MongooseError.VersionError = require('./error/version'); +MongooseError.OverwriteModelError = require('./error/overwriteModel'); +MongooseError.MissingSchemaError = require('./error/missingSchema'); +MongooseError.DivergentArrayError = require('./error/divergentArray'); diff --git a/5-3/node_modules/mongoose/lib/error/browserMissingSchema.js b/5-3/node_modules/mongoose/lib/error/browserMissingSchema.js new file mode 100644 index 0000000..1c7892e --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/browserMissingSchema.js @@ -0,0 +1,32 @@ +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/*! + * MissingSchema Error constructor. + * + * @inherits MongooseError + */ + +function MissingSchemaError() { + var msg = 'Schema hasn\'t been registered for document.\n' + + 'Use mongoose.Document(name, schema)'; + MongooseError.call(this, msg); + Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee); + this.name = 'MissingSchemaError'; +} + +/*! + * Inherits from MongooseError. + */ + +MissingSchemaError.prototype = Object.create(MongooseError.prototype); +MissingSchemaError.prototype.constructor = MongooseError; + +/*! + * exports + */ + +module.exports = MissingSchemaError; diff --git a/5-3/node_modules/mongoose/lib/error/cast.js b/5-3/node_modules/mongoose/lib/error/cast.js new file mode 100644 index 0000000..fcace73 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/cast.js @@ -0,0 +1,42 @@ +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/** + * Casting Error constructor. + * + * @param {String} type + * @param {String} value + * @inherits MongooseError + * @api private + */ + +function CastError(type, value, path, reason) { + MongooseError.call(this, 'Cast to ' + type + ' failed for value "' + value + '" at path "' + path + '"'); + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.name = 'CastError'; + this.kind = type; + this.value = value; + this.path = path; + this.reason = reason; +} + +/*! + * Inherits from MongooseError. + */ + +CastError.prototype = Object.create(MongooseError.prototype); +CastError.prototype.constructor = MongooseError; + + +/*! + * exports + */ + +module.exports = CastError; diff --git a/5-3/node_modules/mongoose/lib/error/divergentArray.js b/5-3/node_modules/mongoose/lib/error/divergentArray.js new file mode 100644 index 0000000..1cbaa25 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/divergentArray.js @@ -0,0 +1,42 @@ + +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/*! + * DivergentArrayError constructor. + * + * @inherits MongooseError + */ + +function DivergentArrayError(paths) { + var msg = 'For your own good, using `document.save()` to update an array ' + + 'which was selected using an $elemMatch projection OR ' + + 'populated using skip, limit, query conditions, or exclusion of ' + + 'the _id field when the operation results in a $pop or $set of ' + + 'the entire array is not supported. The following ' + + 'path(s) would have been modified unsafely:\n' + + ' ' + paths.join('\n ') + '\n' + + 'Use Model.update() to update these arrays instead.'; + // TODO write up a docs page (FAQ) and link to it + + MongooseError.call(this, msg); + Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee); + this.name = 'DivergentArrayError'; +} + +/*! + * Inherits from MongooseError. + */ + +DivergentArrayError.prototype = Object.create(MongooseError.prototype); +DivergentArrayError.prototype.constructor = MongooseError; + + +/*! + * exports + */ + +module.exports = DivergentArrayError; diff --git a/5-3/node_modules/mongoose/lib/error/messages.js b/5-3/node_modules/mongoose/lib/error/messages.js new file mode 100644 index 0000000..f825a4f --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/messages.js @@ -0,0 +1,42 @@ + +/** + * The default built-in validator error messages. These may be customized. + * + * // customize within each schema or globally like so + * var mongoose = require('mongoose'); + * mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; + * + * As you might have noticed, error messages support basic templating + * + * - `{PATH}` is replaced with the invalid document path + * - `{VALUE}` is replaced with the invalid value + * - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined" + * - `{MIN}` is replaced with the declared min value for the Number.min validator + * - `{MAX}` is replaced with the declared max value for the Number.max validator + * + * Click the "show code" link below to see all defaults. + * + * @property messages + * @receiver MongooseError + * @api public + */ + +var msg = module.exports = exports = {}; + +msg.general = {}; +msg.general.default = 'Validator failed for path `{PATH}` with value `{VALUE}`'; +msg.general.required = 'Path `{PATH}` is required.'; + +msg.Number = {}; +msg.Number.min = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).'; +msg.Number.max = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).'; + +msg.Date = {}; +msg.Date.min = 'Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).'; +msg.Date.max = 'Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).'; + +msg.String = {}; +msg.String.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; +msg.String.match = 'Path `{PATH}` is invalid ({VALUE}).'; +msg.String.minlength = 'Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'; +msg.String.maxlength = 'Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).'; diff --git a/5-3/node_modules/mongoose/lib/error/missingSchema.js b/5-3/node_modules/mongoose/lib/error/missingSchema.js new file mode 100644 index 0000000..25eabfa --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/missingSchema.js @@ -0,0 +1,33 @@ + +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/*! + * MissingSchema Error constructor. + * + * @inherits MongooseError + */ + +function MissingSchemaError(name) { + var msg = 'Schema hasn\'t been registered for model "' + name + '".\n' + + 'Use mongoose.model(name, schema)'; + MongooseError.call(this, msg); + Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee); + this.name = 'MissingSchemaError'; +} + +/*! + * Inherits from MongooseError. + */ + +MissingSchemaError.prototype = Object.create(MongooseError.prototype); +MissingSchemaError.prototype.constructor = MongooseError; + +/*! + * exports + */ + +module.exports = MissingSchemaError; diff --git a/5-3/node_modules/mongoose/lib/error/objectExpected.js b/5-3/node_modules/mongoose/lib/error/objectExpected.js new file mode 100644 index 0000000..fa863bc --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/objectExpected.js @@ -0,0 +1,35 @@ +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/** + * Strict mode error constructor + * + * @param {String} type + * @param {String} value + * @inherits MongooseError + * @api private + */ + +function ObjectExpectedError(path, val) { + MongooseError.call(this, 'Tried to set nested object field `' + path + + '` to primitive value `' + val + '` and strict mode is set to throw.'); + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.name = 'ObjectExpectedError'; + this.path = path; +} + +/*! + * Inherits from MongooseError. + */ + +ObjectExpectedError.prototype = Object.create(MongooseError.prototype); +ObjectExpectedError.prototype.constructor = MongooseError; + +module.exports = ObjectExpectedError; diff --git a/5-3/node_modules/mongoose/lib/error/overwriteModel.js b/5-3/node_modules/mongoose/lib/error/overwriteModel.js new file mode 100644 index 0000000..c14ae7f --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/overwriteModel.js @@ -0,0 +1,31 @@ + +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/*! + * OverwriteModel Error constructor. + * + * @inherits MongooseError + */ + +function OverwriteModelError(name) { + MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.'); + Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee); + this.name = 'OverwriteModelError'; +} + +/*! + * Inherits from MongooseError. + */ + +OverwriteModelError.prototype = Object.create(MongooseError.prototype); +OverwriteModelError.prototype.constructor = MongooseError; + +/*! + * exports + */ + +module.exports = OverwriteModelError; diff --git a/5-3/node_modules/mongoose/lib/error/strict.js b/5-3/node_modules/mongoose/lib/error/strict.js new file mode 100644 index 0000000..6e34431 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/strict.js @@ -0,0 +1,35 @@ +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/** + * Strict mode error constructor + * + * @param {String} type + * @param {String} value + * @inherits MongooseError + * @api private + */ + +function StrictModeError(path) { + MongooseError.call(this, 'Field `' + path + '` is not in schema and strict ' + + 'mode is set to throw.'); + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.name = 'StrictModeError'; + this.path = path; +} + +/*! + * Inherits from MongooseError. + */ + +StrictModeError.prototype = Object.create(MongooseError.prototype); +StrictModeError.prototype.constructor = MongooseError; + +module.exports = StrictModeError; diff --git a/5-3/node_modules/mongoose/lib/error/validation.js b/5-3/node_modules/mongoose/lib/error/validation.js new file mode 100644 index 0000000..bcbad61 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/validation.js @@ -0,0 +1,63 @@ +/*! + * Module requirements + */ + +var MongooseError = require('../error.js'); + +/** + * Document Validation Error + * + * @api private + * @param {Document} instance + * @inherits MongooseError + */ + +function ValidationError(instance) { + if (instance && instance.constructor.name === 'model') { + MongooseError.call(this, instance.constructor.modelName + ' validation failed'); + } else { + MongooseError.call(this, 'Validation failed'); + } + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.name = 'ValidationError'; + this.errors = {}; + if (instance) { + instance.errors = this.errors; + } +} + +/*! + * Inherits from MongooseError. + */ + +ValidationError.prototype = Object.create(MongooseError.prototype); +ValidationError.prototype.constructor = MongooseError; + + +/** + * Console.log helper + */ + +ValidationError.prototype.toString = function() { + var ret = this.name + ': '; + var msgs = []; + + Object.keys(this.errors).forEach(function(key) { + if (this === this.errors[key]) { + return; + } + msgs.push(String(this.errors[key])); + }, this); + + return ret + msgs.join(', '); +}; + +/*! + * Module exports + */ + +module.exports = exports = ValidationError; diff --git a/5-3/node_modules/mongoose/lib/error/validator.js b/5-3/node_modules/mongoose/lib/error/validator.js new file mode 100644 index 0000000..959073b --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/validator.js @@ -0,0 +1,71 @@ +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); +var errorMessages = MongooseError.messages; + +/** + * Schema validator error + * + * @param {Object} properties + * @inherits MongooseError + * @api private + */ + +function ValidatorError(properties) { + var msg = properties.message; + if (!msg) { + msg = errorMessages.general.default; + } + + this.properties = properties; + var message = this.formatMessage(msg, properties); + MongooseError.call(this, message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this); + } else { + this.stack = new Error().stack; + } + this.name = 'ValidatorError'; + this.kind = properties.type; + this.path = properties.path; + this.value = properties.value; +} + +/*! + * Inherits from MongooseError + */ + +ValidatorError.prototype = Object.create(MongooseError.prototype); +ValidatorError.prototype.constructor = MongooseError; + +/*! + * Formats error messages + */ + +ValidatorError.prototype.formatMessage = function(msg, properties) { + var propertyNames = Object.keys(properties); + for (var i = 0; i < propertyNames.length; ++i) { + var propertyName = propertyNames[i]; + if (propertyName === 'message') { + continue; + } + msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); + } + return msg; +}; + +/*! + * toString helper + */ + +ValidatorError.prototype.toString = function() { + return this.message; +}; + +/*! + * exports + */ + +module.exports = ValidatorError; diff --git a/5-3/node_modules/mongoose/lib/error/version.js b/5-3/node_modules/mongoose/lib/error/version.js new file mode 100644 index 0000000..815b1bc --- /dev/null +++ b/5-3/node_modules/mongoose/lib/error/version.js @@ -0,0 +1,32 @@ + +/*! + * Module dependencies. + */ + +var MongooseError = require('../error.js'); + +/** + * Version Error constructor. + * + * @inherits MongooseError + * @api private + */ + +function VersionError() { + MongooseError.call(this, 'No matching document found.'); + Error.captureStackTrace && Error.captureStackTrace(this, arguments.callee); + this.name = 'VersionError'; +} + +/*! + * Inherits from MongooseError. + */ + +VersionError.prototype = Object.create(MongooseError.prototype); +VersionError.prototype.constructor = MongooseError; + +/*! + * exports + */ + +module.exports = VersionError; diff --git a/5-3/node_modules/mongoose/lib/index.js b/5-3/node_modules/mongoose/lib/index.js new file mode 100644 index 0000000..6c85703 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/index.js @@ -0,0 +1,771 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +var Schema = require('./schema'), + SchemaType = require('./schematype'), + VirtualType = require('./virtualtype'), + STATES = require('./connectionstate'), + Types = require('./types'), + Query = require('./query'), + Model = require('./model'), + Document = require('./document'), + utils = require('./utils'), + format = utils.toCollectionName, + pkg = require('../package.json'); + +var querystring = require('querystring'); + +var Aggregate = require('./aggregate'); +var PromiseProvider = require('./promise_provider'); + +/** + * Mongoose constructor. + * + * The exports object of the `mongoose` module is an instance of this class. + * Most apps will only use this one instance. + * + * @api public + */ + +function Mongoose() { + this.connections = []; + this.plugins = []; + this.models = {}; + this.modelSchemas = {}; + // default global options + this.options = { + pluralization: true + }; + var conn = this.createConnection(); // default connection + conn.models = this.models; +} + +/** + * Wraps the given Mongoose instance into a thenable (pseudo-promise). This + * is so `connect()` and `disconnect()` can return a thenable while maintaining + * backwards compatibility. + * + * @api private + */ + +function MongooseThenable(mongoose, promise) { + for (var key in mongoose) { + if (typeof mongoose[key] === 'function') { + this[key] = function() { + return mongoose[key].apply(mongoose, arguments); + }; + } else { + this[key] = mongoose[key]; + } + } + this.$opPromise = promise; +} + +/** + * Ability to use mongoose object as a pseudo-promise so `.connect().then()` + * and `.disconnect().then()` are viable. + * + * @param {Function} onFulfilled + * @param {Function} onRejected + * @return {Promise} + * @api private + */ + +MongooseThenable.prototype.then = function(onFulfilled, onRejected) { + var Promise = PromiseProvider.get(); + if (!this.$opPromise) { + return new Promise.ES6(function(resolve, reject) { + reject(new Error('Can only call `.then()` if connect() or disconnect() ' + + 'has been called')); + }).then(onFulfilled, onRejected); + } + return this.$opPromise.then(onFulfilled, onRejected); +}; + +/** + * Ability to use mongoose object as a pseudo-promise so `.connect().then()` + * and `.disconnect().then()` are viable. + * + * @param {Function} onFulfilled + * @param {Function} onRejected + * @return {Promise} + * @api private + */ + +MongooseThenable.prototype.catch = function(onRejected) { + return this.then(null, onRejected); +}; + +/** + * Expose connection states for user-land + * + */ +Mongoose.prototype.STATES = STATES; + +/** + * Sets mongoose options + * + * ####Example: + * + * mongoose.set('test', value) // sets the 'test' option to `value` + * + * mongoose.set('debug', true) // enable logging collection methods + arguments to the console + * + * mongoose.set('debug', function(collectionName, methodName, arg1, arg2...) {}); // use custom function to log collection methods + arguments + * + * @param {String} key + * @param {String|Function} value + * @api public + */ + +Mongoose.prototype.set = function(key, value) { + if (arguments.length === 1) { + return this.options[key]; + } + + this.options[key] = value; + return this; +}; + +/** + * Gets mongoose options + * + * ####Example: + * + * mongoose.get('test') // returns the 'test' value + * + * @param {String} key + * @method get + * @api public + */ + +Mongoose.prototype.get = Mongoose.prototype.set; + +/*! + * ReplSet connection string check. + */ + +var rgxReplSet = /^.+,.+$/; + +/** + * Checks if ?replicaSet query parameter is specified in URI + * + * ####Example: + * + * checkReplicaSetInUri('localhost:27000?replicaSet=rs0'); // true + * + * @param {String} uri + * @return {boolean} + * @api private + */ + +var checkReplicaSetInUri = function(uri) { + if (!uri) { + return false; + } + + var queryStringStart = uri.indexOf('?'); + var isReplicaSet = false; + if (queryStringStart !== -1) { + try { + var obj = querystring.parse(uri.substr(queryStringStart + 1)); + if (obj && obj.replicaSet) { + isReplicaSet = true; + } + } catch (e) { + return false; + } + } + + return isReplicaSet; +}; + +/** + * Creates a Connection instance. + * + * Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections. + * + * If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately. This means we can pass `db`, `server`, and `replset` options to the driver. _Note that the `safe` option specified in your schema will overwrite the `safe` db option specified here unless you set your schemas `safe` option to `undefined`. See [this](/docs/guide.html#safe) for more information._ + * + * _Options passed take precedence over options included in connection strings._ + * + * ####Example: + * + * // with mongodb:// URI + * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); + * + * // and options + * var opts = { db: { native_parser: true }} + * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts); + * + * // replica sets + * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database'); + * + * // and options + * var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }} + * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts); + * + * // with [host, database_name[, port] signature + * db = mongoose.createConnection('localhost', 'database', port) + * + * // and options + * var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' } + * db = mongoose.createConnection('localhost', 'database', port, opts) + * + * // initialize now, connect later + * db = mongoose.createConnection(); + * db.open('localhost', 'database', port, [opts]); + * + * @param {String} [uri] a mongodb:// URI + * @param {Object} [options] options to pass to the driver + * @param {Object} [options.config] mongoose-specific options + * @param {Boolean} [options.config.autoIndex] set to false to disable automatic index creation for all models associated with this connection. + * @see Connection#open #connection_Connection-open + * @see Connection#openSet #connection_Connection-openSet + * @return {Connection} the created Connection object + * @api public + */ + +Mongoose.prototype.createConnection = function(uri, options) { + var conn = new Connection(this); + this.connections.push(conn); + + if (arguments.length) { + if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) { + conn.openSet.apply(conn, arguments); + } else if (options && options.replset && + (options.replset.replicaSet || options.replset.rs_name)) { + conn.openSet.apply(conn, arguments); + } else { + conn.open.apply(conn, arguments); + } + } + + return conn; +}; + +/** + * Opens the default mongoose connection. + * + * If arguments are passed, they are proxied to either + * [Connection#open](#connection_Connection-open) or + * [Connection#openSet](#connection_Connection-openSet) appropriately. + * + * _Options passed take precedence over options included in connection strings._ + * + * ####Example: + * + * mongoose.connect('mongodb://user:pass@localhost:port/database'); + * + * // replica sets + * var uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase'; + * mongoose.connect(uri); + * + * // with options + * mongoose.connect(uri, options); + * + * // connecting to multiple mongos + * var uri = 'mongodb://hostA:27501,hostB:27501'; + * var opts = { mongos: true }; + * mongoose.connect(uri, opts); + * + * // optional callback that gets fired when initial connection completed + * var uri = 'mongodb://nonexistent.domain:27000'; + * mongoose.connect(uri, function(error) { + * // if error is truthy, the initial connection failed. + * }) + * + * @param {String} uri(s) + * @param {Object} [options] + * @param {Function} [callback] + * @see Mongoose#createConnection #index_Mongoose-createConnection + * @api public + * @return {MongooseThenable} pseudo-promise wrapper around this + */ + +Mongoose.prototype.connect = function() { + var conn = this.connection; + if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) { + return new MongooseThenable(this, conn.openSet.apply(conn, arguments)); + } + + return new MongooseThenable(this, conn.open.apply(conn, arguments)); +}; + +/** + * Disconnects all connections. + * + * @param {Function} [fn] called after all connection close. + * @return {MongooseThenable} pseudo-promise wrapper around this + * @api public + */ + +Mongoose.prototype.disconnect = function(fn) { + var error; + this.connections.forEach(function(conn) { + conn.close(function(err) { + if (error) { + return; + } + if (err) { + error = err; + } + }); + }); + + var Promise = PromiseProvider.get(); + return new MongooseThenable(this, new Promise.ES6(function(resolve, reject) { + fn && fn(error); + if (error) { + reject(error); + return; + } + resolve(); + })); +}; + +/** + * Defines a model or retrieves it. + * + * Models defined on the `mongoose` instance are available to all connection created by the same `mongoose` instance. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * + * // define an Actor model with this mongoose instance + * mongoose.model('Actor', new Schema({ name: String })); + * + * // create a new connection + * var conn = mongoose.createConnection(..); + * + * // retrieve the Actor model + * var Actor = conn.model('Actor'); + * + * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ + * + * ####Example: + * + * var schema = new Schema({ name: String }, { collection: 'actor' }); + * + * // or + * + * schema.set('collection', 'actor'); + * + * // or + * + * var collectionName = 'actor' + * var M = mongoose.model('Actor', schema, collectionName) + * + * @param {String} name model name + * @param {Schema} [schema] + * @param {String} [collection] name (optional, induced from model name) + * @param {Boolean} [skipInit] whether to skip initialization (defaults to false) + * @api public + */ + +Mongoose.prototype.model = function(name, schema, collection, skipInit) { + if (typeof schema === 'string') { + collection = schema; + schema = false; + } + + if (utils.isObject(schema) && !(schema.instanceOfSchema)) { + schema = new Schema(schema); + } + + if (typeof collection === 'boolean') { + skipInit = collection; + collection = null; + } + + // handle internal options from connection.model() + var options; + if (skipInit && utils.isObject(skipInit)) { + options = skipInit; + skipInit = true; + } else { + options = {}; + } + + // look up schema for the collection. + if (!this.modelSchemas[name]) { + if (schema) { + // cache it so we only apply plugins once + this.modelSchemas[name] = schema; + this._applyPlugins(schema); + } else { + throw new mongoose.Error.MissingSchemaError(name); + } + } + + var model; + var sub; + + // connection.model() may be passing a different schema for + // an existing model name. in this case don't read from cache. + if (this.models[name] && options.cache !== false) { + if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { + throw new mongoose.Error.OverwriteModelError(name); + } + + if (collection) { + // subclass current model with alternate collection + model = this.models[name]; + schema = model.prototype.schema; + sub = model.__subclass(this.connection, schema, collection); + // do not cache the sub model + return sub; + } + + return this.models[name]; + } + + // ensure a schema exists + if (!schema) { + schema = this.modelSchemas[name]; + if (!schema) { + throw new mongoose.Error.MissingSchemaError(name); + } + } + + // Apply relevant "global" options to the schema + if (!('pluralization' in schema.options)) schema.options.pluralization = this.options.pluralization; + + + if (!collection) { + collection = schema.get('collection') || format(name, schema.options); + } + + var connection = options.connection || this.connection; + model = Model.compile(name, schema, collection, connection, this); + + if (!skipInit) { + model.init(); + } + + if (options.cache === false) { + return model; + } + + this.models[name] = model; + return this.models[name]; +}; + +/** + * Returns an array of model names created on this instance of Mongoose. + * + * ####Note: + * + * _Does not include names of models created using `connection.model()`._ + * + * @api public + * @return {Array} + */ + +Mongoose.prototype.modelNames = function() { + var names = Object.keys(this.models); + return names; +}; + +/** + * Applies global plugins to `schema`. + * + * @param {Schema} schema + * @api private + */ + +Mongoose.prototype._applyPlugins = function(schema) { + for (var i = 0, l = this.plugins.length; i < l; i++) { + schema.plugin(this.plugins[i][0], this.plugins[i][1]); + } +}; + +/** + * Declares a global plugin executed on all Schemas. + * + * Equivalent to calling `.plugin(fn)` on each Schema you create. + * + * @param {Function} fn plugin callback + * @param {Object} [opts] optional options + * @return {Mongoose} this + * @see plugins ./plugins.html + * @api public + */ + +Mongoose.prototype.plugin = function(fn, opts) { + this.plugins.push([fn, opts]); + return this; +}; + +/** + * The default connection of the mongoose module. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * mongoose.connect(...); + * mongoose.connection.on('error', cb); + * + * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model). + * + * @property connection + * @return {Connection} + * @api public + */ + +Mongoose.prototype.__defineGetter__('connection', function() { + return this.connections[0]; +}); + +/*! + * Driver depentend APIs + */ + +var driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native'; + +/*! + * Connection + */ + +var Connection = require(driver + '/connection'); + +/*! + * Collection + */ + +var Collection = require(driver + '/collection'); + +/** + * The Mongoose Aggregate constructor + * + * @method Aggregate + * @api public + */ + +Mongoose.prototype.Aggregate = Aggregate; + +/** + * The Mongoose Collection constructor + * + * @method Collection + * @api public + */ + +Mongoose.prototype.Collection = Collection; + +/** + * The Mongoose [Connection](#connection_Connection) constructor + * + * @method Connection + * @api public + */ + +Mongoose.prototype.Connection = Connection; + +/** + * The Mongoose version + * + * @property version + * @api public + */ + +Mongoose.prototype.version = pkg.version; + +/** + * The Mongoose constructor + * + * The exports of the mongoose module is an instance of this class. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var mongoose2 = new mongoose.Mongoose(); + * + * @method Mongoose + * @api public + */ + +Mongoose.prototype.Mongoose = Mongoose; + +/** + * The Mongoose [Schema](#schema_Schema) constructor + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var Schema = mongoose.Schema; + * var CatSchema = new Schema(..); + * + * @method Schema + * @api public + */ + +Mongoose.prototype.Schema = Schema; + +/** + * The Mongoose [SchemaType](#schematype_SchemaType) constructor + * + * @method SchemaType + * @api public + */ + +Mongoose.prototype.SchemaType = SchemaType; + +/** + * The various Mongoose SchemaTypes. + * + * ####Note: + * + * _Alias of mongoose.Schema.Types for backwards compatibility._ + * + * @property SchemaTypes + * @see Schema.SchemaTypes #schema_Schema.Types + * @api public + */ + +Mongoose.prototype.SchemaTypes = Schema.Types; + +/** + * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor + * + * @method VirtualType + * @api public + */ + +Mongoose.prototype.VirtualType = VirtualType; + +/** + * The various Mongoose Types. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var array = mongoose.Types.Array; + * + * ####Types: + * + * - [ObjectId](#types-objectid-js) + * - [Buffer](#types-buffer-js) + * - [SubDocument](#types-embedded-js) + * - [Array](#types-array-js) + * - [DocumentArray](#types-documentarray-js) + * + * Using this exposed access to the `ObjectId` type, we can construct ids on demand. + * + * var ObjectId = mongoose.Types.ObjectId; + * var id1 = new ObjectId; + * + * @property Types + * @api public + */ + +Mongoose.prototype.Types = Types; + +/** + * The Mongoose [Query](#query_Query) constructor. + * + * @method Query + * @api public + */ + +Mongoose.prototype.Query = Query; + +/** + * The Mongoose [Promise](#promise_Promise) constructor. + * + * @method Promise + * @api public + */ + +Object.defineProperty(Mongoose.prototype, 'Promise', { + get: function() { + return PromiseProvider.get(); + }, + set: function(lib) { + PromiseProvider.set(lib); + } +}); + +/** + * Storage layer for mongoose promises + * + * @method PromiseProvider + * @api public + */ + +Mongoose.prototype.PromiseProvider = PromiseProvider; + +/** + * The Mongoose [Model](#model_Model) constructor. + * + * @method Model + * @api public + */ + +Mongoose.prototype.Model = Model; + +/** + * The Mongoose [Document](#document-js) constructor. + * + * @method Document + * @api public + */ + +Mongoose.prototype.Document = Document; + +/** + * The Mongoose DocumentProvider constructor. + * + * @method DocumentProvider + * @api public + */ + +Mongoose.prototype.DocumentProvider = require('./document_provider'); + +/** + * The [MongooseError](#error_MongooseError) constructor. + * + * @method Error + * @api public + */ + +Mongoose.prototype.Error = require('./error'); + +/** + * The Mongoose CastError constructor + * + * @method Error + * @api public + */ + +Mongoose.prototype.CastError = require('./error/cast'); + +/** + * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses. + * + * @property mongo + * @api public + */ + +Mongoose.prototype.mongo = require('mongodb'); + +/** + * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses. + * + * @property mquery + * @api public + */ + +Mongoose.prototype.mquery = require('mquery'); + +/*! + * The exports object is an instance of Mongoose. + * + * @api public + */ + +var mongoose = module.exports = exports = new Mongoose; diff --git a/5-3/node_modules/mongoose/lib/internal.js b/5-3/node_modules/mongoose/lib/internal.js new file mode 100644 index 0000000..edf3338 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/internal.js @@ -0,0 +1,31 @@ +/*! + * Dependencies + */ + +var StateMachine = require('./statemachine'); +var ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore'); + +module.exports = exports = InternalCache; + +function InternalCache() { + this.strictMode = undefined; + this.selected = undefined; + this.shardval = undefined; + this.saveError = undefined; + this.validationError = undefined; + this.adhocPaths = undefined; + this.removing = undefined; + this.inserting = undefined; + this.version = undefined; + this.getters = {}; + this._id = undefined; + this.populate = undefined; // what we want to populate in this doc + this.populated = undefined;// the _ids that have been populated + this.wasPopulated = false; // if this doc was the result of a population + this.scope = undefined; + this.activePaths = new ActiveRoster; + + // embedded docs + this.ownerDocument = undefined; + this.fullPath = undefined; +} diff --git a/5-3/node_modules/mongoose/lib/model.js b/5-3/node_modules/mongoose/lib/model.js new file mode 100644 index 0000000..185f83a --- /dev/null +++ b/5-3/node_modules/mongoose/lib/model.js @@ -0,0 +1,3183 @@ +/*! + * Module dependencies. + */ + +var Document = require('./document'); +var MongooseError = require('./error'); +var VersionError = MongooseError.VersionError; +var DivergentArrayError = MongooseError.DivergentArrayError; +var Query = require('./query'); +var Aggregate = require('./aggregate'); +var Schema = require('./schema'); +var utils = require('./utils'); +var hasOwnProperty = utils.object.hasOwnProperty; +var isMongooseObject = utils.isMongooseObject; +var EventEmitter = require('events').EventEmitter; +var Promise = require('./promise'); +var util = require('util'); +var tick = utils.tick; + +var async = require('async'); +var PromiseProvider = require('./promise_provider'); + +var VERSION_WHERE = 1, + VERSION_INC = 2, + VERSION_ALL = VERSION_WHERE | VERSION_INC; + +/** + * Model constructor + * + * Provides the interface to MongoDB collections as well as creates document instances. + * + * @param {Object} doc values with which to create the document + * @inherits Document + * @event `error`: If listening to this event, it is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. + * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. + * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event. + * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed. + * @api public + */ + +function Model(doc, fields, skipId) { + Document.call(this, doc, fields, skipId); +} + +/*! + * Inherits from Document. + * + * All Model.prototype features are available on + * top level (non-sub) documents. + */ + +Model.prototype.__proto__ = Document.prototype; + +/** + * Connection the model uses. + * + * @api public + * @property db + */ + +Model.prototype.db; + +/** + * Collection the model uses. + * + * @api public + * @property collection + */ + +Model.prototype.collection; + +/** + * The name of the model + * + * @api public + * @property modelName + */ + +Model.prototype.modelName; + +/** + * If this is a discriminator model, `baseModelName` is the name of + * the base model. + * + * @api public + * @property baseModelName + */ + +Model.prototype.baseModelName; + +Model.prototype.$__handleSave = function(options, callback) { + var _this = this; + if (!options.safe && this.schema.options.safe) { + options.safe = this.schema.options.safe; + } + if (typeof options.safe === 'boolean') { + options.safe = null; + } + + if (this.isNew) { + // send entire doc + var toObjectOptions = {}; + if (this.schema.options.toObject && + this.schema.options.toObject.retainKeyOrder) { + toObjectOptions.retainKeyOrder = true; + } + + toObjectOptions.depopulate = 1; + toObjectOptions._skipDepopulateTopLevel = true; + toObjectOptions.transform = false; + + var obj = this.toObject(toObjectOptions); + + if (!utils.object.hasOwnProperty(obj || {}, '_id')) { + // documents must have an _id else mongoose won't know + // what to update later if more changes are made. the user + // wouldn't know what _id was generated by mongodb either + // nor would the ObjectId generated my mongodb necessarily + // match the schema definition. + setTimeout(function() { + callback(new Error('document must have an _id before saving')); + }, 0); + return; + } + + this.$__version(true, obj); + this.collection.insert(obj, options.safe, function(err, ret) { + if (err) { + _this.isNew = true; + _this.emit('isNew', true); + + callback(err); + return; + } + + callback(null, ret); + }); + this.$__reset(); + this.isNew = false; + this.emit('isNew', false); + // Make it possible to retry the insert + this.$__.inserting = true; + } else { + // Make sure we don't treat it as a new object on error, + // since it already exists + this.$__.inserting = false; + + var delta = this.$__delta(); + + if (delta) { + if (delta instanceof Error) { + callback(delta); + return; + } + var where = this.$__where(delta[0]); + + if (where instanceof Error) { + callback(where); + return; + } + + this.collection.update(where, delta[1], options.safe, function(err, ret) { + if (err) { + callback(err); + return; + } + callback(null, ret); + }); + } else { + this.$__reset(); + callback(); + return; + } + + this.emit('isNew', false); + } +}; + +/*! + * ignore + */ + +Model.prototype.$__save = function(options, callback) { + var _this = this; + + _this.$__handleSave(options, function(error, result) { + if (error) { + return callback(error); + } + + _this.$__reset(); + _this.$__storeShard(); + + var numAffected = 0; + if (result) { + if (Array.isArray(result)) { + numAffected = result.length; + } else if (result.result && result.result.n !== undefined) { + numAffected = result.result.n; + } else if (result.result && result.result.nModified !== undefined) { + numAffected = result.result.nModified; + } else { + numAffected = result; + } + } + + // was this an update that required a version bump? + if (_this.$__.version && !_this.$__.inserting) { + var doIncrement = VERSION_INC === (VERSION_INC & _this.$__.version); + _this.$__.version = undefined; + + if (numAffected <= 0) { + // the update failed. pass an error back + var err = new VersionError(); + return callback(err); + } + + // increment version if was successful + if (doIncrement) { + var key = _this.schema.options.versionKey; + var version = _this.getValue(key) | 0; + _this.setValue(key, version + 1); + } + } + + _this.emit('save', _this, numAffected); + callback(null, _this, numAffected); + }); +}; + +/** + * Saves this document. + * + * ####Example: + * + * product.sold = Date.now(); + * product.save(function (err, product, numAffected) { + * if (err) .. + * }) + * + * The callback will receive three parameters + * + * 1. `err` if an error occurred + * 2. `product` which is the saved `product` + * 3. `numAffected` will be 1 when the document was successfully persisted to MongoDB, otherwise 0. Unless you tweak mongoose's internals, you don't need to worry about checking this parameter for errors - checking `err` is sufficient to make sure your document was properly saved. + * + * As an extra measure of flow control, save will return a Promise. + * ####Example: + * product.save().then(function(product) { + * ... + * }); + * + * For legacy reasons, mongoose stores object keys in reverse order on initial + * save. That is, `{ a: 1, b: 2 }` will be saved as `{ b: 2, a: 1 }` in + * MongoDB. To override this behavior, set + * [the `toObject.retainKeyOrder` option](http://mongoosejs.com/docs/api.html#document_Document-toObject) + * to true on your schema. + * + * @param {Object} [options] options optional options + * @param {Object} [options.safe] overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe) + * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. + * @param {Function} [fn] optional callback + * @return {Promise} Promise + * @api public + * @see middleware http://mongoosejs.com/docs/middleware.html + */ + +Model.prototype.save = function(options, fn) { + if (typeof options === 'function') { + fn = options; + options = undefined; + } + + if (!options) { + options = {}; + } + + if (options.__noPromise) { + return this.$__save(options, fn); + } + + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _this.$__save(options, function(error, doc, numAffected) { + if (error) { + fn && fn(error); + reject(error); + return; + } + + fn && fn(null, doc, numAffected); + resolve(doc, numAffected); + }); + }); +}; + +/** + * Determines whether versioning should be skipped for the given path + * + * @param {Document} self + * @param {String} path + * @return {Boolean} true if versioning should be skipped for the given path + */ +function shouldSkipVersioning(self, path) { + var skipVersioning = self.schema.options.skipVersioning; + if (!skipVersioning) return false; + + // Remove any array indexes from the path + path = path.replace(/\.\d+\./, '.'); + + return skipVersioning[path]; +} + +/*! + * Apply the operation to the delta (update) clause as + * well as track versioning for our where clause. + * + * @param {Document} self + * @param {Object} where + * @param {Object} delta + * @param {Object} data + * @param {Mixed} val + * @param {String} [operation] + */ + +function operand(self, where, delta, data, val, op) { + // delta + op || (op = '$set'); + if (!delta[op]) delta[op] = {}; + delta[op][data.path] = val; + + // disabled versioning? + if (self.schema.options.versionKey === false) return; + + // path excluded from versioning? + if (shouldSkipVersioning(self, data.path)) return; + + // already marked for versioning? + if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; + + switch (op) { + case '$set': + case '$unset': + case '$pop': + case '$pull': + case '$pullAll': + case '$push': + case '$pushAll': + case '$addToSet': + break; + default: + // nothing to do + return; + } + + // ensure updates sent with positional notation are + // editing the correct array element. + // only increment the version if an array position changes. + // modifying elements of an array is ok if position does not change. + + if (op === '$push' || op === '$pushAll' || op === '$addToSet') { + self.$__.version = VERSION_INC; + } else if (/^\$p/.test(op)) { + // potentially changing array positions + self.increment(); + } else if (Array.isArray(val)) { + // $set an array + self.increment(); + } else if (/\.\d+\.|\.\d+$/.test(data.path)) { + // now handling $set, $unset + // subpath of array + self.$__.version = VERSION_WHERE; + } +} + +/*! + * Compiles an update and where clause for a `val` with _atomics. + * + * @param {Document} self + * @param {Object} where + * @param {Object} delta + * @param {Object} data + * @param {Array} value + */ + +function handleAtomics(self, where, delta, data, value) { + if (delta.$set && delta.$set[data.path]) { + // $set has precedence over other atomics + return; + } + + if (typeof value.$__getAtomics === 'function') { + value.$__getAtomics().forEach(function(atomic) { + var op = atomic[0]; + var val = atomic[1]; + operand(self, where, delta, data, val, op); + }); + return; + } + + // legacy support for plugins + + var atomics = value._atomics, + ops = Object.keys(atomics), + i = ops.length, + val, + op; + + if (i === 0) { + // $set + + if (isMongooseObject(value)) { + value = value.toObject({depopulate: 1}); + } else if (value.valueOf) { + value = value.valueOf(); + } + + return operand(self, where, delta, data, value); + } + + function iter(mem) { + return isMongooseObject(mem) + ? mem.toObject({depopulate: 1}) + : mem; + } + + while (i--) { + op = ops[i]; + val = atomics[op]; + + if (isMongooseObject(val)) { + val = val.toObject({depopulate: 1}); + } else if (Array.isArray(val)) { + val = val.map(iter); + } else if (val.valueOf) { + val = val.valueOf(); + } + + if (op === '$addToSet') { + val = {$each: val}; + } + + operand(self, where, delta, data, val, op); + } +} + +/** + * Produces a special query document of the modified properties used in updates. + * + * @api private + * @method $__delta + * @memberOf Model + */ + +Model.prototype.$__delta = function() { + var dirty = this.$__dirty(); + if (!dirty.length && VERSION_ALL !== this.$__.version) return; + + var where = {}, + delta = {}, + len = dirty.length, + divergent = [], + d = 0; + + where._id = this._doc._id; + + for (; d < len; ++d) { + var data = dirty[d]; + var value = data.value; + + var match = checkDivergentArray(this, data.path, value); + if (match) { + divergent.push(match); + continue; + } + + if (divergent.length) continue; + + if (undefined === value) { + operand(this, where, delta, data, 1, '$unset'); + } else if (value === null) { + operand(this, where, delta, data, null); + } else if (value._path && value._atomics) { + // arrays and other custom types (support plugins etc) + handleAtomics(this, where, delta, data, value); + } else if (value._path && Buffer.isBuffer(value)) { + // MongooseBuffer + value = value.toObject(); + operand(this, where, delta, data, value); + } else { + value = utils.clone(value, {depopulate: 1}); + operand(this, where, delta, data, value); + } + } + + if (divergent.length) { + return new DivergentArrayError(divergent); + } + + if (this.$__.version) { + this.$__version(where, delta); + } + + return [where, delta]; +}; + +/*! + * Determine if array was populated with some form of filter and is now + * being updated in a manner which could overwrite data unintentionally. + * + * @see https://github.com/Automattic/mongoose/issues/1334 + * @param {Document} doc + * @param {String} path + * @return {String|undefined} + */ + +function checkDivergentArray(doc, path, array) { + // see if we populated this path + var pop = doc.populated(path, true); + + if (!pop && doc.$__.selected) { + // If any array was selected using an $elemMatch projection, we deny the update. + // NOTE: MongoDB only supports projected $elemMatch on top level array. + var top = path.split('.')[0]; + if ((doc.$__.selected[top] && doc.$__.selected[top].$elemMatch) || + doc.$__.selected[top + '.$']) { + return top; + } + } + + if (!(pop && array && array.isMongooseArray)) return; + + // If the array was populated using options that prevented all + // documents from being returned (match, skip, limit) or they + // deselected the _id field, $pop and $set of the array are + // not safe operations. If _id was deselected, we do not know + // how to remove elements. $pop will pop off the _id from the end + // of the array in the db which is not guaranteed to be the + // same as the last element we have here. $set of the entire array + // would be similarily destructive as we never received all + // elements of the array and potentially would overwrite data. + var check = pop.options.match || + pop.options.options && hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted + pop.options.options && pop.options.options.skip || // 0 is permitted + pop.options.select && // deselected _id? + (pop.options.select._id === 0 || + /\s?-_id\s?/.test(pop.options.select)); + + if (check) { + var atomics = array._atomics; + if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) { + return path; + } + } +} + +/** + * Appends versioning to the where and update clauses. + * + * @api private + * @method $__version + * @memberOf Model + */ + +Model.prototype.$__version = function(where, delta) { + var key = this.schema.options.versionKey; + + if (where === true) { + // this is an insert + if (key) this.setValue(key, delta[key] = 0); + return; + } + + // updates + + // only apply versioning if our versionKey was selected. else + // there is no way to select the correct version. we could fail + // fast here and force them to include the versionKey but + // thats a bit intrusive. can we do this automatically? + if (!this.isSelected(key)) { + return; + } + + // $push $addToSet don't need the where clause set + if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { + where[key] = this.getValue(key); + } + + if (VERSION_INC === (VERSION_INC & this.$__.version)) { + if (!delta.$set || typeof delta.$set[key] === 'undefined') { + delta.$inc || (delta.$inc = {}); + delta.$inc[key] = 1; + } + } +}; + +/** + * Signal that we desire an increment of this documents version. + * + * ####Example: + * + * Model.findById(id, function (err, doc) { + * doc.increment(); + * doc.save(function (err) { .. }) + * }) + * + * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey + * @api public + */ + +Model.prototype.increment = function increment() { + this.$__.version = VERSION_ALL; + return this; +}; + +/** + * Returns a query object which applies shardkeys if they exist. + * + * @api private + * @method $__where + * @memberOf Model + */ + +Model.prototype.$__where = function _where(where) { + where || (where = {}); + + var paths, + len; + + if (!where._id) { + where._id = this._doc._id; + } + + if (this.$__.shardval) { + paths = Object.keys(this.$__.shardval); + len = paths.length; + + for (var i = 0; i < len; ++i) { + where[paths[i]] = this.$__.shardval[paths[i]]; + } + } + + if (this._doc._id == null) { + return new Error('No _id found on document!'); + } + + return where; +}; + +/** + * Removes this document from the db. + * + * ####Example: + * product.remove(function (err, product) { + * if (err) return handleError(err); + * Product.findById(product._id, function (err, product) { + * console.log(product) // null + * }) + * }) + * + * + * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recive errors + * + * ####Example: + * product.remove().then(function (product) { + * ... + * }).onRejected(function (err) { + * assert.ok(err) + * }) + * + * @param {function(err,product)} [fn] optional callback + * @return {Promise} Promise + * @api public + */ + +Model.prototype.remove = function remove(options, fn) { + if (typeof options === 'function') { + fn = options; + options = undefined; + } + + if (!options) { + options = {}; + } + + if (this.$__.removing) { + if (fn) { + this.$__.removing.then( + function(res) { fn(null, res); }, + function(err) { fn(err); }); + } + return this; + } + + var _this = this; + var Promise = PromiseProvider.get(); + this.$__.removing = new Promise.ES6(function(resolve, reject) { + var where = _this.$__where(); + if (where instanceof Error) { + reject(where); + fn && fn(where); + return; + } + + if (!options.safe && _this.schema.options.safe) { + options.safe = _this.schema.options.safe; + } + + _this.collection.remove(where, options, function(err) { + if (!err) { + _this.emit('remove', _this); + resolve(_this); + fn && fn(null, _this); + return; + } + + reject(err); + fn && fn(err); + }); + }); + return this.$__.removing; +}; + +/** + * Returns another Model instance. + * + * ####Example: + * + * var doc = new Tank; + * doc.model('User').findById(id, callback); + * + * @param {String} name model name + * @api public + */ + +Model.prototype.model = function model(name) { + return this.db.model(name); +}; + +/** + * Adds a discriminator type. + * + * ####Example: + * + * function BaseSchema() { + * Schema.apply(this, arguments); + * + * this.add({ + * name: String, + * createdAt: Date + * }); + * } + * util.inherits(BaseSchema, Schema); + * + * var PersonSchema = new BaseSchema(); + * var BossSchema = new BaseSchema({ department: String }); + * + * var Person = mongoose.model('Person', PersonSchema); + * var Boss = Person.discriminator('Boss', BossSchema); + * + * @param {String} name discriminator model name + * @param {Schema} schema discriminator model schema + * @api public + */ + +Model.discriminator = function discriminator(name, schema) { + if (!(schema && schema.instanceOfSchema)) { + throw new Error('You must pass a valid discriminator Schema'); + } + + if (this.schema.discriminatorMapping && !this.schema.discriminatorMapping.isRoot) { + throw new Error('Discriminator "' + name + + '" can only be a discriminator of the root model'); + } + + var key = this.schema.options.discriminatorKey; + if (schema.path(key)) { + throw new Error('Discriminator "' + name + + '" cannot have field with name "' + key + '"'); + } + + function clean(a, b) { + a = utils.clone(a); + b = utils.clone(b); + delete a.toJSON; + delete a.toObject; + delete b.toJSON; + delete b.toObject; + delete a._id; + delete b._id; + + if (!utils.deepEqual(a, b)) { + throw new Error('Discriminator options are not customizable ' + + '(except toJSON, toObject, _id)'); + } + } + + function merge(schema, baseSchema) { + utils.merge(schema, baseSchema); + + var obj = {}; + obj[key] = {type: String, default: name}; + schema.add(obj); + schema.discriminatorMapping = {key: key, value: name, isRoot: false}; + + if (baseSchema.options.collection) { + schema.options.collection = baseSchema.options.collection; + } + + // throws error if options are invalid + clean(schema.options, baseSchema.options); + + var toJSON = schema.options.toJSON; + var toObject = schema.options.toObject; + var _id = schema.options._id; + + schema.options = utils.clone(baseSchema.options); + if (toJSON) schema.options.toJSON = toJSON; + if (toObject) schema.options.toObject = toObject; + if (typeof _id !== 'undefined') { + schema.options._id = _id; + } + + schema.callQueue = baseSchema.callQueue.concat(schema.callQueue.slice(schema._defaultMiddleware.length)); + schema._requiredpaths = undefined; // reset just in case Schema#requiredPaths() was called on either schema + } + + // merges base schema into new discriminator schema and sets new type field. + merge(schema, this.schema); + + if (!this.discriminators) { + this.discriminators = {}; + } + + if (!this.schema.discriminatorMapping) { + this.schema.discriminatorMapping = {key: key, value: null, isRoot: true}; + } + + if (this.discriminators[name]) { + throw new Error('Discriminator with name "' + name + '" already exists'); + } + + this.discriminators[name] = this.db.model(name, schema, this.collection.name); + this.discriminators[name].prototype.__proto__ = this.prototype; + Object.defineProperty(this.discriminators[name], 'baseModelName', { + value: this.modelName, + configurable: true, + writable: false + }); + + // apply methods and statics + applyMethods(this.discriminators[name], schema); + applyStatics(this.discriminators[name], schema); + + return this.discriminators[name]; +}; + +// Model (class) features + +/*! + * Give the constructor the ability to emit events. + */ + +for (var i in EventEmitter.prototype) { + Model[i] = EventEmitter.prototype[i]; +} + +/** + * Called when the model compiles. + * + * @api private + */ + +Model.init = function init() { + if ((this.schema.options.autoIndex) || + (this.schema.options.autoIndex === null && this.db.config.autoIndex)) { + this.ensureIndexes({ __noPromise: true }); + } + + this.schema.emit('init', this); +}; + +/** + * Sends `ensureIndex` commands to mongo for each index declared in the schema. + * + * ####Example: + * + * Event.ensureIndexes(function (err) { + * if (err) return handleError(err); + * }); + * + * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. + * + * ####Example: + * + * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) + * var Event = mongoose.model('Event', eventSchema); + * + * Event.on('index', function (err) { + * if (err) console.error(err); // error occurred during index creation + * }) + * + * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ + * + * The `ensureIndex` commands are not sent in parallel. This is to avoid the `MongoError: cannot add index with a background operation in progress` error. See [this ticket](https://github.com/Automattic/mongoose/issues/1365) for more information. + * + * @param {Object} [options] internal options + * @param {Function} [cb] optional callback + * @return {Promise} + * @api public + */ + +Model.ensureIndexes = function ensureIndexes(options, cb) { + if (typeof options === 'function') { + cb = options; + options = null; + } + + if (options && options.__noPromise) { + _ensureIndexes(this, cb); + return; + } + + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _ensureIndexes(_this, function(error) { + if (error) { + cb && cb(error); + reject(error); + } + cb && cb(); + resolve(); + }); + }); +}; + +function _ensureIndexes(model, callback) { + var indexes = model.schema.indexes(); + if (!indexes.length) { + process.nextTick(function() { + callback && callback(); + }); + return; + } + // Indexes are created one-by-one to support how MongoDB < 2.4 deals + // with background indexes. + + var done = function(err) { + if (err && model.schema.options.emitIndexErrors) { + model.emit('error', err); + } + model.emit('index', err); + callback && callback(err); + }; + + var indexSingleDone = function(err, fields, options, name) { + model.emit('index-single-done', err, fields, options, name); + }; + var indexSingleStart = function(fields, options) { + model.emit('index-single-start', fields, options); + }; + + var create = function() { + var index = indexes.shift(); + if (!index) return done(); + + var indexFields = index[0]; + var options = index[1]; + _handleSafe(options); + + indexSingleStart(indexFields, options); + + model.collection.ensureIndex(indexFields, options, tick(function(err, name) { + indexSingleDone(err, indexFields, options, name); + if (err) { + return done(err); + } + create(); + })); + }; + + create(); +} + +function _handleSafe(options) { + if (options.safe) { + if (typeof options.safe === 'boolean') { + options.w = options.safe; + delete options.safe; + } + if (typeof options.safe === 'object') { + options.w = options.safe.w; + options.j = options.safe.j; + options.wtimeout = options.safe.wtimeout; + delete options.safe; + } + } +} + +/** + * Schema the model uses. + * + * @property schema + * @receiver Model + * @api public + */ + +Model.schema; + +/*! + * Connection instance the model uses. + * + * @property db + * @receiver Model + * @api public + */ + +Model.db; + +/*! + * Collection the model uses. + * + * @property collection + * @receiver Model + * @api public + */ + +Model.collection; + +/** + * Base Mongoose instance the model uses. + * + * @property base + * @receiver Model + * @api public + */ + +Model.base; + +/** + * Registered discriminators for this model. + * + * @property discriminators + * @receiver Model + * @api public + */ + +Model.discriminators; + +/** + * Removes documents from the collection. + * + * ####Example: + * + * Comment.remove({ title: 'baby born from alien father' }, function (err) { + * + * }); + * + * ####Note: + * + * To remove documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js): + * + * var query = Comment.remove({ _id: id }); + * query.exec(); + * + * ####Note: + * + * This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, _no middleware (hooks) are executed_. + * + * @param {Object} conditions + * @param {Function} [callback] + * @return {Promise} Promise + * @api public + */ + +Model.remove = function remove(conditions, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + + // get the mongodb collection object + var mq = new Query(conditions, {}, this, this.collection); + + return mq.remove(callback); +}; + +/** + * Finds documents + * + * The `conditions` are cast to their respective SchemaTypes before the command is sent. + * + * ####Examples: + * + * // named john and at least 18 + * MyModel.find({ name: 'john', age: { $gte: 18 }}); + * + * // executes immediately, passing results to callback + * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); + * + * // name LIKE john and only selecting the "name" and "friends" fields, executing immediately + * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) + * + * // passing options + * MyModel.find({ name: /john/i }, null, { skip: 10 }) + * + * // passing options and executing immediately + * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); + * + * // executing a query explicitly + * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }) + * query.exec(function (err, docs) {}); + * + * // using the promise returned from executing a query + * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }); + * var promise = query.exec(); + * promise.addBack(function (err, docs) {}); + * + * @param {Object} conditions + * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo) + * @param {Object} [options] optional + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see promise #promise-js + * @api public + */ + +Model.find = function find(conditions, projection, options, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + projection = null; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + projection = null; + options = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } + + // get the raw mongodb collection object + var mq = new Query({}, {}, this, this.collection); + mq.select(projection); + mq.setOptions(options); + if (this.schema.discriminatorMapping && mq.selectedInclusively()) { + mq.select(this.schema.options.discriminatorKey); + } + + return mq.find(conditions, callback); +}; + +/** + * Finds a single document by its _id field. `findById(id)` is almost* + * equivalent to `findOne({ _id: id })`. + * + * The `id` is cast based on the Schema before sending the command. + * + * Note: `findById()` triggers `findOne` hooks. + * + * * Except for how it treats `undefined`. Because the MongoDB driver + * deletes keys that have value `undefined`, `findById(undefined)` gets + * translated to `findById({ _id: null })`. + * + * ####Example: + * + * // find adventure by id and execute immediately + * Adventure.findById(id, function (err, adventure) {}); + * + * // same as above + * Adventure.findById(id).exec(callback); + * + * // select only the adventures name and length + * Adventure.findById(id, 'name length', function (err, adventure) {}); + * + * // same as above + * Adventure.findById(id, 'name length').exec(callback); + * + * // include all properties except for `length` + * Adventure.findById(id, '-length').exec(function (err, adventure) {}); + * + * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean` + * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {}); + * + * // same as above + * Adventure.findById(id, 'name').lean().exec(function (err, doc) {}); + * + * @param {Object|String|Number} id value of `_id` to query by + * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo) + * @param {Object} [options] optional + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see lean queries #query_Query-lean + * @api public + */ + +Model.findById = function findById(id, projection, options, callback) { + if (typeof id === 'undefined') { + id = null; + } + return this.findOne({_id: id}, projection, options, callback); +}; + +/** + * Finds one document. + * + * The `conditions` are cast to their respective SchemaTypes before the command is sent. + * + * ####Example: + * + * // find one iphone adventures - iphone adventures?? + * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {}); + * + * // same as above + * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); + * + * // select only the adventures name + * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); + * + * // same as above + * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); + * + * // specify options, in this case lean + * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback); + * + * // same as above + * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback); + * + * // chaining findOne queries (same as above) + * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback); + * + * @param {Object} [conditions] + * @param {Object} [projection] optional fields to return (http://bit.ly/1HotzBo) + * @param {Object} [options] optional + * @param {Function} [callback] + * @return {Query} + * @see field selection #query_Query-select + * @see lean queries #query_Query-lean + * @api public + */ + +Model.findOne = function findOne(conditions, projection, options, callback) { + if (typeof options === 'function') { + callback = options; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + projection = null; + options = null; + } else if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + projection = null; + options = null; + } + + // get the mongodb collection object + var mq = new Query({}, {}, this, this.collection); + mq.select(projection); + mq.setOptions(options); + if (this.schema.discriminatorMapping && mq.selectedInclusively()) { + mq.select(this.schema.options.discriminatorKey); + } + + return mq.findOne(conditions, callback); +}; + +/** + * Counts number of matching documents in a database collection. + * + * ####Example: + * + * Adventure.count({ type: 'jungle' }, function (err, count) { + * if (err) .. + * console.log('there are %d jungle adventures', count); + * }); + * + * @param {Object} conditions + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.count = function count(conditions, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + + // get the mongodb collection object + var mq = new Query({}, {}, this, this.collection); + + return mq.count(conditions, callback); +}; + +/** + * Creates a Query for a `distinct` operation. + * + * Passing a `callback` immediately executes the query. + * + * ####Example + * + * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { + * if (err) return handleError(err); + * + * assert(Array.isArray(result)); + * console.log('unique urls with more than 100 clicks', result); + * }) + * + * var query = Link.distinct('url'); + * query.exec(callback); + * + * @param {String} field + * @param {Object} [conditions] optional + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.distinct = function distinct(field, conditions, callback) { + // get the mongodb collection object + var mq = new Query({}, {}, this, this.collection); + + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + + return mq.distinct(field, conditions, callback); +}; + +/** + * Creates a Query, applies the passed conditions, and returns the Query. + * + * For example, instead of writing: + * + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * we can instead write: + * + * User.where('age').gte(21).lte(65).exec(callback); + * + * Since the Query class also supports `where` you can continue chaining + * + * User + * .where('age').gte(21).lte(65) + * .where('name', /^b/i) + * ... etc + * + * @param {String} path + * @param {Object} [val] optional value + * @return {Query} + * @api public + */ + +Model.where = function where(path, val) { + void val; // eslint + // get the mongodb collection object + var mq = new Query({}, {}, this, this.collection).find({}); + return mq.where.apply(mq, arguments); +}; + +/** + * Creates a `Query` and specifies a `$where` condition. + * + * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. + * + * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {}); + * + * @param {String|Function} argument is a javascript string or anonymous function + * @method $where + * @memberOf Model + * @return {Query} + * @see Query.$where #query_Query-%24where + * @api public + */ + +Model.$where = function $where() { + var mq = new Query({}, {}, this, this.collection).find({}); + return mq.$where.apply(mq, arguments); +}; + +/** + * Issues a mongodb findAndModify update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned. + * + * ####Options: + * + * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * + * ####Examples: + * + * A.findOneAndUpdate(conditions, update, options, callback) // executes + * A.findOneAndUpdate(conditions, update, options) // returns Query + * A.findOneAndUpdate(conditions, update, callback) // executes + * A.findOneAndUpdate(conditions, update) // returns Query + * A.findOneAndUpdate() // returns Query + * + * ####Note: + * + * All top level update keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * var query = { name: 'borne' }; + * Model.findOneAndUpdate(query, { name: 'jason borne' }, options, callback) + * + * // is sent as + * Model.findOneAndUpdate(query, { $set: { name: 'jason borne' }}, options, callback) + * + * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`. + * + * ####Note: + * + * Values are cast to their appropriate types when using the findAndModify helpers. + * However, the below are never executed. + * + * - defaults + * - setters + * + * `findAndModify` helpers support limited defaults and validation. You can + * enable these by setting the `setDefaultsOnInsert` and `runValidators` options, + * respectively. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason borne'; + * doc.save(callback); + * }); + * + * @param {Object} [conditions] + * @param {Object} [update] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Model.findOneAndUpdate = function(conditions, update, options, callback) { + if (typeof options === 'function') { + callback = options; + options = null; + } else if (arguments.length === 1) { + if (typeof conditions === 'function') { + var msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' + + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n' + + ' ' + this.modelName + '.findOneAndUpdate(update)\n' + + ' ' + this.modelName + '.findOneAndUpdate()\n'; + throw new TypeError(msg); + } + update = conditions; + conditions = undefined; + } + + var fields; + if (options && options.fields) { + fields = options.fields; + options.fields = undefined; + } + + update = utils.clone(update, {depopulate: 1}); + if (this.schema.options.versionKey && options && options.upsert) { + if (!update.$setOnInsert) { + update.$setOnInsert = {}; + } + update.$setOnInsert[this.schema.options.versionKey] = 0; + } + + var mq = new Query({}, {}, this, this.collection); + mq.select(fields); + + return mq.findOneAndUpdate(conditions, update, options, callback); +}; + +/** + * Issues a mongodb findAndModify update command by a document's _id field. + * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`. + * + * Finds a matching document, updates it according to the `update` arg, + * passing any `options`, and returns the found document (if any) to the + * callback. The query executes immediately if `callback` is passed else a + * Query object is returned. + * + * This function triggers `findOneAndUpdate` middleware. + * + * ####Options: + * + * - `new`: bool - true to return the modified document rather than the original. defaults to false + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * + * ####Examples: + * + * A.findByIdAndUpdate(id, update, options, callback) // executes + * A.findByIdAndUpdate(id, update, options) // returns Query + * A.findByIdAndUpdate(id, update, callback) // executes + * A.findByIdAndUpdate(id, update) // returns Query + * A.findByIdAndUpdate() // returns Query + * + * ####Note: + * + * All top level update keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * Model.findByIdAndUpdate(id, { name: 'jason borne' }, options, callback) + * + * // is sent as + * Model.findByIdAndUpdate(id, { $set: { name: 'jason borne' }}, options, callback) + * + * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`. + * + * ####Note: + * + * Values are cast to their appropriate types when using the findAndModify helpers. + * However, the below are never executed. + * + * - defaults + * - setters + * + * `findAndModify` helpers support limited defaults and validation. You can + * enable these by setting the `setDefaultsOnInsert` and `runValidators` options, + * respectively. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason borne'; + * doc.save(callback); + * }); + * + * @param {Object|Number|String} id value of `_id` to query by + * @param {Object} [update] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Model.findByIdAndUpdate = function(id, update, options, callback) { + if (arguments.length === 1) { + if (typeof id === 'function') { + var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' + + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' + + ' ' + this.modelName + '.findByIdAndUpdate()\n'; + throw new TypeError(msg); + } + return this.findOneAndUpdate({_id: id}, undefined); + } + + // if a model is passed in instead of an id + if (id instanceof Document) { + id = id._id; + } + + return this.findOneAndUpdate.call(this, {_id: id}, update, options, callback); +}; + +/** + * Issue a mongodb findAndModify remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * + * Executes immediately if `callback` is passed else a Query object is returned. + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * + * ####Examples: + * + * A.findOneAndRemove(conditions, options, callback) // executes + * A.findOneAndRemove(conditions, options) // return Query + * A.findOneAndRemove(conditions, callback) // executes + * A.findOneAndRemove(conditions) // returns Query + * A.findOneAndRemove() // returns Query + * + * Values are cast to their appropriate types when using the findAndModify helpers. + * However, the below are never executed. + * + * - defaults + * - setters + * + * `findAndModify` helpers support limited defaults and validation. You can + * enable these by setting the `setDefaultsOnInsert` and `runValidators` options, + * respectively. + * + * If you need full-fledged validation, use the traditional approach of first + * retrieving the document. + * + * Model.findById(id, function (err, doc) { + * if (err) .. + * doc.name = 'jason borne'; + * doc.save(callback); + * }); + * + * @param {Object} conditions + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Model.findOneAndRemove = function(conditions, options, callback) { + if (arguments.length === 1 && typeof conditions === 'function') { + var msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' + + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' + + ' ' + this.modelName + '.findOneAndRemove()\n'; + throw new TypeError(msg); + } + + if (typeof options === 'function') { + callback = options; + options = undefined; + } + + var fields; + if (options) { + fields = options.select; + options.select = undefined; + } + + var mq = new Query({}, {}, this, this.collection); + mq.select(fields); + + return mq.findOneAndRemove(conditions, options, callback); +}; + +/** + * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * + * Executes immediately if `callback` is passed, else a `Query` object is returned. + * + * ####Options: + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `select`: sets the document fields to return + * + * ####Examples: + * + * A.findByIdAndRemove(id, options, callback) // executes + * A.findByIdAndRemove(id, options) // return Query + * A.findByIdAndRemove(id, callback) // executes + * A.findByIdAndRemove(id) // returns Query + * A.findByIdAndRemove() // returns Query + * + * @param {Object|Number|String} id value of `_id` to query by + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @see Model.findOneAndRemove #model_Model.findOneAndRemove + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + */ + +Model.findByIdAndRemove = function(id, options, callback) { + if (arguments.length === 1 && typeof id === 'function') { + var msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' + + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' + + ' ' + this.modelName + '.findByIdAndRemove(id)\n' + + ' ' + this.modelName + '.findByIdAndRemove()\n'; + throw new TypeError(msg); + } + + return this.findOneAndRemove({_id: id}, options, callback); +}; + +/** + * Shortcut for creating a new Document that is automatically saved to the db + * if valid. + * + * ####Example: + * + * // pass individual docs + * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) { + * if (err) // ... + * }); + * + * // pass an array + * var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; + * Candy.create(array, function (err, candies) { + * if (err) // ... + * + * var jellybean = candies[0]; + * var snickers = candies[1]; + * // ... + * }); + * + * // callback is optional; use the returned promise if you like: + * var promise = Candy.create({ type: 'jawbreaker' }); + * promise.then(function (jawbreaker) { + * // ... + * }) + * + * @param {Array|Object|*} doc(s) + * @param {Function} [callback] callback + * @return {Promise} + * @api public + */ + +Model.create = function create(doc, callback) { + var args, + cb; + + if (Array.isArray(doc)) { + args = doc; + cb = callback; + } else { + var last = arguments[arguments.length - 1]; + if (typeof last === 'function') { + cb = last; + args = utils.args(arguments, 0, arguments.length - 1); + } else { + args = utils.args(arguments); + } + } + + var Promise = PromiseProvider.get(); + var _this = this; + + var promise = new Promise.ES6(function(resolve, reject) { + if (args.length === 0) { + process.nextTick(function() { + cb && cb(null); + resolve(null); + }); + return; + } + + var toExecute = []; + args.forEach(function(doc) { + toExecute.push(function(callback) { + var toSave = new _this(doc); + var callbackWrapper = function(error, doc) { + if (error) { + return callback(error); + } + callback(null, doc); + }; + + // Hack to avoid getting a promise because of + // $__registerHooksFromSchema + if (toSave.$__original_save) { + toSave.$__original_save({__noPromise: true}, callbackWrapper); + } else { + toSave.save({__noPromise: true}, callbackWrapper); + } + }); + }); + + async.parallel(toExecute, function(error, savedDocs) { + if (error) { + cb && cb(error); + reject(error); + return; + } + + if (doc instanceof Array) { + resolve(savedDocs); + cb && cb.call(_this, null, savedDocs); + } else { + resolve.apply(promise, savedDocs); + if (cb) { + savedDocs.unshift(null); + cb.apply(_this, savedDocs); + } + } + }); + }); + + return promise; +}; + +/** + * Shortcut for validating an array of documents and inserting them into + * MongoDB if they're all valid. This function is faster than `.create()` + * because it only sends one operation to the server, rather than one for each + * document. + * + * This function does **not** trigger save middleware. + * + * ####Example: + * + * var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }]; + * Movies.insertMany(arr, function(error, docs) {}); + * + * @param {Array|Object|*} doc(s) + * @param {Function} [callback] callback + * @return {Promise} + * @api public + */ + +Model.insertMany = function(arr, callback) { + var _this = this; + var Promise = PromiseProvider.get(); + + return new Promise.ES6(function(resolve, reject) { + var toExecute = []; + arr.forEach(function(doc) { + toExecute.push(function(callback) { + doc = new _this(doc); + doc.validate({__noPromise: true}, function(error) { + if (error) { + return callback(error); + } + callback(null, doc); + }); + }); + }); + + async.parallel(toExecute, function(error, docs) { + if (error) { + reject(error); + callback && callback(error); + return; + } + var docObjects = docs.map(function(doc) { + return doc.toObject({virtuals: false}); + }); + _this.collection.insertMany(docObjects, function(error) { + if (error) { + reject(error); + callback && callback(error); + return; + } + resolve(docs); + callback && callback(null, docs); + }); + }); + }); +}; + +/** + * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. + * The document returned has no paths marked as modified initially. + * + * ####Example: + * + * // hydrate previous data into a Mongoose document + * var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' }); + * + * @param {Object} obj + * @return {Document} + * @api public + */ + +Model.hydrate = function(obj) { + var model = require('./queryhelpers').createModel(this, obj); + model.init(obj); + return model; +}; + +/** + * Updates documents in the database without returning them. + * + * ####Examples: + * + * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); + * MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, raw) { + * if (err) return handleError(err); + * console.log('The raw response from Mongo was ', raw); + * }); + * + * ####Valid options: + * + * - `safe` (boolean) safe mode (defaults to value set in schema (true)) + * - `upsert` (boolean) whether to create the doc if it doesn't match (false) + * - `multi` (boolean) whether multiple documents should be updated (false) + * - `strict` (boolean) overrides the `strict` option for this update + * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false) + * + * All `update` values are cast to their appropriate SchemaTypes before being sent. + * + * The `callback` function receives `(err, rawResponse)`. + * + * - `err` is the error if any occurred + * - `rawResponse` is the full response from Mongo + * + * ####Note: + * + * All top level keys which are not `atomic` operation names are treated as set operations: + * + * ####Example: + * + * var query = { name: 'borne' }; + * Model.update(query, { name: 'jason borne' }, options, callback) + * + * // is sent as + * Model.update(query, { $set: { name: 'jason borne' }}, options, callback) + * // if overwrite option is false. If overwrite is true, sent without the $set wrapper. + * + * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason borne' }`. + * + * ####Note: + * + * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. + * + * ####Note: + * + * To update documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js): + * + * Comment.update({ _id: id }, { $set: { text: 'changed' }}).exec(); + * + * ####Note: + * + * Although values are casted to their appropriate types when using update, the following are *not* applied: + * + * - defaults + * - setters + * - validators + * - middleware + * + * If you need those features, use the traditional approach of first retrieving the document. + * + * Model.findOne({ name: 'borne' }, function (err, doc) { + * if (err) .. + * doc.name = 'jason borne'; + * doc.save(callback); + * }) + * + * @see strict http://mongoosejs.com/docs/guide.html#strict + * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output + * @param {Object} conditions + * @param {Object} doc + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} + * @api public + */ + +Model.update = function update(conditions, doc, options, callback) { + var mq = new Query({}, {}, this, this.collection); + // gh-2406 + // make local deep copy of conditions + if (conditions instanceof Document) { + conditions = conditions.toObject(); + } else { + conditions = utils.clone(conditions, {retainKeyOrder: true}); + } + options = typeof options === 'function' ? options : utils.clone(options); + + return mq.update(conditions, doc, options, callback); +}; + +/** + * Executes a mapReduce command. + * + * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options. + * + * ####Example: + * + * var o = {}; + * o.map = function () { emit(this.name, 1) } + * o.reduce = function (k, vals) { return vals.length } + * User.mapReduce(o, function (err, results) { + * console.log(results) + * }) + * + * ####Other options: + * + * - `query` {Object} query filter object. + * - `sort` {Object} sort input objects using this key + * - `limit` {Number} max number of documents + * - `keeptemp` {Boolean, default:false} keep temporary data + * - `finalize` {Function} finalize function + * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution + * - `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} + * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. + * + * ####* out options: + * + * - `{inline:1}` the results are returned in an array + * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection + * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions + * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old + * + * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the `lean` option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). + * + * ####Example: + * + * var o = {}; + * o.map = function () { emit(this.name, 1) } + * o.reduce = function (k, vals) { return vals.length } + * o.out = { replace: 'createdCollectionNameForResults' } + * o.verbose = true; + * + * User.mapReduce(o, function (err, model, stats) { + * console.log('map reduce took %d ms', stats.processtime) + * model.find().where('value').gt(10).exec(function (err, docs) { + * console.log(docs); + * }); + * }) + * + * // a promise is returned so you may instead write + * var promise = User.mapReduce(o); + * promise.then(function (model, stats) { + * console.log('map reduce took %d ms', stats.processtime) + * return model.find().where('value').gt(10).exec(); + * }).then(function (docs) { + * console.log(docs); + * }).then(null, handleError).end() + * + * @param {Object} o an object specifying map-reduce options + * @param {Function} [callback] optional callback + * @see http://www.mongodb.org/display/DOCS/MapReduce + * @return {Promise} + * @api public + */ + +Model.mapReduce = function mapReduce(o, callback) { + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + if (!Model.mapReduce.schema) { + var opts = {noId: true, noVirtualId: true, strict: false}; + Model.mapReduce.schema = new Schema({}, opts); + } + + if (!o.out) o.out = {inline: 1}; + if (o.verbose !== false) o.verbose = true; + + o.map = String(o.map); + o.reduce = String(o.reduce); + + if (o.query) { + var q = new Query(o.query); + q.cast(_this); + o.query = q._conditions; + q = undefined; + } + + _this.collection.mapReduce(null, null, o, function(err, ret, stats) { + if (err) { + callback && callback(err); + reject(err); + return; + } + + if (ret.findOne && ret.mapReduce) { + // returned a collection, convert to Model + var model = Model.compile( + '_mapreduce_' + ret.collectionName + , Model.mapReduce.schema + , ret.collectionName + , _this.db + , _this.base); + + model._mapreduce = true; + + callback && callback(null, model, stats); + return resolve(model, stats); + } + + callback && callback(null, ret, stats); + resolve(ret, stats); + }); + }); +}; + +/** + * geoNear support for Mongoose + * + * ####Options: + * - `lean` {Boolean} return the raw object + * - All options supported by the driver are also supported + * + * ####Example: + * + * // Legacy point + * Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) { + * console.log(results); + * }); + * + * // geoJson + * var point = { type : "Point", coordinates : [9,9] }; + * Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) { + * console.log(results); + * }); + * + * @param {Object|Array} GeoJSON point or legacy coordinate pair [x,y] to search near + * @param {Object} options for the qurery + * @param {Function} [callback] optional callback for the query + * @return {Promise} + * @see http://docs.mongodb.org/manual/core/2dsphere/ + * @see http://mongodb.github.io/node-mongodb-native/api-generated/collection.html?highlight=geonear#geoNear + * @api public + */ + +Model.geoNear = function(near, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var _this = this; + var Promise = PromiseProvider.get(); + if (!near) { + return new Promise.ES6(function(resolve, reject) { + var error = new Error('Must pass a near option to geoNear'); + reject(error); + callback && callback(error); + }); + } + + var x, y; + + return new Promise.ES6(function(resolve, reject) { + var handler = function(err, res) { + if (err) { + reject(err); + callback && callback(err); + return; + } + if (options.lean) { + resolve(res.results, res.stats); + callback && callback(null, res.results, res.stats); + return; + } + + var count = res.results.length; + // if there are no results, fulfill the promise now + if (count === 0) { + resolve(res.results, res.stats); + callback && callback(null, res.results, res.stats); + return; + } + + var errSeen = false; + + function init(err) { + if (err && !errSeen) { + errSeen = true; + reject(err); + callback && callback(err); + return; + } + if (--count <= 0) { + resolve(res.results, res.stats); + callback && callback(null, res.results, res.stats); + } + } + + for (var i = 0; i < res.results.length; i++) { + var temp = res.results[i].obj; + res.results[i].obj = new _this(); + res.results[i].obj.init(temp, init); + } + }; + + if (Array.isArray(near)) { + if (near.length !== 2) { + var error = new Error('If using legacy coordinates, must be an array ' + + 'of size 2 for geoNear'); + reject(error); + callback && callback(error); + return; + } + x = near[0]; + y = near[1]; + _this.collection.geoNear(x, y, options, handler); + } else { + if (near.type !== 'Point' || !Array.isArray(near.coordinates)) { + error = new Error('Must pass either a legacy coordinate array or ' + + 'GeoJSON Point to geoNear'); + reject(error); + callback && callback(error); + return; + } + + _this.collection.geoNear(near, options, handler); + } + }); +}; + +/** + * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. + * + * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. + * + * ####Example: + * + * // Find the max balance of all accounts + * Users.aggregate( + * { $group: { _id: null, maxBalance: { $max: '$balance' }}} + * , { $project: { _id: 0, maxBalance: 1 }} + * , function (err, res) { + * if (err) return handleError(err); + * console.log(res); // [ { maxBalance: 98000 } ] + * }); + * + * // Or use the aggregation pipeline builder. + * Users.aggregate() + * .group({ _id: null, maxBalance: { $max: '$balance' } }) + * .select('-id maxBalance') + * .exec(function (err, res) { + * if (err) return handleError(err); + * console.log(res); // [ { maxBalance: 98 } ] + * }); + * + * ####NOTE: + * + * - Arguments are not cast to the model's schema because `$project` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. + * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). + * - Requires MongoDB >= 2.1 + * + * @see Aggregate #aggregate_Aggregate + * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ + * @param {Object|Array} [...] aggregation pipeline operator(s) or operator array + * @param {Function} [callback] + * @return {Aggregate|Promise} + * @api public + */ + +Model.aggregate = function aggregate() { + var args = [].slice.call(arguments), + aggregate, + callback; + + if (typeof args[args.length - 1] === 'function') { + callback = args.pop(); + } + + if (args.length === 1 && util.isArray(args[0])) { + aggregate = new Aggregate(args[0]); + } else { + aggregate = new Aggregate(args); + } + + aggregate.model(this); + + if (typeof callback === 'undefined') { + return aggregate; + } + + return aggregate.exec(callback); +}; + +/** + * Implements `$geoSearch` functionality for Mongoose + * + * ####Example: + * + * var options = { near: [10, 10], maxDistance: 5 }; + * Locations.geoSearch({ type : "house" }, options, function(err, res) { + * console.log(res); + * }); + * + * ####Options: + * - `near` {Array} x,y point to search for + * - `maxDistance` {Number} the maximum distance from the point near that a result can be + * - `limit` {Number} The maximum number of results to return + * - `lean` {Boolean} return the raw object instead of the Mongoose Model + * + * @param {Object} conditions an object that specifies the match condition (required) + * @param {Object} options for the geoSearch, some (near, maxDistance) are required + * @param {Function} [callback] optional callback + * @return {Promise} + * @see http://docs.mongodb.org/manual/reference/command/geoSearch/ + * @see http://docs.mongodb.org/manual/core/geohaystack/ + * @api public + */ + +Model.geoSearch = function(conditions, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var _this = this; + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + var error; + if (conditions === undefined || !utils.isObject(conditions)) { + error = new Error('Must pass conditions to geoSearch'); + } else if (!options.near) { + error = new Error('Must specify the near option in geoSearch'); + } else if (!Array.isArray(options.near)) { + error = new Error('near option must be an array [x, y]'); + } + + if (error) { + callback && callback(error); + reject(error); + return; + } + + // send the conditions in the options object + options.search = conditions; + + _this.collection.geoHaystackSearch(options.near[0], options.near[1], options, function(err, res) { + // have to deal with driver problem. Should be fixed in a soon-ish release + // (7/8/2013) + if (err) { + callback && callback(err); + reject(err); + return; + } + + var count = res.results.length; + if (options.lean || count === 0) { + callback && callback(null, res.results, res.stats); + resolve(res.results, res.stats); + return; + } + + var errSeen = false; + + function init(err) { + if (err && !errSeen) { + callback && callback(err); + reject(err); + return; + } + + if (!--count && !errSeen) { + callback && callback(null, res.results, res.stats); + resolve(res.results, res.stats); + } + } + + for (var i = 0; i < res.results.length; i++) { + var temp = res.results[i]; + res.results[i] = new _this(); + res.results[i].init(temp, {}, init); + } + }); + }); +}; + +/** + * Populates document references. + * + * ####Available options: + * + * - path: space delimited path(s) to populate + * - select: optional fields to select + * - match: optional query conditions to match + * - model: optional name of the model to use for population + * - options: optional query options like sort, limit, etc + * + * ####Examples: + * + * // populates a single object + * User.findById(id, function (err, user) { + * var opts = [ + * { path: 'company', match: { x: 1 }, select: 'name' } + * , { path: 'notes', options: { limit: 10 }, model: 'override' } + * ] + * + * User.populate(user, opts, function (err, user) { + * console.log(user); + * }) + * }) + * + * // populates an array of objects + * User.find(match, function (err, users) { + * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }] + * + * var promise = User.populate(users, opts); + * promise.then(console.log).end(); + * }) + * + * // imagine a Weapon model exists with two saved documents: + * // { _id: 389, name: 'whip' } + * // { _id: 8921, name: 'boomerang' } + * + * var user = { name: 'Indiana Jones', weapon: 389 } + * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) { + * console.log(user.weapon.name) // whip + * }) + * + * // populate many plain objects + * var users = [{ name: 'Indiana Jones', weapon: 389 }] + * users.push({ name: 'Batman', weapon: 8921 }) + * Weapon.populate(users, { path: 'weapon' }, function (err, users) { + * users.forEach(function (user) { + * console.log('%s uses a %s', users.name, user.weapon.name) + * // Indiana Jones uses a whip + * // Batman uses a boomerang + * }) + * }) + * // Note that we didn't need to specify the Weapon model because + * // we were already using it's populate() method. + * + * @param {Document|Array} docs Either a single document or array of documents to populate. + * @param {Object} options A hash of key/val (path, options) used for population. + * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. + * @return {Promise} + * @api public + */ + +Model.populate = function(docs, paths, cb) { + var _this = this; + + // normalized paths + var noPromise = paths && !!paths.__noPromise; + paths = utils.populate(paths); + + if (noPromise) { + _populate(this, docs, paths, cb); + } else { + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve, reject) { + _populate(_this, docs, paths, function(error, docs) { + if (error) { + cb && cb(error); + reject(error); + } else { + cb && cb(null, docs); + resolve(docs); + } + }); + }); + } +}; + +/*! + * Populate helper + * + * @param {Model} model the model to use + * @param {Document|Array} docs Either a single document or array of documents to populate. + * @param {Object} paths + * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. + * @return {Function} + * @api private + */ + +function _populate(model, docs, paths, cb) { + var pending = paths.length; + + if (pending === 0) { + return cb(null, docs); + } + + // each path has its own query options and must be executed separately + var i = pending; + var path; + while (i--) { + path = paths[i]; + if (typeof path.model === 'function') { + model = path.model; + } + populate(model, docs, path, subPopulate.call(model, docs, path, next)); + } + + function next(err) { + if (err) { + return cb(err); + } + if (--pending) { + return; + } + cb(null, docs); + } +} + +/*! + * Populates deeply if `populate` option is present. + * + * @param {Document|Array} docs + * @param {Object} options + * @param {Function} cb + * @return {Function} + * @api private + */ +function subPopulate(docs, options, cb) { + var _this = this; + var prefix = options.path + '.'; + var pop = options.populate; + + if (!pop) { + return cb; + } + + // normalize as array + if (!Array.isArray(pop)) { + pop = [pop]; + } + + return function(err) { + var pending = pop.length; + + function next(err) { + if (err) return cb(err); + if (--pending) return; + cb(); + } + + if (err || !pending) return cb(err); + + pop.forEach(function(subOptions) { + subOptions = utils.clone(subOptions); + // path needs parent's path prefixed to it + if (!subOptions._originalPath) { + subOptions._originalPath = subOptions.path; + subOptions.path = prefix + subOptions.path; + } + + var schema = _this.schema._getSchema(prefix); + if (typeof subOptions.model === 'string') { + subOptions.model = _this.model(subOptions.model); + } else if (schema && schema.caster && schema.caster.options && + schema.caster.options.ref) { + var subSchema = _this.model(schema.caster.options.ref).schema. + _getSchema(subOptions._originalPath); + if (subSchema && subSchema.options && subSchema.options.ref) { + subOptions.model = _this.model(subSchema.options.ref); + } + } + Model.populate.call(subOptions.model || _this, docs, subOptions, next); + }); + }; +} + +/*! + * Populates `docs` + */ +var excludeIdReg = /\s?-_id\s?/, + excludeIdRegGlobal = /\s?-_id\s?/g; + +function populate(model, docs, options, cb) { + var modelsMap, rawIds; + + // normalize single / multiple docs passed + if (!Array.isArray(docs)) { + docs = [docs]; + } + + if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) { + return cb(); + } + + modelsMap = getModelsMapForPopulate(model, docs, options); + rawIds = getIdsForAndAddIdsInMapPopulate(modelsMap); + + var i, len = modelsMap.length, + mod, match, select, promise, vals = []; + + promise = new Promise(function(err, vals, options, assignmentOpts) { + if (err) return cb(err); + + var lean = options.options && options.options.lean, + len = vals.length, + rawOrder = {}, rawDocs = {}, key, val; + + // optimization: + // record the document positions as returned by + // the query result. + for (var i = 0; i < len; i++) { + val = vals[i]; + key = String(utils.getValue('_id', val)); + rawDocs[key] = val; + rawOrder[key] = i; + + // flag each as result of population + if (!lean) val.$__.wasPopulated = true; + } + + assignVals({ + rawIds: rawIds, + rawDocs: rawDocs, + rawOrder: rawOrder, + docs: docs, + path: options.path, + options: assignmentOpts + }); + cb(); + }); + + function flatten(item) { + // no need to include undefined values in our query + return undefined !== item; + } + + var _remaining = len; + for (i = 0; i < len; i++) { + mod = modelsMap[i]; + select = mod.options.select; + + if (mod.options.match) { + match = utils.object.shallowCopy(mod.options.match); + } else { + match = {}; + } + + var ids = utils.array.flatten(mod.ids, flatten); + + ids = utils.array.unique(ids); + + if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) { + return cb(); + } + + match._id || (match._id = { + $in: ids + }); + + var assignmentOpts = {}; + assignmentOpts.sort = mod.options.options && mod.options.options.sort || undefined; + assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0); + + if (assignmentOpts.excludeId) { + // override the exclusion from the query so we can use the _id + // for document matching during assignment. we'll delete the + // _id back off before returning the result. + if (typeof select === 'string') { + select = select.replace(excludeIdRegGlobal, ' '); + } else { + // preserve original select conditions by copying + select = utils.object.shallowCopy(select); + delete select._id; + } + } + + if (mod.options.options && mod.options.options.limit) { + assignmentOpts.originalLimit = mod.options.options.limit; + mod.options.options.limit = mod.options.options.limit * ids.length; + } + + mod.Model.find(match, select, mod.options.options, next.bind(this, mod.options, assignmentOpts)); + } + + function next(options, assignmentOpts, err, valsFromDb) { + if (err) return promise.resolve(err); + vals = vals.concat(valsFromDb); + if (--_remaining === 0) { + promise.resolve(err, vals, options, assignmentOpts); + } + } +} + +function getModelsMapForPopulate(model, docs, options) { + var i, doc, len = docs.length, + available = {}, + map = [], + modelNameFromQuery = options.model && options.model.modelName || options.model, + schema, refPath, Model, currentOptions, modelNames, modelName, discriminatorKey, modelForFindSchema; + + schema = model._getSchema(options.path); + + if (schema && schema.caster) { + schema = schema.caster; + } + + if (!schema && model.discriminators) { + discriminatorKey = model.schema.discriminatorMapping.key; + } + + refPath = schema && schema.options && schema.options.refPath; + + for (i = 0; i < len; i++) { + doc = docs[i]; + + if (refPath) { + modelNames = utils.getValue(refPath, doc); + } else { + if (!modelNameFromQuery) { + var schemaForCurrentDoc; + + if (!schema && discriminatorKey) { + modelForFindSchema = utils.getValue(discriminatorKey, doc); + + if (modelForFindSchema) { + schemaForCurrentDoc = model.db.model(modelForFindSchema)._getSchema(options.path); + + if (schemaForCurrentDoc && schemaForCurrentDoc.caster) { + schemaForCurrentDoc = schemaForCurrentDoc.caster; + } + } + } else { + schemaForCurrentDoc = schema; + } + + modelNames = [ + schemaForCurrentDoc && schemaForCurrentDoc.options && schemaForCurrentDoc.options.ref // declared in schema + || model.modelName // an ad-hoc structure + ]; + } else { + modelNames = [modelNameFromQuery]; // query options + } + } + + if (!modelNames) { + continue; + } + + if (!Array.isArray(modelNames)) { + modelNames = [modelNames]; + } + + var k = modelNames.length; + while (k--) { + modelName = modelNames[k]; + if (!available[modelName]) { + Model = model.db.model(modelName); + currentOptions = { + model: Model + }; + + if (schema && !discriminatorKey) { + options.model = Model; + } + + utils.merge(currentOptions, options); + + available[modelName] = { + Model: Model, + options: currentOptions, + docs: [doc], + ids: [] + }; + map.push(available[modelName]); + } else { + available[modelName].docs.push(doc); + } + } + } + + return map; +} + +function getIdsForAndAddIdsInMapPopulate(modelsMap) { + var rawIds = [], // for the correct position + i, j, doc, docs, id, len, len2, ret, isDocument, options, path; + + len2 = modelsMap.length; + for (j = 0; j < len2; j++) { + docs = modelsMap[j].docs; + len = docs.length; + options = modelsMap[j].options; + path = options.path; + + for (i = 0; i < len; i++) { + ret = undefined; + doc = docs[i]; + id = String(utils.getValue('_id', doc)); + isDocument = !!doc.$__; + + if (!ret || Array.isArray(ret) && ret.length === 0) { + ret = utils.getValue(path, doc); + } + + if (ret) { + ret = convertTo_id(ret); + + options._docs[id] = Array.isArray(ret) ? ret.slice() : ret; + } + + rawIds.push(ret); + modelsMap[j].ids.push(ret); + + if (isDocument) { + // cache original populated _ids and model used + doc.populated(path, options._docs[id], options); + } + } + } + + return rawIds; +} + +/*! + * Retrieve the _id of `val` if a Document or Array of Documents. + * + * @param {Array|Document|Any} val + * @return {Array|Document|Any} + */ + +function convertTo_id(val) { + if (val instanceof Model) return val._id; + + if (Array.isArray(val)) { + for (var i = 0; i < val.length; ++i) { + if (val[i] instanceof Model) { + val[i] = val[i]._id; + } + } + return val; + } + + return val; +} + +/*! + * Assigns documents returned from a population query back + * to the original document path. + */ + +function assignVals(o) { + // replace the original ids in our intermediate _ids structure + // with the documents found by query + + assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, o.options); + + // now update the original documents being populated using the + // result structure that contains real documents. + + var docs = o.docs; + var path = o.path; + var rawIds = o.rawIds; + var options = o.options; + + function setValue(val) { + return valueFilter(val, options); + } + + for (var i = 0; i < docs.length; ++i) { + if (utils.getValue(path, docs[i]) == null) { + continue; + } + utils.setValue(path, rawIds[i], docs[i], setValue); + } +} + +/*! + * 1) Apply backwards compatible find/findOne behavior to sub documents + * + * find logic: + * a) filter out non-documents + * b) remove _id from sub docs when user specified + * + * findOne + * a) if no doc found, set to null + * b) remove _id from sub docs when user specified + * + * 2) Remove _ids when specified by users query. + * + * background: + * _ids are left in the query even when user excludes them so + * that population mapping can occur. + */ + +function valueFilter(val, assignmentOpts) { + if (Array.isArray(val)) { + // find logic + var ret = []; + var numValues = val.length; + for (var i = 0; i < numValues; ++i) { + var subdoc = val[i]; + if (!isDoc(subdoc)) continue; + maybeRemoveId(subdoc, assignmentOpts); + ret.push(subdoc); + if (assignmentOpts.originalLimit && + ret.length >= assignmentOpts.originalLimit) { + break; + } + } + + // Since we don't want to have to create a new mongoosearray, make sure to + // modify the array in place + while (val.length > ret.length) { + Array.prototype.pop.apply(val, []); + } + for (i = 0; i < ret.length; ++i) { + val[i] = ret[i]; + } + return val; + } + + // findOne + if (isDoc(val)) { + maybeRemoveId(val, assignmentOpts); + return val; + } + + return null; +} + +/*! + * Remove _id from `subdoc` if user specified "lean" query option + */ + +function maybeRemoveId(subdoc, assignmentOpts) { + if (assignmentOpts.excludeId) { + if (typeof subdoc.setValue === 'function') { + delete subdoc._doc._id; + } else { + delete subdoc._id; + } + } +} + +/*! + * Determine if `doc` is a document returned + * by a populate query. + */ + +function isDoc(doc) { + if (doc == null) { + return false; + } + + var type = typeof doc; + if (type === 'string') { + return false; + } + + if (type === 'number') { + return false; + } + + if (Buffer.isBuffer(doc)) { + return false; + } + + if (doc.constructor.name === 'ObjectID') { + return false; + } + + // only docs + return true; +} + +/*! + * Assign `vals` returned by mongo query to the `rawIds` + * structure returned from utils.getVals() honoring + * query sort order if specified by user. + * + * This can be optimized. + * + * Rules: + * + * if the value of the path is not an array, use findOne rules, else find. + * for findOne the results are assigned directly to doc path (including null results). + * for find, if user specified sort order, results are assigned directly + * else documents are put back in original order of array if found in results + * + * @param {Array} rawIds + * @param {Array} vals + * @param {Boolean} sort + * @api private + */ + +function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, recursed) { + // honor user specified sort order + var newOrder = []; + var sorting = options.sort && rawIds.length > 1; + var doc; + var sid; + var id; + + for (var i = 0; i < rawIds.length; ++i) { + id = rawIds[i]; + + if (Array.isArray(id)) { + // handle [ [id0, id2], [id3] ] + assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, true); + newOrder.push(id); + continue; + } + + if (id === null && !sorting) { + // keep nulls for findOne unless sorting, which always + // removes them (backward compat) + newOrder.push(id); + continue; + } + + sid = String(id); + + if (recursed) { + // apply find behavior + + // assign matching documents in original order unless sorting + doc = resultDocs[sid]; + if (doc) { + if (sorting) { + newOrder[resultOrder[sid]] = doc; + } else { + newOrder.push(doc); + } + } else { + newOrder.push(id); + } + } else { + // apply findOne behavior - if document in results, assign, else assign null + newOrder[i] = doc = resultDocs[sid] || null; + } + } + + rawIds.length = 0; + if (newOrder.length) { + // reassign the documents based on corrected order + + // forEach skips over sparse entries in arrays so we + // can safely use this to our advantage dealing with sorted + // result sets too. + newOrder.forEach(function(doc, i) { + rawIds[i] = doc; + }); + } +} + +/** + * Finds the schema for `path`. This is different than + * calling `schema.path` as it also resolves paths with + * positional selectors (something.$.another.$.path). + * + * @param {String} path + * @return {Schema} + * @api private + */ + +Model._getSchema = function _getSchema(path) { + return this.schema._getSchema(path); +}; + +/*! + * Compiler utility. + * + * @param {String} name model name + * @param {Schema} schema + * @param {String} collectionName + * @param {Connection} connection + * @param {Mongoose} base mongoose instance + */ + +Model.compile = function compile(name, schema, collectionName, connection, base) { + var versioningEnabled = schema.options.versionKey !== false; + + if (versioningEnabled && !schema.paths[schema.options.versionKey]) { + // add versioning to top level documents only + var o = {}; + o[schema.options.versionKey] = Number; + schema.add(o); + } + + // generate new class + function model(doc, fields, skipId) { + if (!(this instanceof model)) { + return new model(doc, fields, skipId); + } + Model.call(this, doc, fields, skipId); + } + + model.hooks = schema.s.hooks.clone(); + model.base = base; + model.modelName = name; + model.__proto__ = Model; + model.prototype.__proto__ = Model.prototype; + model.model = Model.prototype.model; + model.db = model.prototype.db = connection; + model.discriminators = model.prototype.discriminators = undefined; + + model.prototype.$__setSchema(schema); + + var collectionOptions = { + bufferCommands: schema.options.bufferCommands, + capped: schema.options.capped + }; + + model.prototype.collection = connection.collection( + collectionName + , collectionOptions + ); + + // apply methods and statics + applyMethods(model, schema); + applyStatics(model, schema); + + model.schema = model.prototype.schema; + model.collection = model.prototype.collection; + + return model; +}; + +/*! + * Register methods for this model + * + * @param {Model} model + * @param {Schema} schema + */ +var applyMethods = function(model, schema) { + function apply(method, schema) { + Object.defineProperty(model.prototype, method, { + get: function() { + var h = {}; + for (var k in schema.methods[method]) { + h[k] = schema.methods[method][k].bind(this); + } + return h; + }, + configurable: true + }); + } + for (var method in schema.methods) { + if (typeof schema.methods[method] === 'function') { + model.prototype[method] = schema.methods[method]; + } else { + apply(method, schema); + } + } +}; + +/*! + * Register statics for this model + * @param {Model} model + * @param {Schema} schema + */ +var applyStatics = function(model, schema) { + for (var i in schema.statics) { + model[i] = schema.statics[i]; + } +}; + +/*! + * Subclass this model with `conn`, `schema`, and `collection` settings. + * + * @param {Connection} conn + * @param {Schema} [schema] + * @param {String} [collection] + * @return {Model} + */ + +Model.__subclass = function subclass(conn, schema, collection) { + // subclass model using this connection and collection name + var _this = this; + + var Model = function Model(doc, fields, skipId) { + if (!(this instanceof Model)) { + return new Model(doc, fields, skipId); + } + _this.call(this, doc, fields, skipId); + }; + + Model.__proto__ = _this; + Model.prototype.__proto__ = _this.prototype; + Model.db = Model.prototype.db = conn; + + var s = schema && typeof schema !== 'string' + ? schema + : _this.prototype.schema; + + var options = s.options || {}; + + if (!collection) { + collection = _this.prototype.schema.get('collection') + || utils.toCollectionName(_this.modelName, options); + } + + var collectionOptions = { + bufferCommands: s ? options.bufferCommands : true, + capped: s && options.capped + }; + + Model.prototype.collection = conn.collection(collection, collectionOptions); + Model.collection = Model.prototype.collection; + Model.init(); + return Model; +}; + +/*! + * Module exports. + */ + +module.exports = exports = Model; diff --git a/5-3/node_modules/mongoose/lib/promise.js b/5-3/node_modules/mongoose/lib/promise.js new file mode 100644 index 0000000..403eaa3 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/promise.js @@ -0,0 +1,291 @@ +/*! + * Module dependencies + */ + +var MPromise = require('mpromise'); +var util = require('util'); + +/** + * Promise constructor. + * + * Promises are returned from executed queries. Example: + * + * var query = Candy.find({ bar: true }); + * var promise = query.exec(); + * + * DEPRECATED. Mongoose 5.0 will use native promises by default (or bluebird, + * if native promises are not present) but still + * support plugging in your own ES6-compatible promises library. Mongoose 5.0 + * will **not** support mpromise. + * + * @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature + * @inherits mpromise https://github.com/aheckmann/mpromise + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `err`: Emits when the promise is rejected + * @event `complete`: Emits when the promise is fulfilled + * @api public + * @deprecated + */ + +function Promise(fn) { + MPromise.call(this, fn); +} + +/** + * ES6-style promise constructor wrapper around mpromise. + * + * @param {Function} resolver + * @return {Promise} new promise + * @api public + */ +Promise.ES6 = function(resolver) { + var promise = new Promise(); + + // No try/catch for backwards compatibility + resolver( + function() { + promise.complete.apply(promise, arguments); + }, + function(e) { + promise.error(e); + }); + + return promise; +}; + +/*! + * Inherit from mpromise + */ + +Promise.prototype = Object.create(MPromise.prototype, { + constructor: { + value: Promise, + enumerable: false, + writable: true, + configurable: true + } +}); + +/*! + * Override event names for backward compatibility. + */ + +Promise.SUCCESS = 'complete'; +Promise.FAILURE = 'err'; + +/** + * 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. + * + * @see mpromise#on https://github.com/aheckmann/mpromise#on + * @method on + * @memberOf Promise + * @param {String} event + * @param {Function} listener + * @return {Promise} this + * @api public + */ + +/** + * Rejects this promise with `reason`. + * + * If the promise has already been fulfilled or rejected, not action is taken. + * + * @see mpromise#reject https://github.com/aheckmann/mpromise#reject + * @method reject + * @memberOf Promise + * @param {Object|String|Error} reason + * @return {Promise} this + * @api public + */ + +/** + * Rejects this promise with `err`. + * + * If the promise has already been fulfilled or rejected, not action is taken. + * + * Differs from [#reject](#promise_Promise-reject) by first casting `err` to an `Error` if it is not `instanceof Error`. + * + * @api public + * @param {Error|String} err + * @return {Promise} this + */ + +Promise.prototype.error = function(err) { + if (!(err instanceof Error)) { + if (err instanceof Object) { + err = util.inspect(err); + } + err = new Error(err); + } + return this.reject(err); +}; + +/** + * Resolves this promise to a rejected state if `err` is passed or a fulfilled state if no `err` is passed. + * + * If the promise has already been fulfilled or rejected, not action is taken. + * + * `err` will be cast to an Error if not already instanceof Error. + * + * _NOTE: overrides [mpromise#resolve](https://github.com/aheckmann/mpromise#resolve) to provide error casting._ + * + * @param {Error} [err] error or null + * @param {Object} [val] value to fulfill the promise with + * @api public + * @deprecated + */ + +Promise.prototype.resolve = function(err) { + if (err) return this.error(err); + return this.fulfill.apply(this, Array.prototype.slice.call(arguments, 1)); +}; + +/** + * Adds a single function as a listener to both err and complete. + * + * It will be executed with traditional node.js argument position when the promise is resolved. + * + * promise.addBack(function (err, args...) { + * if (err) return handleError(err); + * console.log('success'); + * }) + * + * Alias of [mpromise#onResolve](https://github.com/aheckmann/mpromise#onresolve). + * + * _Deprecated. Use `onResolve` instead._ + * + * @method addBack + * @param {Function} listener + * @return {Promise} this + * @deprecated + */ + +Promise.prototype.addBack = Promise.prototype.onResolve; + +/** + * Fulfills this promise with passed arguments. + * + * @method fulfill + * @receiver Promise + * @see https://github.com/aheckmann/mpromise#fulfill + * @param {any} args + * @api public + * @deprecated + */ + +/** + * Fulfills this promise with passed arguments. + * + * Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill). + * + * _Deprecated. Use `fulfill` instead._ + * + * @method complete + * @receiver Promise + * @param {any} args + * @api public + * @deprecated + */ + +Promise.prototype.complete = MPromise.prototype.fulfill; + +/** + * Adds a listener to the `complete` (success) event. + * + * Alias of [mpromise#onFulfill](https://github.com/aheckmann/mpromise#onfulfill). + * + * _Deprecated. Use `onFulfill` instead._ + * + * @method addCallback + * @param {Function} listener + * @return {Promise} this + * @api public + * @deprecated + */ + +Promise.prototype.addCallback = Promise.prototype.onFulfill; + +/** + * Adds a listener to the `err` (rejected) event. + * + * Alias of [mpromise#onReject](https://github.com/aheckmann/mpromise#onreject). + * + * _Deprecated. Use `onReject` instead._ + * + * @method addErrback + * @param {Function} listener + * @return {Promise} this + * @api public + * @deprecated + */ + +Promise.prototype.addErrback = Promise.prototype.onReject; + +/** + * 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. + * + * ####Example: + * + * var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec(); + * promise.then(function (meetups) { + * var ids = meetups.map(function (m) { + * return m._id; + * }); + * return People.find({ meetups: { $in: ids }).exec(); + * }).then(function (people) { + * if (people.length < 10000) { + * throw new Error('Too few people!!!'); + * } else { + * throw new Error('Still need more people!!!'); + * } + * }).then(null, function (err) { + * assert.ok(err instanceof Error); + * }); + * + * @see promises-A+ https://github.com/promises-aplus/promises-spec + * @see mpromise#then https://github.com/aheckmann/mpromise#then + * @method then + * @memberOf Promise + * @param {Function} onFulFill + * @param {Function} onReject + * @return {Promise} newPromise + * @deprecated + */ + +/** + * 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 + * @see mpromise#end https://github.com/aheckmann/mpromise#end + * @method end + * @memberOf Promise + * @deprecated + */ + +/*! + * expose + */ + +module.exports = Promise; diff --git a/5-3/node_modules/mongoose/lib/promise_provider.js b/5-3/node_modules/mongoose/lib/promise_provider.js new file mode 100644 index 0000000..368cf85 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/promise_provider.js @@ -0,0 +1,51 @@ +/*! + * Module dependencies. + */ + +var MPromise = require('./promise'); + +/** + * Helper for multiplexing promise implementations + * + * @api private + */ + +var Promise = { + _promise: MPromise +}; + +/** + * Get the current promise constructor + * + * @api private + */ +Promise.get = function() { + return Promise._promise; +}; + +/** + * Set the current promise constructor + * + * @api private + */ + +Promise.set = function(lib) { + if (lib === MPromise) { + return Promise.reset(); + } + Promise._promise = require('./ES6Promise'); + Promise._promise.use(lib); + require('mquery').Promise = Promise._promise.ES6; +}; + +/** + * Resets to using mpromise + * + * @api private + */ + +Promise.reset = function() { + Promise._promise = MPromise; +}; + +module.exports = Promise; diff --git a/5-3/node_modules/mongoose/lib/query.js b/5-3/node_modules/mongoose/lib/query.js new file mode 100644 index 0000000..ac426e2 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/query.js @@ -0,0 +1,3146 @@ +/*! + * Module dependencies. + */ + +var mquery = require('mquery'); +var util = require('util'); +var readPref = require('./drivers').ReadPreference; +var PromiseProvider = require('./promise_provider'); +var updateValidators = require('./services/updateValidators'); +var utils = require('./utils'); +var helpers = require('./queryhelpers'); +var QueryStream = require('./querystream'); +var StrictModeError = require('./error/strict'); +var cast = require('./cast'); + +/** + * Query constructor used for building queries. + * + * ####Example: + * + * var query = new Query(); + * query.setOptions({ lean : true }); + * query.collection(model.collection); + * query.where('age').gte(21).exec(callback); + * + * @param {Object} [options] + * @param {Object} [model] + * @param {Object} [conditions] + * @param {Object} [collection] Mongoose collection + * @api private + */ + +function Query(conditions, options, model, collection) { + // this stuff is for dealing with custom queries created by #toConstructor + if (!this._mongooseOptions) { + this._mongooseOptions = {}; + } + + // this is the case where we have a CustomQuery, we need to check if we got + // options passed in, and if we did, merge them in + if (options) { + var keys = Object.keys(options); + for (var i = 0; i < keys.length; ++i) { + var k = keys[i]; + this._mongooseOptions[k] = options[k]; + } + } + + if (collection) { + this.mongooseCollection = collection; + } + + if (model) { + this.model = model; + this.schema = model.schema; + } + + // this is needed because map reduce returns a model that can be queried, but + // all of the queries on said model should be lean + if (this.model && this.model._mapreduce) { + this.lean(); + } + + // inherit mquery + mquery.call(this, this.mongooseCollection, options); + + if (conditions) { + this.find(conditions); + } + + if (this.schema) { + this._count = this.model.hooks.createWrapper('count', + Query.prototype._count, this); + this._execUpdate = this.model.hooks.createWrapper('update', + Query.prototype._execUpdate, this); + this._find = this.model.hooks.createWrapper('find', + Query.prototype._find, this); + this._findOne = this.model.hooks.createWrapper('findOne', + Query.prototype._findOne, this); + this._findOneAndRemove = this.model.hooks.createWrapper('findOneAndRemove', + Query.prototype._findOneAndRemove, this); + this._findOneAndUpdate = this.model.hooks.createWrapper('findOneAndUpdate', + Query.prototype._findOneAndUpdate, this); + } +} + +/*! + * inherit mquery + */ + +Query.prototype = new mquery; +Query.prototype.constructor = Query; +Query.base = mquery.prototype; + +/** + * Flag to opt out of using `$geoWithin`. + * + * mongoose.Query.use$geoWithin = false; + * + * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work. + * + * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ + * @default true + * @property use$geoWithin + * @memberOf Query + * @receiver Query + * @api public + */ + +Query.use$geoWithin = mquery.use$geoWithin; + +/** + * Converts this query to a customized, reusable query constructor with all arguments and options retained. + * + * ####Example + * + * // Create a query for adventure movies and read from the primary + * // node in the replica-set unless it is down, in which case we'll + * // read from a secondary node. + * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred'); + * + * // create a custom Query constructor based off these settings + * var Adventure = query.toConstructor(); + * + * // Adventure is now a subclass of mongoose.Query and works the same way but with the + * // default query parameters and options set. + * Adventure().exec(callback) + * + * // further narrow down our query results while still using the previous settings + * Adventure().where({ name: /^Life/ }).exec(callback); + * + * // since Adventure is a stand-alone constructor we can also add our own + * // helper methods and getters without impacting global queries + * Adventure.prototype.startsWith = function (prefix) { + * this.where({ name: new RegExp('^' + prefix) }) + * return this; + * } + * Object.defineProperty(Adventure.prototype, 'highlyRated', { + * get: function () { + * this.where({ rating: { $gt: 4.5 }}); + * return this; + * } + * }) + * Adventure().highlyRated.startsWith('Life').exec(callback) + * + * New in 3.7.3 + * + * @return {Query} subclass-of-Query + * @api public + */ + +Query.prototype.toConstructor = function toConstructor() { + var CustomQuery = function(criteria, options) { + if (!(this instanceof CustomQuery)) { + return new CustomQuery(criteria, options); + } + this._mongooseOptions = utils.clone(p._mongooseOptions); + Query.call(this, criteria, options || null); + }; + + util.inherits(CustomQuery, Query); + + // set inherited defaults + var p = CustomQuery.prototype; + + p.options = {}; + + p.setOptions(this.options); + + p.op = this.op; + p._conditions = utils.clone(this._conditions); + p._fields = utils.clone(this._fields); + p._update = utils.clone(this._update); + p._path = this._path; + p._distinct = this._distinct; + p._collection = this._collection; + p.model = this.model; + p.mongooseCollection = this.mongooseCollection; + p._mongooseOptions = this._mongooseOptions; + + return CustomQuery; +}; + +/** + * Specifies a javascript function or expression to pass to MongoDBs query system. + * + * ####Example + * + * query.$where('this.comments.length === 10 || this.name.length === 5') + * + * // or + * + * query.$where(function () { + * return this.comments.length === 10 || this.name.length === 5; + * }) + * + * ####NOTE: + * + * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. + * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.** + * + * @see $where http://docs.mongodb.org/manual/reference/operator/where/ + * @method $where + * @param {String|Function} js javascript string or function + * @return {Query} this + * @memberOf Query + * @method $where + * @api public + */ + +/** + * Specifies a `path` for use with chaining. + * + * ####Example + * + * // instead of writing: + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * // we can instead write: + * User.where('age').gte(21).lte(65); + * + * // passing query conditions is permitted + * User.find().where({ name: 'vonderful' }) + * + * // chaining + * User + * .where('age').gte(21).lte(65) + * .where('name', /^vonderful/i) + * .where('friends').slice(10) + * .exec(callback) + * + * @method where + * @memberOf Query + * @param {String|Object} [path] + * @param {any} [val] + * @return {Query} this + * @api public + */ + +/** + * Specifies the complementary comparison value for paths specified with `where()` + * + * ####Example + * + * User.where('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @method equals + * @memberOf Query + * @param {Object} val + * @return {Query} this + * @api public + */ + +/** + * Specifies arguments for an `$or` condition. + * + * ####Example + * + * query.or([{ color: 'red' }, { status: 'emergency' }]) + * + * @see $or http://docs.mongodb.org/manual/reference/operator/or/ + * @method or + * @memberOf Query + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +/** + * Specifies arguments for a `$nor` condition. + * + * ####Example + * + * query.nor([{ color: 'green' }, { status: 'ok' }]) + * + * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/ + * @method nor + * @memberOf Query + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +/** + * Specifies arguments for a `$and` condition. + * + * ####Example + * + * query.and([{ color: 'green' }, { status: 'ok' }]) + * + * @method and + * @memberOf Query + * @see $and http://docs.mongodb.org/manual/reference/operator/and/ + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +/** + * Specifies a $gt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * Thing.find().where('age').gt(21) + * + * // or + * Thing.find().gt('age', 21) + * + * @method gt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/ + * @api public + */ + +/** + * Specifies a $gte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method gte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/ + * @api public + */ + +/** + * Specifies a $lt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/ + * @api public + */ + +/** + * Specifies a $lte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lte + * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/ + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $ne query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/ + * @method ne + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $in query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $in http://docs.mongodb.org/manual/reference/operator/in/ + * @method in + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $nin query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/ + * @method nin + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $all query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $all http://docs.mongodb.org/manual/reference/operator/all/ + * @method all + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $size query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * MyModel.where('tags').size(0).exec(function (err, docs) { + * if (err) return handleError(err); + * + * assert(Array.isArray(docs)); + * console.log('documents with 0 tags', docs); + * }) + * + * @see $size http://docs.mongodb.org/manual/reference/operator/size/ + * @method size + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $regex query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/ + * @method regex + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $maxDistance query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + * @method maxDistance + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a `$mod` condition + * + * @method mod + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/ + * @api public + */ + +/** + * Specifies an `$exists` condition + * + * ####Example + * + * // { name: { $exists: true }} + * Thing.where('name').exists() + * Thing.where('name').exists(true) + * Thing.find().exists('name') + * + * // { name: { $exists: false }} + * Thing.where('name').exists(false); + * Thing.find().exists('name', false); + * + * @method exists + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/ + * @api public + */ + +/** + * Specifies an `$elemMatch` condition + * + * ####Example + * + * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) + * + * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + * + * query.elemMatch('comment', function (elem) { + * elem.where('author').equals('autobot'); + * elem.where('votes').gte(5); + * }) + * + * query.where('comment').elemMatch(function (elem) { + * elem.where({ author: 'autobot' }); + * elem.where('votes').gte(5); + * }) + * + * @method elemMatch + * @memberOf Query + * @param {String|Object|Function} path + * @param {Object|Function} criteria + * @return {Query} this + * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/ + * @api public + */ + +/** + * Defines a `$within` or `$geoWithin` argument for geo-spatial queries. + * + * ####Example + * + * query.where(path).within().box() + * query.where(path).within().circle() + * query.where(path).within().geometry() + * + * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); + * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); + * query.where('loc').within({ polygon: [[],[],[],[]] }); + * + * query.where('loc').within([], [], []) // polygon + * query.where('loc').within([], []) // box + * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry + * + * **MUST** be used after `where()`. + * + * ####NOTE: + * + * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin). + * + * ####NOTE: + * + * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). + * + * @method within + * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ + * @see $box http://docs.mongodb.org/manual/reference/operator/box/ + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see $center http://docs.mongodb.org/manual/reference/operator/center/ + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @memberOf Query + * @return {Query} this + * @api public + */ + +/** + * Specifies a $slice projection for an array. + * + * ####Example + * + * query.slice('comments', 5) + * query.slice('comments', -5) + * query.slice('comments', [10, 5]) + * query.where('comments').slice(5) + * query.where('comments').slice([-10, 5]) + * + * @method slice + * @memberOf Query + * @param {String} [path] + * @param {Number} val number/range of elements to slice + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements + * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice + * @api public + */ + +/** + * Specifies the maximum number of documents the query will return. + * + * ####Example + * + * query.limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method limit + * @memberOf Query + * @param {Number} val + * @api public + */ + +/** + * Specifies the number of documents to skip. + * + * ####Example + * + * query.skip(100).limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method skip + * @memberOf Query + * @param {Number} val + * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/ + * @api public + */ + +/** + * Specifies the maxScan option. + * + * ####Example + * + * query.maxScan(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method maxScan + * @memberOf Query + * @param {Number} val + * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/ + * @api public + */ + +/** + * Specifies the batchSize option. + * + * ####Example + * + * query.batchSize(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method batchSize + * @memberOf Query + * @param {Number} val + * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/ + * @api public + */ + +/** + * Specifies the `comment` option. + * + * ####Example + * + * query.comment('login query') + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method comment + * @memberOf Query + * @param {Number} val + * @see comment http://docs.mongodb.org/manual/reference/operator/comment/ + * @api public + */ + +/** + * Specifies this query as a `snapshot` query. + * + * ####Example + * + * query.snapshot() // true + * query.snapshot(true) + * query.snapshot(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method snapshot + * @memberOf Query + * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/ + * @return {Query} this + * @api public + */ + +/** + * Sets query hints. + * + * ####Example + * + * query.hint({ indexA: 1, indexB: -1}) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method hint + * @memberOf Query + * @param {Object} val a hint object + * @return {Query} this + * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/ + * @api public + */ + +/** + * Specifies which document fields to include or exclude (also known as the query "projection") + * + * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select). + * + * ####Example + * + * // include a and b, exclude other fields + * query.select('a b'); + * + * // exclude c and d, include other fields + * query.select('-c -d'); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * query.select({ a: 1, b: 1 }); + * query.select({ c: 0, d: 0 }); + * + * // force inclusion of field excluded at schema level + * query.select('+path') + * + * ####NOTE: + * + * Cannot be used with `distinct()`. + * + * _v2 had slightly different syntax such as allowing arrays of field names. This support was removed in v3._ + * + * @method select + * @memberOf Query + * @param {Object|String} arg + * @return {Query} this + * @see SchemaType + * @api public + */ + +/** + * _DEPRECATED_ Sets the slaveOk option. + * + * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read). + * + * ####Example: + * + * query.slaveOk() // true + * query.slaveOk(true) + * query.slaveOk(false) + * + * @method slaveOk + * @memberOf Query + * @deprecated use read() preferences instead if on mongodb >= 2.2 + * @param {Boolean} v defaults to true + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/ + * @see read() #query_Query-read + * @return {Query} this + * @api public + */ + +/** + * Determines the MongoDB nodes from which to read. + * + * ####Preferences: + * + * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. + * secondary Read from secondary if available, otherwise error. + * primaryPreferred Read from primary if available, otherwise a secondary. + * secondaryPreferred Read from a secondary if available, otherwise read from the primary. + * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + * + * Aliases + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * ####Example: + * + * new Query().read('primary') + * new Query().read('p') // same as primary + * + * new Query().read('primaryPreferred') + * new Query().read('pp') // same as primaryPreferred + * + * new Query().read('secondary') + * new Query().read('s') // same as secondary + * + * new Query().read('secondaryPreferred') + * new Query().read('sp') // same as secondaryPreferred + * + * new Query().read('nearest') + * new Query().read('n') // same as nearest + * + * // read from secondaries with matching tags + * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) + * + * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + * + * @method read + * @memberOf Query + * @param {String} pref one of the listed preference options or aliases + * @param {Array} [tags] optional tags for this query + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + * @return {Query} this + * @api public + */ + +Query.prototype.read = function read(pref, tags) { + // first cast into a ReadPreference object to support tags + var read = readPref.call(readPref, pref, tags); + return Query.base.read.call(this, read); +}; + +/** + * Merges another Query or conditions object into this one. + * + * When a Query is passed, conditions, field selection and options are merged. + * + * New in 3.7.0 + * + * @method merge + * @memberOf Query + * @param {Query|Object} source + * @return {Query} this + */ + +/** + * Sets query options. + * + * ####Options: + * + * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * + * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * + * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * + * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * + * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan) * + * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * + * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * + * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * + * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * + * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference) ** + * - [lean](./api.html#query_Query-lean) * + * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) + * + * _* denotes a query helper method is also available_ + * _** query helper method to set `readPreference` is `read()`_ + * + * @param {Object} options + * @api public + */ + +Query.prototype.setOptions = function(options, overwrite) { + // overwrite is only for internal use + if (overwrite) { + // ensure that _mongooseOptions & options are two different objects + this._mongooseOptions = (options && utils.clone(options)) || {}; + this.options = options || {}; + + if ('populate' in options) { + this.populate(this._mongooseOptions); + } + return this; + } + + if (!(options && options.constructor.name === 'Object')) { + return this; + } + + return Query.base.setOptions.call(this, options); +}; + +/** + * Returns the current query conditions as a JSON object. + * + * ####Example: + * + * var query = new Query(); + * query.find({ a: 1 }).where('b').gt(2); + * query.getQuery(); // { a: 1, b: { $gt: 2 } } + * + * @return {Object} current query conditions + * @api public + */ + +Query.prototype.getQuery = function() { + return this._conditions; +}; + +/** + * Returns the current update operations as a JSON object. + * + * ####Example: + * + * var query = new Query(); + * query.update({}, { $set: { a: 5 } }); + * query.getUpdate(); // { $set: { a: 5 } } + * + * @return {Object} current update operations + * @api public + */ + +Query.prototype.getUpdate = function() { + return this._update; +}; + +/** + * Returns fields selection for this query. + * + * @method _fieldsForExec + * @return {Object} + * @api private + * @receiver Query + */ + +/** + * Return an update document with corrected $set operations. + * + * @method _updateForExec + * @api private + * @receiver Query + */ + +/** + * Makes sure _path is set. + * + * @method _ensurePath + * @param {String} method + * @api private + * @receiver Query + */ + +/** + * Determines if `conds` can be merged using `mquery().merge()` + * + * @method canMerge + * @memberOf Query + * @param {Object} conds + * @return {Boolean} + * @api private + */ + +/** + * Returns default options for this query. + * + * @param {Model} model + * @api private + */ + +Query.prototype._optionsForExec = function(model) { + var options = Query.base._optionsForExec.call(this); + + delete options.populate; + model = model || this.model; + + if (!model) { + return options; + } + + if (!('safe' in options) && model.schema.options.safe) { + options.safe = model.schema.options.safe; + } + + if (!('readPreference' in options) && model.schema.options.read) { + options.readPreference = model.schema.options.read; + } + + return options; +}; + +/** + * Sets the lean option. + * + * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied. + * + * ####Example: + * + * new Query().lean() // true + * new Query().lean(true) + * new Query().lean(false) + * + * Model.find().lean().exec(function (err, docs) { + * docs[0] instanceof mongoose.Document // false + * }); + * + * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream). + * + * @param {Boolean} bool defaults to true + * @return {Query} this + * @api public + */ + +Query.prototype.lean = function(v) { + this._mongooseOptions.lean = arguments.length ? !!v : true; + return this; +}; + +/** + * Thunk around find() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._find = function(callback) { + if (this._castError) { + callback(this._castError); + return this; + } + + this._applyPaths(); + this._fields = this._castFields(this._fields); + + var fields = this._fieldsForExec(); + var options = this._mongooseOptions; + var _this = this; + + var cb = function(err, docs) { + if (err) { + return callback(err); + } + + if (docs.length === 0) { + return callback(null, docs); + } + + if (!options.populate) { + return options.lean === true + ? callback(null, docs) + : completeMany(_this.model, docs, fields, _this, null, callback); + } + + var pop = helpers.preparePopulationOptionsMQ(_this, options); + pop.__noPromise = true; + _this.model.populate(docs, pop, function(err, docs) { + if (err) return callback(err); + return options.lean === true + ? callback(null, docs) + : completeMany(_this.model, docs, fields, _this, pop, callback); + }); + }; + + return Query.base.find.call(this, {}, cb); +}; + +/** + * Finds documents. + * + * When no `callback` is passed, the query is not executed. When the query is executed, the result will be an array of documents. + * + * ####Example + * + * query.find({ name: 'Los Pollos Hermanos' }).find(callback) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.find = function(conditions, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = {}; + } + + conditions = utils.toObject(conditions); + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + prepareDiscriminatorCriteria(this); + + try { + this.cast(this.model); + this._castError = null; + } catch (err) { + this._castError = err; + } + + // if we don't have a callback, then just return the query object + if (!callback) { + return Query.base.find.call(this); + } + + this._find(callback); + + return this; +}; + +/*! + * hydrates many documents + * + * @param {Model} model + * @param {Array} docs + * @param {Object} fields + * @param {Query} self + * @param {Array} [pop] array of paths used in population + * @param {Function} callback + */ + +function completeMany(model, docs, fields, self, pop, callback) { + var arr = []; + var count = docs.length; + var len = count; + var opts = pop ? + {populated: pop} + : undefined; + function init(err) { + if (err) return callback(err); + --count || callback(null, arr); + } + for (var i = 0; i < len; ++i) { + arr[i] = helpers.createModel(model, docs[i], fields); + arr[i].init(docs[i], opts, init); + } +} + +/** + * Thunk around findOne() + * + * @param {Function} [callback] + * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ + * @api private + */ + +Query.prototype._findOne = function(callback) { + if (this._castError) { + return callback(this._castError); + } + + this._applyPaths(); + this._fields = this._castFields(this._fields); + + var options = this._mongooseOptions; + var projection = this._fieldsForExec(); + var _this = this; + + // don't pass in the conditions because we already merged them in + Query.base.findOne.call(_this, {}, function(err, doc) { + if (err) { + return callback(err); + } + if (!doc) { + return callback(null, null); + } + + if (!options.populate) { + return options.lean === true + ? callback(null, doc) + : completeOne(_this.model, doc, null, projection, _this, null, callback); + } + + var pop = helpers.preparePopulationOptionsMQ(_this, options); + pop.__noPromise = true; + _this.model.populate(doc, pop, function(err, doc) { + if (err) { + return callback(err); + } + + return options.lean === true + ? callback(null, doc) + : completeOne(_this.model, doc, null, projection, _this, pop, callback); + }); + }); +}; + +/** + * Declares the query a findOne operation. When executed, the first found document is passed to the callback. + * + * Passing a `callback` executes the query. The result of the query is a single document. + * + * ####Example + * + * var query = Kitten.where({ color: 'white' }); + * query.findOne(function (err, kitten) { + * if (err) return handleError(err); + * if (kitten) { + * // doc may be null if no document matched + * } + * }); + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Object} [projection] optional fields to return + * @param {Function} [callback] + * @return {Query} this + * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ + * @see Query.select #query_Query-select + * @api public + */ + +Query.prototype.findOne = function(conditions, projection, options, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = null; + projection = null; + options = null; + } else if (typeof projection === 'function') { + callback = projection; + options = null; + projection = null; + } else if (typeof options === 'function') { + callback = options; + options = null; + } + + // make sure we don't send in the whole Document to merge() + conditions = utils.toObject(conditions); + + this.op = 'findOne'; + + if (options) { + this.setOptions(options); + } + + if (projection) { + this.select(projection); + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + prepareDiscriminatorCriteria(this); + + try { + this.cast(this.model); + this._castError = null; + } catch (err) { + this._castError = err; + } + + if (!callback) { + // already merged in the conditions, don't need to send them in. + return Query.base.findOne.call(this); + } + + this._findOne(callback); + + return this; +}; + +/** + * Thunk around count() + * + * @param {Function} [callback] + * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ + * @api private + */ + +Query.prototype._count = function(callback) { + try { + this.cast(this.model); + } catch (err) { + process.nextTick(function() { + callback(err); + }); + return this; + } + + var conds = this._conditions; + var options = this._optionsForExec(); + + this._collection.count(conds, options, utils.tick(callback)); +}; + +/** + * Specifying this query as a `count` query. + * + * Passing a `callback` executes the query. + * + * ####Example: + * + * var countQuery = model.where({ 'color': 'black' }).count(); + * + * query.count({ color: 'black' }).count(callback) + * + * query.count({ color: 'black' }, callback) + * + * query.where('color', 'black').count(function (err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ + * @api public + */ + +Query.prototype.count = function(conditions, callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + this.op = 'count'; + if (!callback) { + return this; + } + + this._count(callback); + + return this; +}; + +/** + * Declares or executes a distict() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * distinct(field, conditions, callback) + * distinct(field, conditions) + * distinct(field, callback) + * distinct(field) + * distinct(callback) + * distinct() + * + * @param {String} [field] + * @param {Object|Query} [criteria] + * @param {Function} [callback] + * @return {Query} this + * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ + * @api public + */ + +Query.prototype.distinct = function(field, conditions, callback) { + if (!callback) { + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + } else if (typeof field === 'function') { + callback = field; + field = undefined; + conditions = undefined; + } + } + + conditions = utils.toObject(conditions); + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + try { + this.cast(this.model); + } catch (err) { + if (!callback) { + throw err; + } + callback(err); + return this; + } + + return Query.base.distinct.call(this, {}, field, callback); +}; + +/** + * Sets the sort order + * + * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + * + * If a string is passed, it must be a space delimited list of path names. The + * sort order of each path is ascending unless the path name is prefixed with `-` + * which will be treated as descending. + * + * ####Example + * + * // sort by "field" ascending and "test" descending + * query.sort({ field: 'asc', test: -1 }); + * + * // equivalent + * query.sort('field -test'); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/ + * @api public + */ + +Query.prototype.sort = function(arg) { + var nArg = {}; + + if (arguments.length > 1) { + throw new Error('sort() only takes 1 Argument'); + } + + if (Array.isArray(arg)) { + // time to deal with the terrible syntax + for (var i = 0; i < arg.length; i++) { + if (!Array.isArray(arg[i])) throw new Error('Invalid sort() argument.'); + nArg[arg[i][0]] = arg[i][1]; + } + } else { + nArg = arg; + } + + // workaround for gh-2374 when sort is called after count + // if previous operation is count, we ignore + if (this.op === 'count') { + delete this.op; + } + return Query.base.sort.call(this, nArg); +}; + +/** + * Declare and/or execute this query as a remove() operation. + * + * ####Example + * + * Model.remove({ artist: 'Anne Murray' }, callback) + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback, you must first call `remove()` and then execute it by using the `exec()` method. + * + * // not executed + * var query = Model.find().remove({ name: 'Anne Murray' }) + * + * // executed + * query.remove({ name: 'Anne Murray' }, callback) + * query.remove({ name: 'Anne Murray' }).remove(callback) + * + * // executed without a callback (unsafe write) + * query.exec() + * + * // summary + * query.remove(conds, fn); // executes + * query.remove(conds) + * query.remove(fn) // executes + * query.remove() + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/ + * @api public + */ + +Query.prototype.remove = function(cond, callback) { + if (typeof cond === 'function') { + callback = cond; + cond = null; + } + + var cb = typeof callback === 'function'; + + try { + this.cast(this.model); + } catch (err) { + if (cb) return process.nextTick(callback.bind(null, err)); + return this; + } + + return Query.base.remove.call(this, cond, callback); +}; + +/*! + * hydrates a document + * + * @param {Model} model + * @param {Document} doc + * @param {Object} res 3rd parameter to callback + * @param {Object} fields + * @param {Query} self + * @param {Array} [pop] array of paths used in population + * @param {Function} callback + */ + +function completeOne(model, doc, res, fields, self, pop, callback) { + var opts = pop ? + {populated: pop} + : undefined; + + var casted = helpers.createModel(model, doc, fields); + casted.init(doc, opts, function(err) { + if (err) { + return callback(err); + } + if (res) { + return callback(null, casted, res); + } + callback(null, casted); + }); +} + +/*! + * If the model is a discriminator type and not root, then add the key & value to the criteria. + */ + +function prepareDiscriminatorCriteria(query) { + if (!query || !query.model || !query.model.schema) { + return; + } + + var schema = query.model.schema; + + if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { + query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; + } +} + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. + * + * ####Available options + * + * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * } + * + * ####Examples + * + * query.findOneAndUpdate(conditions, update, options, callback) // executes + * query.findOneAndUpdate(conditions, update, options) // returns Query + * query.findOneAndUpdate(conditions, update, callback) // executes + * query.findOneAndUpdate(conditions, update) // returns Query + * query.findOneAndUpdate(update, callback) // returns Query + * query.findOneAndUpdate(update) // returns Query + * query.findOneAndUpdate(callback) // executes + * query.findOneAndUpdate() // returns Query + * + * @method findOneAndUpdate + * @memberOf Query + * @param {Object|Query} [query] + * @param {Object} [doc] + * @param {Object} [options] + * @param {Function} [callback] + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @return {Query} this + * @api public + */ + +Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) { + this.op = 'findOneAndUpdate'; + this._validate(); + + switch (arguments.length) { + case 3: + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 2: + if (typeof doc === 'function') { + callback = doc; + doc = criteria; + criteria = undefined; + } + options = undefined; + break; + case 1: + if (typeof criteria === 'function') { + callback = criteria; + criteria = options = doc = undefined; + } else { + doc = criteria; + criteria = options = undefined; + } + } + + if (mquery.canMerge(criteria)) { + this.merge(criteria); + } + + // apply doc + if (doc) { + this._mergeUpdate(doc); + } + + options && this.setOptions(options); + + if (!callback) { + return this; + } + + return this._findOneAndUpdate(callback); +}; + +/** + * Thunk around findOneAndUpdate() + * + * @param {Function} [callback] + * @api private + */ + +Query.prototype._findOneAndUpdate = function(callback) { + this._findAndModify('update', callback); + return this; +}; + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * - `passRawResult`: if true, passes the [raw result from the MongoDB driver as the third callback parameter](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * + * ####Callback Signature + * function(error, doc, result) { + * // error: any errors that occurred + * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` + * // result: [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) + * } + * + * ####Examples + * + * A.where().findOneAndRemove(conditions, options, callback) // executes + * A.where().findOneAndRemove(conditions, options) // return Query + * A.where().findOneAndRemove(conditions, callback) // executes + * A.where().findOneAndRemove(conditions) // returns Query + * A.where().findOneAndRemove(callback) // executes + * A.where().findOneAndRemove() // returns Query + * + * @method findOneAndRemove + * @memberOf Query + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Query.prototype.findOneAndRemove = function(conditions, options, callback) { + this.op = 'findOneAndRemove'; + this._validate(); + + switch (arguments.length) { + case 2: + if (typeof options === 'function') { + callback = options; + options = {}; + } + break; + case 1: + if (typeof conditions === 'function') { + callback = conditions; + conditions = undefined; + options = undefined; + } + break; + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + options && this.setOptions(options); + + if (!callback) { + return this; + } + + this._findOneAndRemove(callback); + + return this; +}; + +/** + * Thunk around findOneAndRemove() + * + * @param {Function} [callback] + * @return {Query} this + * @api private + */ +Query.prototype._findOneAndRemove = function(callback) { + Query.base.findOneAndRemove.call(this, callback); +}; + +/** + * Override mquery.prototype._findAndModify to provide casting etc. + * + * @param {String} type - either "remove" or "update" + * @param {Function} callback + * @api private + */ + +Query.prototype._findAndModify = function(type, callback) { + if (typeof callback !== 'function') { + throw new Error('Expected callback in _findAndModify'); + } + + var model = this.model; + var schema = model.schema; + var _this = this; + var castedQuery; + var castedDoc; + var fields; + var opts; + var doValidate; + + castedQuery = castQuery(this); + if (castedQuery instanceof Error) { + return callback(castedQuery); + } + + opts = this._optionsForExec(model); + + if ('strict' in opts) { + this._mongooseOptions.strict = opts.strict; + } + + if (type === 'remove') { + opts.remove = true; + } else { + if (!('new' in opts)) { + opts.new = false; + } + if (!('upsert' in opts)) { + opts.upsert = false; + } + if (opts.upsert || opts['new']) { + opts.remove = false; + } + + castedDoc = castDoc(this, opts.overwrite); + if (!castedDoc) { + if (opts.upsert) { + // still need to do the upsert to empty doc + var doc = utils.clone(castedQuery); + delete doc._id; + castedDoc = {$set: doc}; + } else { + return this.findOne(callback); + } + } else if (castedDoc instanceof Error) { + return callback(castedDoc); + } else { + // In order to make MongoDB 2.6 happy (see + // https://jira.mongodb.org/browse/SERVER-12266 and related issues) + // if we have an actual update document but $set is empty, junk the $set. + if (castedDoc.$set && Object.keys(castedDoc.$set).length === 0) { + delete castedDoc.$set; + } + } + + doValidate = updateValidators(this, schema, castedDoc, opts); + } + + this._applyPaths(); + + var options = this._mongooseOptions; + + if (this._fields) { + fields = utils.clone(this._fields); + opts.fields = this._castFields(fields); + if (opts.fields instanceof Error) { + return callback(opts.fields); + } + } + + if (opts.sort) convertSortToArray(opts); + + var cb = function(err, doc, res) { + if (err) { + return callback(err); + } + + if (!doc || (utils.isObject(doc) && Object.keys(doc).length === 0)) { + return callback(null, null); + } + + if (!opts.passRawResult) { + res = null; + } + + if (!options.populate) { + return options.lean === true + ? callback(null, doc) + : completeOne(_this.model, doc, res, fields, _this, null, callback); + } + + var pop = helpers.preparePopulationOptionsMQ(_this, options); + pop.__noPromise = true; + _this.model.populate(doc, pop, function(err, doc) { + if (err) { + return callback(err); + } + + return options.lean === true + ? callback(null, doc) + : completeOne(_this.model, doc, res, fields, _this, pop, callback); + }); + }; + + if ((opts.runValidators || opts.setDefaultsOnInsert) && doValidate) { + doValidate(function(error) { + if (error) { + return callback(error); + } + _this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function(error, res) { + return cb(error, res ? res.value : res, res); + })); + }); + } else { + this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(function(error, res) { + return cb(error, res ? res.value : res, res); + })); + } + + return this; +}; + +/** + * Override mquery.prototype._mergeUpdate to handle mongoose objects in + * updates. + * + * @param {Object} doc + * @api private + */ + +Query.prototype._mergeUpdate = function(doc) { + if (!this._update) this._update = {}; + if (doc instanceof Query) { + if (doc._update) { + utils.mergeClone(this._update, doc._update); + } + } else { + utils.mergeClone(this._update, doc); + } +}; + +/*! + * The mongodb driver 1.3.23 only supports the nested array sort + * syntax. We must convert it or sorting findAndModify will not work. + */ + +function convertSortToArray(opts) { + if (Array.isArray(opts.sort)) { + return; + } + if (!utils.isObject(opts.sort)) { + return; + } + + var sort = []; + + for (var key in opts.sort) { + if (utils.object.hasOwnProperty(opts.sort, key)) { + sort.push([key, opts.sort[key]]); + } + } + + opts.sort = sort; +} + +/** + * Internal thunk for .update() + * + * @param {Function} callback + * @see Model.update #model_Model.update + * @api private + */ +Query.prototype._execUpdate = function(callback) { + var schema = this.model.schema; + var doValidate; + var _this; + + var castedQuery = this._conditions; + var castedDoc = this._update; + var options = this.options; + + if (this._castError) { + callback(this._castError); + return this; + } + + if (this.options.runValidators || this.options.setDefaultsOnInsert) { + _this = this; + doValidate = updateValidators(this, schema, castedDoc, options); + doValidate(function(err) { + if (err) { + return callback(err); + } + + Query.base.update.call(_this, castedQuery, castedDoc, options, callback); + }); + return this; + } + + Query.base.update.call(this, castedQuery, castedDoc, options, callback); + return this; +}; + +/** + * Declare and/or execute this query as an update() operation. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * Model.where({ _id: id }).update({ title: 'words' }) + * + * // becomes + * + * Model.where({ _id: id }).update({ $set: { title: 'words' }}) + * + * ####Note + * + * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. + * + * var q = Model.where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).update(); // not executed + * + * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe + * + * // keys that are not $atomic ops become $set. + * // this executes the same command as the previous example. + * q.update({ name: 'bob' }).exec(); + * + * // overwriting with empty docs + * var q = Model.where({ _id: id }).setOptions({ overwrite: true }) + * q.update({ }, callback); // executes + * + * // multi update with overwrite to empty doc + * var q = Model.where({ _id: id }); + * q.setOptions({ multi: true, overwrite: true }) + * q.update({ }); + * q.update(callback); // executed + * + * // multi updates + * Model.where() + * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) + * + * // more multi updates + * Model.where() + * .setOptions({ multi: true }) + * .update({ $set: { arr: [] }}, callback) + * + * // single update by default + * Model.where({ email: 'address@example.com' }) + * .update({ $inc: { counter: 1 }}, callback) + * + * API summary + * + * update(criteria, doc, options, cb) // executes + * update(criteria, doc, options) + * update(criteria, doc, cb) // executes + * update(criteria, doc) + * update(doc, cb) // executes + * update(doc) + * update(cb) // executes + * update(true) // executes (unsafe write) + * update() + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @see Model.update #model_Model.update + * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ + * @api public + */ + +Query.prototype.update = function(conditions, doc, options, callback) { + if (typeof options === 'function') { + // .update(conditions, doc, callback) + callback = options; + options = null; + } else if (typeof doc === 'function') { + // .update(doc, callback); + callback = doc; + doc = conditions; + conditions = {}; + options = null; + } else if (typeof conditions === 'function') { + // .update(callback) + callback = conditions; + conditions = undefined; + doc = undefined; + options = undefined; + } else if (typeof conditions === 'object' && !doc && !options && !callback) { + // .update(doc) + doc = conditions; + conditions = undefined; + options = undefined; + callback = undefined; + } + + // make sure we don't send in the whole Document to merge() + conditions = utils.toObject(conditions); + + var oldCb = callback; + if (oldCb) { + if (typeof oldCb === 'function') { + callback = function(error, result) { + oldCb(error, result ? result.result : {ok: 0, n: 0, nModified: 0}); + }; + } else { + throw new Error('Invalid callback() argument.'); + } + } + + // strict is an option used in the update checking, make sure it gets set + if (options) { + if ('strict' in options) { + this._mongooseOptions.strict = options.strict; + } + } + + // if doc is undefined at this point, this means this function is being + // executed by exec(not always see below). Grab the update doc from here in + // order to validate + // This could also be somebody calling update() or update({}). Probably not a + // common use case, check for _update to make sure we don't do anything bad + if (!doc && this._update) { + doc = this._updateForExec(); + } + + if (mquery.canMerge(conditions)) { + this.merge(conditions); + } + + // validate the selector part of the query + var castedQuery = castQuery(this); + if (castedQuery instanceof Error) { + this._castError = castedQuery; + if (callback) { + callback(castedQuery); + return this; + } else if (!options || !options.dontThrowCastError) { + throw castedQuery; + } + } + + // validate the update part of the query + var castedDoc; + try { + var $options = {retainKeyOrder: true}; + if (options && options.minimize) { + $options.minimize = true; + } + castedDoc = this._castUpdate(utils.clone(doc, $options), + options && options.overwrite); + } catch (err) { + this._castError = castedQuery; + if (callback) { + callback(err); + return this; + } else if (!options || !options.dontThrowCastError) { + throw err; + } + } + + if (!castedDoc) { + // Make sure promises know that this is still an update, see gh-2796 + this.op = 'update'; + callback && callback(null); + return this; + } + + if (utils.isObject(options)) { + this.setOptions(options); + } + + if (!this._update) this._update = castedDoc; + + // Hooks + if (callback) { + return this._execUpdate(callback); + } + + return Query.base.update.call(this, castedQuery, castedDoc, options, callback); +}; + +/** + * Executes the query + * + * ####Examples: + * + * var promise = query.exec(); + * var promise = query.exec('update'); + * + * query.exec(callback); + * query.exec('find', callback); + * + * @param {String|Function} [operation] + * @param {Function} [callback] + * @return {Promise} + * @api public + */ + +Query.prototype.exec = function exec(op, callback) { + var Promise = PromiseProvider.get(); + var _this = this; + + if (typeof op === 'function') { + callback = op; + op = null; + } else if (typeof op === 'string') { + this.op = op; + } + + return new Promise.ES6(function(resolve, reject) { + if (!_this.op) { + callback && callback(null, undefined); + resolve(); + return; + } + + _this[_this.op].call(_this, function(error, res) { + if (error) { + callback && callback(error); + reject(error); + return; + } + callback && callback.apply(null, arguments); + resolve(res); + }); + }); +}; + +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @return {Promise} + * @api public + */ + +Query.prototype.then = function(resolve, reject) { + return this.exec().then(resolve, reject); +}; + +/** + * Finds the schema for `path`. This is different than + * calling `schema.path` as it also resolves paths with + * positional selectors (something.$.another.$.path). + * + * @param {String} path + * @api private + */ + +Query.prototype._getSchema = function _getSchema(path) { + return this.model._getSchema(path); +}; + +/*! + * These operators require casting docs + * to real Documents for Update operations. + */ + +var castOps = { + $push: 1, + $pushAll: 1, + $addToSet: 1, + $set: 1 +}; + +/*! + * These operators should be cast to numbers instead + * of their path schema type. + */ + +var numberOps = { + $pop: 1, + $unset: 1, + $inc: 1 +}; + +/** + * Casts obj for an update command. + * + * @param {Object} obj + * @return {Object} obj after casting its values + * @api private + */ + +Query.prototype._castUpdate = function _castUpdate(obj, overwrite) { + if (!obj) { + return undefined; + } + + var ops = Object.keys(obj); + var i = ops.length; + var ret = {}; + var hasKeys; + var val; + var hasDollarKey = false; + + while (i--) { + var op = ops[i]; + // if overwrite is set, don't do any of the special $set stuff + if (op[0] !== '$' && !overwrite) { + // fix up $set sugar + if (!ret.$set) { + if (obj.$set) { + ret.$set = obj.$set; + } else { + ret.$set = {}; + } + } + ret.$set[op] = obj[op]; + ops.splice(i, 1); + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if (op === '$set') { + if (!ret.$set) { + ret[op] = obj[op]; + } + } else { + ret[op] = obj[op]; + } + } + + // cast each value + i = ops.length; + + // if we get passed {} for the update, we still need to respect that when it + // is an overwrite scenario + if (overwrite) { + hasKeys = true; + } + + while (i--) { + op = ops[i]; + val = ret[op]; + hasDollarKey = hasDollarKey || op.charAt(0) === '$'; + if (val && + val.constructor.name === 'Object' && + (!overwrite || hasDollarKey)) { + hasKeys |= this._walkUpdatePath(val, op); + } else if (overwrite && ret.constructor.name === 'Object') { + // if we are just using overwrite, cast the query and then we will + // *always* return the value, even if it is an empty object. We need to + // set hasKeys above because we need to account for the case where the + // user passes {} and wants to clobber the whole document + // Also, _walkUpdatePath expects an operation, so give it $set since that + // is basically what we're doing + this._walkUpdatePath(ret, '$set'); + } else { + var msg = 'Invalid atomic update value for ' + op + '. ' + + 'Expected an object, received ' + typeof val; + throw new Error(msg); + } + } + + return hasKeys && ret; +}; + +/** + * Walk each path of obj and cast its values + * according to its schema. + * + * @param {Object} obj - part of a query + * @param {String} op - the atomic operator ($pull, $set, etc) + * @param {String} pref - path prefix (internal only) + * @return {Bool} true if this path has keys to update + * @api private + */ + +Query.prototype._walkUpdatePath = function _walkUpdatePath(obj, op, pref) { + var prefix = pref ? pref + '.' : '', + keys = Object.keys(obj), + i = keys.length, + hasKeys = false, + schema, + key, + val; + + var strict = 'strict' in this._mongooseOptions + ? this._mongooseOptions.strict + : this.model.schema.options.strict; + + while (i--) { + key = keys[i]; + val = obj[key]; + + if (val && val.constructor.name === 'Object') { + // watch for embedded doc schemas + schema = this._getSchema(prefix + key); + if (schema && schema.caster && op in castOps) { + // embedded doc schema + hasKeys = true; + + if ('$each' in val) { + obj[key] = { + $each: this._castUpdateVal(schema, val.$each, op) + }; + + if (val.$slice != null) { + obj[key].$slice = val.$slice | 0; + } + + if (val.$sort) { + obj[key].$sort = val.$sort; + } + + if (!!val.$position || val.$position === 0) { + obj[key].$position = val.$position; + } + } else { + obj[key] = this._castUpdateVal(schema, val, op); + } + } else if (op === '$currentDate') { + // $currentDate can take an object + obj[key] = this._castUpdateVal(schema, val, op); + hasKeys = true; + } else if (op === '$set' && schema) { + obj[key] = this._castUpdateVal(schema, val, op); + hasKeys = true; + } else { + var pathToCheck = (prefix + key); + var v = this.model.schema._getPathType(pathToCheck); + if (v === 'undefined') { + if (strict === 'throw') { + throw new StrictModeError(pathToCheck); + } else if (strict) { + delete obj[key]; + continue; + } + } + + // gh-2314 + // we should be able to set a schema-less field + // to an empty object literal + hasKeys |= this._walkUpdatePath(val, op, prefix + key) || + (utils.isObject(val) && Object.keys(val).length === 0); + } + } else { + schema = (key === '$each' || key === '$or' || key === '$and') + ? this._getSchema(pref) + : this._getSchema(prefix + key); + + var skip = strict && + !schema && + !/real|nested/.test(this.model.schema.pathType(prefix + key)); + + if (skip) { + if (strict === 'throw') { + throw new StrictModeError(prefix + key); + } else { + delete obj[key]; + } + } else { + // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking + // improving this. + if (op === '$rename') { + hasKeys = true; + return; + } + + hasKeys = true; + obj[key] = this._castUpdateVal(schema, val, op, key); + } + } + } + return hasKeys; +}; + +/** + * Casts `val` according to `schema` and atomic `op`. + * + * @param {Schema} schema + * @param {Object} val + * @param {String} op - the atomic operator ($pull, $set, etc) + * @param {String} [$conditional] + * @api private + */ + +Query.prototype._castUpdateVal = function _castUpdateVal(schema, val, op, $conditional) { + if (!schema) { + // non-existing schema path + return op in numberOps + ? Number(val) + : val; + } + + var cond = schema.caster && op in castOps && + (utils.isObject(val) || Array.isArray(val)); + if (cond) { + // Cast values for ops that add data to MongoDB. + // Ensures embedded documents get ObjectIds etc. + var tmp = schema.cast(val); + if (Array.isArray(val)) { + val = tmp; + } else if (schema.caster.$isSingleNested) { + val = tmp; + } else { + val = tmp[0]; + } + } + + if (op in numberOps) { + return Number(val); + } + if (op === '$currentDate') { + if (typeof val === 'object') { + return {$type: val.$type}; + } + return Boolean(val); + } + if (/^\$/.test($conditional)) { + return schema.castForQuery($conditional, val); + } + + return schema.castForQuery(val); +}; + +/*! + * castQuery + * @api private + */ + +function castQuery(query) { + try { + return query.cast(query.model); + } catch (err) { + return err; + } +} + +/*! + * castDoc + * @api private + */ + +function castDoc(query, overwrite) { + try { + return query._castUpdate(query._update, overwrite); + } catch (err) { + return err; + } +} + +/** + * Specifies paths which should be populated with other documents. + * + * ####Example: + * + * Kitten.findOne().populate('owner').exec(function (err, kitten) { + * console.log(kitten.owner.name) // Max + * }) + * + * Kitten.find().populate({ + * path: 'owner' + * , select: 'name' + * , match: { color: 'black' } + * , options: { sort: { name: -1 }} + * }).exec(function (err, kittens) { + * console.log(kittens[0].owner.name) // Zoopa + * }) + * + * // alternatively + * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) { + * console.log(kittens[0].owner.name) // Zoopa + * }) + * + * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback. + * + * @param {Object|String} path either the path to populate or an object specifying all parameters + * @param {Object|String} [select] Field selection for the population query + * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field. + * @param {Object} [match] Conditions for the population query + * @param {Object} [options] Options for the population query (sort, etc) + * @see population ./populate.html + * @see Query#select #query_Query-select + * @see Model.populate #model_Model.populate + * @return {Query} this + * @api public + */ + +Query.prototype.populate = function() { + var res = utils.populate.apply(null, arguments); + var opts = this._mongooseOptions; + + if (!utils.isObject(opts.populate)) { + opts.populate = {}; + } + + for (var i = 0; i < res.length; ++i) { + opts.populate[res[i].path] = res[i]; + } + + return this; +}; + +/** + * Casts this query to the schema of `model` + * + * ####Note + * + * If `obj` is present, it is cast instead of this query. + * + * @param {Model} model + * @param {Object} [obj] + * @return {Object} + * @api public + */ + +Query.prototype.cast = function(model, obj) { + obj || (obj = this._conditions); + + return cast(model.schema, obj); +}; + +/** + * Casts selected field arguments for field selection with mongo 2.2 + * + * query.select({ ids: { $elemMatch: { $in: [hexString] }}) + * + * @param {Object} fields + * @see https://github.com/Automattic/mongoose/issues/1091 + * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ + * @api private + */ + +Query.prototype._castFields = function _castFields(fields) { + var selected, + elemMatchKeys, + keys, + key, + out, + i; + + if (fields) { + keys = Object.keys(fields); + elemMatchKeys = []; + i = keys.length; + + // collect $elemMatch args + while (i--) { + key = keys[i]; + if (fields[key].$elemMatch) { + selected || (selected = {}); + selected[key] = fields[key]; + elemMatchKeys.push(key); + } + } + } + + if (selected) { + // they passed $elemMatch, cast em + try { + out = this.cast(this.model, selected); + } catch (err) { + return err; + } + + // apply the casted field args + i = elemMatchKeys.length; + while (i--) { + key = elemMatchKeys[i]; + fields[key] = out[key]; + } + } + + return fields; +}; + +/** + * Applies schematype selected options to this query. + * @api private + */ + +Query.prototype._applyPaths = function applyPaths() { + // determine if query is selecting or excluding fields + + var fields = this._fields, + exclude, + keys, + ki; + + if (fields) { + keys = Object.keys(fields); + ki = keys.length; + + while (ki--) { + if (keys[ki][0] === '+') continue; + exclude = fields[keys[ki]] === 0; + break; + } + } + + // if selecting, apply default schematype select:true fields + // if excluding, apply schematype select:false fields + + var selected = [], + excluded = [], + seen = []; + + var analyzePath = function(path, type) { + if (typeof type.selected !== 'boolean') return; + + var plusPath = '+' + path; + if (fields && plusPath in fields) { + // forced inclusion + delete fields[plusPath]; + + // if there are other fields being included, add this one + // if no other included fields, leave this out (implied inclusion) + if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) { + fields[path] = 1; + } + + return; + } + + // check for parent exclusions + var root = path.split('.')[0]; + if (~excluded.indexOf(root)) return; + + (type.selected ? selected : excluded).push(path); + }; + + var analyzeSchema = function(schema, prefix) { + prefix || (prefix = ''); + + // avoid recursion + if (~seen.indexOf(schema)) return; + seen.push(schema); + + schema.eachPath(function(path, type) { + if (prefix) path = prefix + '.' + path; + + analyzePath(path, type); + + // array of subdocs? + if (type.schema) { + analyzeSchema(type.schema, path); + } + }); + }; + + analyzeSchema(this.model.schema); + + switch (exclude) { + case true: + excluded.length && this.select('-' + excluded.join(' -')); + break; + case false: + if (this.model.schema && this.model.schema.paths['_id'] && + this.model.schema.paths['_id'].options && this.model.schema.paths['_id'].options.select === false) { + selected.push('-_id'); + } + selected.length && this.select(selected.join(' ')); + break; + case undefined: + // user didn't specify fields, implies returning all fields. + // only need to apply excluded fields + excluded.length && this.select('-' + excluded.join(' -')); + break; + } + seen = excluded = selected = keys = fields = null; +}; + +/** + * Returns a Node.js 0.8 style [read stream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface. + * + * ####Example + * + * // follows the nodejs 0.8 stream api + * Thing.find({ name: /^hello/ }).stream().pipe(res) + * + * // manual streaming + * var stream = Thing.find({ name: /^hello/ }).stream(); + * + * stream.on('data', function (doc) { + * // do something with the mongoose document + * }).on('error', function (err) { + * // handle the error + * }).on('close', function () { + * // the stream is closed + * }); + * + * ####Valid options + * + * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`. + * + * ####Example + * + * // JSON.stringify all documents before emitting + * var stream = Thing.find().stream({ transform: JSON.stringify }); + * stream.pipe(writeStream); + * + * @return {QueryStream} + * @param {Object} [options] + * @see QueryStream + * @api public + */ + +Query.prototype.stream = function stream(opts) { + this._applyPaths(); + this._fields = this._castFields(this._fields); + return new QueryStream(this, opts); +}; + +// the rest of these are basically to support older Mongoose syntax with mquery + +/** + * _DEPRECATED_ Alias of `maxScan` + * + * @deprecated + * @see maxScan #query_Query-maxScan + * @method maxscan + * @memberOf Query + */ + +Query.prototype.maxscan = Query.base.maxScan; + +/** + * Sets the tailable option (for use with capped collections). + * + * ####Example + * + * query.tailable() // true + * query.tailable(true) + * query.tailable(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Boolean} bool defaults to true + * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/ + * @api public + */ + +Query.prototype.tailable = function(val, opts) { + // we need to support the tailable({ awaitdata : true }) as well as the + // tailable(true, {awaitdata :true}) syntax that mquery does not support + if (val && val.constructor.name === 'Object') { + opts = val; + val = true; + } + + if (val === undefined) { + val = true; + } + + if (opts && typeof opts === 'object') { + for (var key in opts) { + if (key === 'awaitdata') { + // For backwards compatibility + this.options[key] = !!opts[key]; + } else { + this.options[key] = opts[key]; + } + } + } + + return Query.base.tailable.call(this, val); +}; + +/** + * Declares an intersects query for `geometry()`. + * + * ####Example + * + * query.where('path').intersects().geometry({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * query.where('path').intersects({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * ####NOTE: + * + * **MUST** be used after `where()`. + * + * ####NOTE: + * + * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). + * + * @method intersects + * @memberOf Query + * @param {Object} [arg] + * @return {Query} this + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/ + * @api public + */ + +/** + * Specifies a `$geometry` condition + * + * ####Example + * + * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] + * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + * + * // or + * var polyB = [[ 0, 0 ], [ 1, 1 ]] + * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + * + * // or + * var polyC = [ 0, 0 ] + * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + * + * // or + * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + * + * The argument is assigned to the most recent path passed to `where()`. + * + * ####NOTE: + * + * `geometry()` **must** come after either `intersects()` or `within()`. + * + * The `object` argument must contain `type` and `coordinates` properties. + * - type {String} + * - coordinates {Array} + * + * @method geometry + * @memberOf Query + * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. + * @return {Query} this + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/** + * Specifies a `$near` or `$nearSphere` condition + * + * These operators return documents sorted by distance. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10] }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); + * query.near('loc', { center: [10, 10], maxDistance: 5 }); + * + * @method near + * @memberOf Query + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see $near http://docs.mongodb.org/manual/reference/operator/near/ + * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/*! + * Overwriting mquery is needed to support a couple different near() forms found in older + * versions of mongoose + * near([1,1]) + * near(1,1) + * near(field, [1,2]) + * near(field, 1, 2) + * In addition to all of the normal forms supported by mquery + */ + +Query.prototype.near = function() { + var params = []; + var sphere = this._mongooseOptions.nearSphere; + + // TODO refactor + + if (arguments.length === 1) { + if (Array.isArray(arguments[0])) { + params.push({center: arguments[0], spherical: sphere}); + } else if (typeof arguments[0] === 'string') { + // just passing a path + params.push(arguments[0]); + } else if (utils.isObject(arguments[0])) { + if (typeof arguments[0].spherical !== 'boolean') { + arguments[0].spherical = sphere; + } + params.push(arguments[0]); + } else { + throw new TypeError('invalid argument'); + } + } else if (arguments.length === 2) { + if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') { + params.push({center: [arguments[0], arguments[1]], spherical: sphere}); + } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) { + params.push(arguments[0]); + params.push({center: arguments[1], spherical: sphere}); + } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) { + params.push(arguments[0]); + if (typeof arguments[1].spherical !== 'boolean') { + arguments[1].spherical = sphere; + } + params.push(arguments[1]); + } else { + throw new TypeError('invalid argument'); + } + } else if (arguments.length === 3) { + if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number' + && typeof arguments[2] === 'number') { + params.push(arguments[0]); + params.push({center: [arguments[1], arguments[2]], spherical: sphere}); + } else { + throw new TypeError('invalid argument'); + } + } else { + throw new TypeError('invalid argument'); + } + + return Query.base.near.apply(this, params); +}; + +/** + * _DEPRECATED_ Specifies a `$nearSphere` condition + * + * ####Example + * + * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); + * + * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10], spherical: true }); + * + * @deprecated + * @see near() #query_Query-near + * @see $near http://docs.mongodb.org/manual/reference/operator/near/ + * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ + * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ + */ + +Query.prototype.nearSphere = function() { + this._mongooseOptions.nearSphere = true; + this.near.apply(this, arguments); + return this; +}; + +/** + * Specifies a $polygon condition + * + * ####Example + * + * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) + * query.polygon('loc', [10,20], [13, 25], [7,15]) + * + * @method polygon + * @memberOf Query + * @param {String|Array} [path] + * @param {Array|Object} [coordinatePairs...] + * @return {Query} this + * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/** + * Specifies a $box condition + * + * ####Example + * + * var lowerLeft = [40.73083, -73.99756] + * var upperRight= [40.741404, -73.988135] + * + * query.where('loc').within().box(lowerLeft, upperRight) + * query.box({ ll : lowerLeft, ur : upperRight }) + * + * @method box + * @memberOf Query + * @see $box http://docs.mongodb.org/manual/reference/operator/box/ + * @see within() Query#within #query_Query-within + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @param {Object} val + * @param [Array] Upper Right Coords + * @return {Query} this + * @api public + */ + +/*! + * this is needed to support the mongoose syntax of: + * box(field, { ll : [x,y], ur : [x2,y2] }) + * box({ ll : [x,y], ur : [x2,y2] }) + */ + +Query.prototype.box = function(ll, ur) { + if (!Array.isArray(ll) && utils.isObject(ll)) { + ur = ll.ur; + ll = ll.ll; + } + return Query.base.box.call(this, ll, ur); +}; + +/** + * Specifies a $center or $centerSphere condition. + * + * ####Example + * + * var area = { center: [50, 50], radius: 10, unique: true } + * query.where('loc').within().circle(area) + * // alternatively + * query.circle('loc', area); + * + * // spherical calculations + * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } + * query.where('loc').within().circle(area) + * // alternatively + * query.circle('loc', area); + * + * New in 3.7.0 + * + * @method circle + * @memberOf Query + * @param {String} [path] + * @param {Object} area + * @return {Query} this + * @see $center http://docs.mongodb.org/manual/reference/operator/center/ + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/within/ + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +/** + * _DEPRECATED_ Alias for [circle](#query_Query-circle) + * + * **Deprecated.** Use [circle](#query_Query-circle) instead. + * + * @deprecated + * @method center + * @memberOf Query + * @api public + */ + +Query.prototype.center = Query.base.circle; + +/** + * _DEPRECATED_ Specifies a $centerSphere condition + * + * **Deprecated.** Use [circle](#query_Query-circle) instead. + * + * ####Example + * + * var area = { center: [50, 50], radius: 10 }; + * query.where('loc').within().centerSphere(area); + * + * @deprecated + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ + * @api public + */ + +Query.prototype.centerSphere = function() { + if (arguments[0] && arguments[0].constructor.name === 'Object') { + arguments[0].spherical = true; + } + + if (arguments[1] && arguments[1].constructor.name === 'Object') { + arguments[1].spherical = true; + } + + Query.base.circle.apply(this, arguments); +}; + +/** + * Determines if field selection has been made. + * + * @method selected + * @memberOf Query + * @return {Boolean} + * @api public + */ + +/** + * Executes this query and returns a promise + * + * @method then + * @memberOf Query + * @return {Promise} + * @api public + */ + +/** + * Determines if inclusive field selection has been made. + * + * query.selectedInclusively() // false + * query.select('name') + * query.selectedInclusively() // true + * + * @method selectedInclusively + * @memberOf Query + * @return {Boolean} + * @api public + */ + +/** + * Determines if exclusive field selection has been made. + * + * query.selectedExclusively() // false + * query.select('-name') + * query.selectedExclusively() // true + * query.selectedInclusively() // false + * + * @method selectedExclusively + * @memberOf Query + * @return {Boolean} + * @api public + */ + +/*! + * Export + */ + +module.exports = Query; diff --git a/5-3/node_modules/mongoose/lib/queryhelpers.js b/5-3/node_modules/mongoose/lib/queryhelpers.js new file mode 100644 index 0000000..3e0b82d --- /dev/null +++ b/5-3/node_modules/mongoose/lib/queryhelpers.js @@ -0,0 +1,78 @@ + +/*! + * Module dependencies + */ + +var utils = require('./utils'); + +/*! + * Prepare a set of path options for query population. + * + * @param {Query} query + * @param {Object} options + * @return {Array} + */ + +exports.preparePopulationOptions = function preparePopulationOptions(query, options) { + var pop = utils.object.vals(query.options.populate); + + // lean options should trickle through all queries + if (options.lean) pop.forEach(makeLean); + + return pop; +}; + +/*! + * Prepare a set of path options for query population. This is the MongooseQuery + * version + * + * @param {Query} query + * @param {Object} options + * @return {Array} + */ + +exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) { + var pop = utils.object.vals(query._mongooseOptions.populate); + + // lean options should trickle through all queries + if (options.lean) pop.forEach(makeLean); + + return pop; +}; + +/*! + * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise, + * it returns an instance of the given model. + * + * @param {Model} model + * @param {Object} doc + * @param {Object} fields + * + * @return {Model} + */ +exports.createModel = function createModel(model, doc, fields) { + var discriminatorMapping = model.schema + ? model.schema.discriminatorMapping + : null; + + var key = discriminatorMapping && discriminatorMapping.isRoot + ? discriminatorMapping.key + : null; + + if (key && doc[key] && model.discriminators && model.discriminators[doc[key]]) { + return new model.discriminators[doc[key]](undefined, fields, true); + } + + return new model(undefined, fields, true); +}; + +/*! + * Set each path query option to lean + * + * @param {Object} option + */ + +function makeLean(option) { + option.options || (option.options = {}); + option.options.lean = true; +} diff --git a/5-3/node_modules/mongoose/lib/querystream.js b/5-3/node_modules/mongoose/lib/querystream.js new file mode 100644 index 0000000..25bcb9e --- /dev/null +++ b/5-3/node_modules/mongoose/lib/querystream.js @@ -0,0 +1,367 @@ +/* eslint no-empty: 1 */ + +/*! + * Module dependencies. + */ + +var Stream = require('stream').Stream; +var utils = require('./utils'); +var helpers = require('./queryhelpers'); +var K = function(k) { + return k; +}; + +/** + * Provides a Node.js 0.8 style [ReadStream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface for Queries. + * + * var stream = Model.find().stream(); + * + * stream.on('data', function (doc) { + * // do something with the mongoose document + * }).on('error', function (err) { + * // handle the error + * }).on('close', function () { + * // the stream is closed + * }); + * + * + * The stream interface allows us to simply "plug-in" to other _Node.js 0.8_ style write streams. + * + * Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream); + * + * ####Valid options + * + * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`. + * + * ####Example + * + * // JSON.stringify all documents before emitting + * var stream = Thing.find().stream({ transform: JSON.stringify }); + * stream.pipe(writeStream); + * + * _NOTE: plugging into an HTTP response will *not* work out of the box. Those streams expect only strings or buffers to be emitted, so first formatting our documents as strings/buffers is necessary._ + * + * _NOTE: these streams are Node.js 0.8 style read streams which differ from Node.js 0.10 style. Node.js 0.10 streams are not well tested yet and are not guaranteed to work._ + * + * @param {Query} query + * @param {Object} [options] + * @inherits NodeJS Stream http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream + * @event `data`: emits a single Mongoose document + * @event `error`: emits when an error occurs during streaming. This will emit _before_ the `close` event. + * @event `close`: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually `destroy`ed. After this event, no more events are emitted. + * @api public + */ + +function QueryStream(query, options) { + Stream.call(this); + + this.query = query; + this.readable = true; + this.paused = false; + this._cursor = null; + this._destroyed = null; + this._fields = null; + this._buffer = null; + this._inline = T_INIT; + this._running = false; + this._transform = options && typeof options.transform === 'function' + ? options.transform + : K; + + // give time to hook up events + var _this = this; + process.nextTick(function() { + _this._init(); + }); +} + +/*! + * Inherit from Stream + */ + +QueryStream.prototype.__proto__ = Stream.prototype; + +/** + * Flag stating whether or not this stream is readable. + * + * @property readable + * @api public + */ + +QueryStream.prototype.readable; + +/** + * Flag stating whether or not this stream is paused. + * + * @property paused + * @api public + */ + +QueryStream.prototype.paused; + +// trampoline flags +var T_INIT = 0; +var T_IDLE = 1; +var T_CONT = 2; + +/** + * Initializes the query. + * + * @api private + */ + +QueryStream.prototype._init = function() { + if (this._destroyed) { + return; + } + + var query = this.query, + model = query.model, + options = query._optionsForExec(model), + _this = this; + + try { + query.cast(model); + } catch (err) { + return _this.destroy(err); + } + + _this._fields = utils.clone(query._fields); + options.fields = query._castFields(_this._fields); + + model.collection.find(query._conditions, options, function(err, cursor) { + if (err) { + return _this.destroy(err); + } + _this._cursor = cursor; + _this._next(); + }); +}; + +/** + * Trampoline for pulling the next doc from cursor. + * + * @see QueryStream#__next #querystream_QueryStream-__next + * @api private + */ + +QueryStream.prototype._next = function _next() { + if (this.paused || this._destroyed) { + this._running = false; + return this._running; + } + + this._running = true; + + if (this._buffer && this._buffer.length) { + var arg; + while (!this.paused && !this._destroyed && (arg = this._buffer.shift())) { // eslint-disable-line no-cond-assign + this._onNextObject.apply(this, arg); + } + } + + // avoid stack overflows with large result sets. + // trampoline instead of recursion. + while (this.__next()) { + } +}; + +/** + * Pulls the next doc from the cursor. + * + * @see QueryStream#_next #querystream_QueryStream-_next + * @api private + */ + +QueryStream.prototype.__next = function() { + if (this.paused || this._destroyed) { + this._running = false; + return this._running; + } + + var _this = this; + _this._inline = T_INIT; + + _this._cursor.nextObject(function cursorcb(err, doc) { + _this._onNextObject(err, doc); + }); + + // if onNextObject() was already called in this tick + // return ourselves to the trampoline. + if (T_CONT === this._inline) { + return true; + } + // onNextObject() hasn't fired yet. tell onNextObject + // that its ok to call _next b/c we are not within + // the trampoline anymore. + this._inline = T_IDLE; +}; + +/** + * Transforms raw `doc`s returned from the cursor into a model instance. + * + * @param {Error|null} err + * @param {Object} doc + * @api private + */ + +QueryStream.prototype._onNextObject = function _onNextObject(err, doc) { + if (this._destroyed) { + return; + } + + if (this.paused) { + this._buffer || (this._buffer = []); + this._buffer.push([err, doc]); + this._running = false; + return this._running; + } + + if (err) { + return this.destroy(err); + } + + // when doc is null we hit the end of the cursor + if (!doc) { + this.emit('end'); + return this.destroy(); + } + + var opts = this.query._mongooseOptions; + + if (!opts.populate) { + return opts.lean === true ? + emit(this, doc) : + createAndEmit(this, null, doc); + } + + var _this = this; + var pop = helpers.preparePopulationOptionsMQ(_this.query, _this.query._mongooseOptions); + + // Hack to work around gh-3108 + pop.forEach(function(option) { + delete option.model; + }); + + pop.__noPromise = true; + _this.query.model.populate(doc, pop, function(err, doc) { + if (err) { + return _this.destroy(err); + } + return opts.lean === true ? + emit(_this, doc) : + createAndEmit(_this, pop, doc); + }); +}; + +function createAndEmit(self, populatedIds, doc) { + var instance = helpers.createModel(self.query.model, doc, self._fields); + var opts = populatedIds ? + {populated: populatedIds} : + undefined; + + instance.init(doc, opts, function(err) { + if (err) { + return self.destroy(err); + } + emit(self, instance); + }); +} + +/*! + * Emit a data event and manage the trampoline state + */ + +function emit(self, doc) { + self.emit('data', self._transform(doc)); + + // trampoline management + if (T_IDLE === self._inline) { + // no longer in trampoline. restart it. + self._next(); + } else { + // in a trampoline. tell __next that its + // ok to continue jumping. + self._inline = T_CONT; + } +} + +/** + * Pauses this stream. + * + * @api public + */ + +QueryStream.prototype.pause = function() { + this.paused = true; +}; + +/** + * Resumes this stream. + * + * @api public + */ + +QueryStream.prototype.resume = function() { + this.paused = false; + + if (!this._cursor) { + // cannot start if not initialized + return; + } + + // are we within the trampoline? + if (T_INIT === this._inline) { + return; + } + + if (!this._running) { + // outside QueryStream control, need manual restart + return this._next(); + } +}; + +/** + * Destroys the stream, closing the underlying cursor. No more events will be emitted. + * + * @param {Error} [err] + * @api public + */ + +QueryStream.prototype.destroy = function(err) { + if (this._destroyed) { + return; + } + this._destroyed = true; + this._running = false; + this.readable = false; + + if (this._cursor) { + this._cursor.close(); + } + + if (err) { + this.emit('error', err); + } + + this.emit('close'); +}; + +/** + * Pipes this query stream into another stream. This method is inherited from NodeJS Streams. + * + * ####Example: + * + * query.stream().pipe(writeStream [, options]) + * + * @method pipe + * @memberOf QueryStream + * @see NodeJS http://nodejs.org/api/stream.html + * @api public + */ + +/*! + * Module exports + */ + +module.exports = exports = QueryStream; diff --git a/5-3/node_modules/mongoose/lib/schema.js b/5-3/node_modules/mongoose/lib/schema.js new file mode 100644 index 0000000..06b2d7a --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema.js @@ -0,0 +1,1374 @@ +/*! + * Module dependencies. + */ + +var readPref = require('./drivers').ReadPreference; +var EventEmitter = require('events').EventEmitter; +var VirtualType = require('./virtualtype'); +var utils = require('./utils'); +var MongooseTypes; +var Kareem = require('kareem'); +var async = require('async'); + +var IS_QUERY_HOOK = { + count: true, + find: true, + findOne: true, + findOneAndUpdate: true, + findOneAndRemove: true, + update: true +}; + +/** + * Schema constructor. + * + * ####Example: + * + * var child = new Schema({ name: String }); + * var schema = new Schema({ name: String, age: Number, children: [child] }); + * var Tree = mongoose.model('Tree', schema); + * + * // setting schema options + * new Schema({ name: String }, { _id: false, autoIndex: false }) + * + * ####Options: + * + * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option) + * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true + * - [capped](/docs/guide.html#capped): bool - defaults to false + * - [collection](/docs/guide.html#collection): string - no default + * - [emitIndexErrors](/docs/guide.html#emitIndexErrors): bool - defaults to false. + * - [id](/docs/guide.html#id): bool - defaults to true + * - [_id](/docs/guide.html#_id): bool - defaults to true + * - `minimize`: bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true + * - [read](/docs/guide.html#read): string + * - [safe](/docs/guide.html#safe): bool - defaults to true. + * - [shardKey](/docs/guide.html#shardKey): bool - defaults to `null` + * - [strict](/docs/guide.html#strict): bool - defaults to true + * - [toJSON](/docs/guide.html#toJSON) - object - no default + * - [toObject](/docs/guide.html#toObject) - object - no default + * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type' + * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` + * - [versionKey](/docs/guide.html#versionKey): string - defaults to "__v" + * + * ####Note: + * + * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ + * + * @param {Object} definition + * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter + * @event `init`: Emitted after the schema is compiled into a `Model`. + * @api public + */ + +function Schema(obj, options) { + if (!(this instanceof Schema)) { + return new Schema(obj, options); + } + + this.paths = {}; + this.subpaths = {}; + this.virtuals = {}; + this.singleNestedPaths = {}; + this.nested = {}; + this.inherits = {}; + this.callQueue = []; + this._indexes = []; + this.methods = {}; + this.statics = {}; + this.tree = {}; + this._requiredpaths = undefined; + this.discriminatorMapping = undefined; + this._indexedpaths = undefined; + + this.s = { + hooks: new Kareem(), + queryHooks: IS_QUERY_HOOK + }; + + this.options = this.defaultOptions(options); + + // build paths + if (obj) { + this.add(obj); + } + + // check if _id's value is a subdocument (gh-2276) + var _idSubDoc = obj && obj._id && utils.isObject(obj._id); + + // ensure the documents get an auto _id unless disabled + var auto_id = !this.paths['_id'] && + (!this.options.noId && this.options._id) && !_idSubDoc; + + if (auto_id) { + obj = {_id: {auto: true}}; + obj._id[this.options.typeKey] = Schema.ObjectId; + this.add(obj); + } + + // ensure the documents receive an id getter unless disabled + var autoid = !this.paths['id'] && + (!this.options.noVirtualId && this.options.id); + if (autoid) { + this.virtual('id').get(idGetter); + } + + for (var i = 0; i < this._defaultMiddleware.length; ++i) { + var m = this._defaultMiddleware[i]; + this[m.kind](m.hook, !!m.isAsync, m.fn); + } + + // adds updatedAt and createdAt timestamps to documents if enabled + var timestamps = this.options.timestamps; + if (timestamps) { + var createdAt = timestamps.createdAt || 'createdAt', + updatedAt = timestamps.updatedAt || 'updatedAt', + schemaAdditions = {}; + + schemaAdditions[updatedAt] = Date; + + if (!this.paths[createdAt]) { + schemaAdditions[createdAt] = Date; + } + + this.add(schemaAdditions); + + this.pre('save', function(next) { + var defaultTimestamp = new Date(); + + if (!this[createdAt]) { + this[createdAt] = auto_id ? this._id.getTimestamp() : defaultTimestamp; + } + + this[updatedAt] = this.isNew ? this[createdAt] : defaultTimestamp; + + next(); + }); + + var genUpdates = function() { + var now = new Date(); + var updates = {$set: {}, $setOnInsert: {}}; + updates.$set[updatedAt] = now; + updates.$setOnInsert[createdAt] = now; + + return updates; + }; + + this.pre('findOneAndUpdate', function(next) { + this.findOneAndUpdate({}, genUpdates()); + next(); + }); + + this.pre('update', function(next) { + this.update({}, genUpdates()); + next(); + }); + } +} + +/*! + * Returns this documents _id cast to a string. + */ + +function idGetter() { + if (this.$__._id) { + return this.$__._id; + } + + this.$__._id = this._id == null + ? null + : String(this._id); + return this.$__._id; +} + +/*! + * Inherit from EventEmitter. + */ +Schema.prototype = Object.create(EventEmitter.prototype); +Schema.prototype.constructor = Schema; +Schema.prototype.instanceOfSchema = true; + +/** + * Default middleware attached to a schema. Cannot be changed. + * + * This field is used to make sure discriminators don't get multiple copies of + * built-in middleware. Declared as a constant because changing this at runtime + * may lead to instability with Model.prototype.discriminator(). + * + * @api private + * @property _defaultMiddleware + */ +Object.defineProperty(Schema.prototype, '_defaultMiddleware', { + configurable: false, + enumerable: false, + writable: false, + value: [{ + kind: 'pre', + hook: 'save', + fn: function(next, options) { + // Nested docs have their own presave + if (this.ownerDocument) { + return next(); + } + + var hasValidateBeforeSaveOption = options && + (typeof options === 'object') && + ('validateBeforeSave' in options); + + var shouldValidate; + if (hasValidateBeforeSaveOption) { + shouldValidate = !!options.validateBeforeSave; + } else { + shouldValidate = this.schema.options.validateBeforeSave; + } + + // Validate + if (shouldValidate) { + // HACK: use $__original_validate to avoid promises so bluebird doesn't + // complain + if (this.$__original_validate) { + this.$__original_validate({__noPromise: true}, function(error) { + next(error); + }); + } else { + this.validate({__noPromise: true}, function(error) { + next(error); + }); + } + } else { + next(); + } + } + }, { + kind: 'pre', + hook: 'save', + isAsync: true, + fn: function(next, done) { + var subdocs = this.$__getAllSubdocs(); + + if (!subdocs.length || this.$__preSavingFromParent) { + done(); + next(); + return; + } + + async.each(subdocs, function(subdoc, cb) { + subdoc.$__preSavingFromParent = true; + subdoc.save(function(err) { + cb(err); + }); + }, function(error) { + for (var i = 0; i < subdocs.length; ++i) { + delete subdocs[i].$__preSavingFromParent; + } + if (error) { + done(error); + return; + } + next(); + done(); + }); + } + }] +}); + +/** + * Schema as flat paths + * + * ####Example: + * { + * '_id' : SchemaType, + * , 'nested.key' : SchemaType, + * } + * + * @api private + * @property paths + */ + +Schema.prototype.paths; + +/** + * Schema as a tree + * + * ####Example: + * { + * '_id' : ObjectId + * , 'nested' : { + * 'key' : String + * } + * } + * + * @api private + * @property tree + */ + +Schema.prototype.tree; + +/** + * Returns default options for this schema, merged with `options`. + * + * @param {Object} options + * @return {Object} + * @api private + */ + +Schema.prototype.defaultOptions = function(options) { + if (options && options.safe === false) { + options.safe = {w: 0}; + } + + if (options && options.safe && options.safe.w === 0) { + // if you turn off safe writes, then versioning goes off as well + options.versionKey = false; + } + + options = utils.options({ + strict: true, + bufferCommands: true, + capped: false, // { size, max, autoIndexId } + versionKey: '__v', + discriminatorKey: '__t', + minimize: true, + autoIndex: null, + shardKey: null, + read: null, + validateBeforeSave: true, + // the following are only applied at construction time + noId: false, // deprecated, use { _id: false } + _id: true, + noVirtualId: false, // deprecated, use { id: false } + id: true, + typeKey: 'type' + }, options); + + if (options.read) { + options.read = readPref(options.read); + } + + return options; +}; + +/** + * Adds key path / schema type pairs to this schema. + * + * ####Example: + * + * var ToySchema = new Schema; + * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); + * + * @param {Object} obj + * @param {String} prefix + * @api public + */ + +Schema.prototype.add = function add(obj, prefix) { + prefix = prefix || ''; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + + if (obj[key] == null) { + throw new TypeError('Invalid value for schema path `' + prefix + key + '`'); + } + + if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) { + throw new TypeError('Invalid value for schema Array path `' + prefix + key + '`'); + } + + if (utils.isObject(obj[key]) && + (!obj[key].constructor || utils.getFunctionName(obj[key].constructor) === 'Object') && + (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type))) { + if (Object.keys(obj[key]).length) { + // nested object { last: { name: String }} + this.nested[prefix + key] = true; + this.add(obj[key], prefix + key + '.'); + } else { + this.path(prefix + key, obj[key]); // mixed type + } + } else { + this.path(prefix + key, obj[key]); + } + } +}; + +/** + * Reserved document keys. + * + * Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error. + * + * on, emit, _events, db, get, set, init, isNew, errors, schema, options, modelName, collection, _pres, _posts, toObject + * + * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. + * + * var schema = new Schema(..); + * schema.methods.init = function () {} // potentially breaking + */ + +Schema.reserved = Object.create(null); +var reserved = Schema.reserved; +// EventEmitter +reserved.emit = +reserved.on = +reserved.once = +reserved.listeners = +reserved.removeListener = +// document properties and functions +reserved.collection = +reserved.db = +reserved.errors = +reserved.init = +reserved.isModified = +reserved.isNew = +reserved.get = +reserved.modelName = +reserved.save = +reserved.schema = +reserved.set = +reserved.toObject = +reserved.validate = +// hooks.js +reserved._pres = reserved._posts = 1; + +/** + * Document keys to print warnings for + */ + +var warnings = {}; +warnings.increment = '`increment` should not be used as a schema path name ' + + 'unless you have disabled versioning.'; + +/** + * Gets/sets schema paths. + * + * Sets a path (if arity 2) + * Gets a path (if arity 1) + * + * ####Example + * + * schema.path('name') // returns a SchemaType + * schema.path('name', Number) // changes the schemaType of `name` to Number + * + * @param {String} path + * @param {Object} constructor + * @api public + */ + +Schema.prototype.path = function(path, obj) { + if (obj === undefined) { + if (this.paths[path]) { + return this.paths[path]; + } + if (this.subpaths[path]) { + return this.subpaths[path]; + } + if (this.singleNestedPaths[path]) { + return this.singleNestedPaths[path]; + } + + // subpaths? + return /\.\d+\.?.*$/.test(path) + ? getPositionalPath(this, path) + : undefined; + } + + // some path names conflict with document methods + if (reserved[path]) { + throw new Error('`' + path + '` may not be used as a schema pathname'); + } + + if (warnings[path]) { + console.log('WARN: ' + warnings[path]); + } + + // update the tree + var subpaths = path.split(/\./), + last = subpaths.pop(), + branch = this.tree; + + subpaths.forEach(function(sub, i) { + if (!branch[sub]) { + branch[sub] = {}; + } + if (typeof branch[sub] !== 'object') { + var msg = 'Cannot set nested path `' + path + '`. ' + + 'Parent path `' + + subpaths.slice(0, i).concat([sub]).join('.') + + '` already set to type ' + branch[sub].name + + '.'; + throw new Error(msg); + } + branch = branch[sub]; + }); + + branch[last] = utils.clone(obj); + + this.paths[path] = Schema.interpretAsType(path, obj, this.options); + if (this.paths[path].$isSingleNested) { + for (var key in this.paths[path].schema.paths) { + this.singleNestedPaths[path + '.' + key] = + this.paths[path].schema.paths[key]; + } + for (key in this.paths[path].schema.singleNestedPaths) { + this.singleNestedPaths[path + '.' + key] = + this.paths[path].schema.singleNestedPaths[key]; + } + } + return this; +}; + +/** + * Converts type arguments into Mongoose Types. + * + * @param {String} path + * @param {Object} obj constructor + * @api private + */ + +Schema.interpretAsType = function(path, obj, options) { + if (obj.constructor) { + var constructorName = utils.getFunctionName(obj.constructor); + if (constructorName !== 'Object') { + var oldObj = obj; + obj = {}; + obj[options.typeKey] = oldObj; + } + } + + // Get the type making sure to allow keys named "type" + // and default to mixed if not specified. + // { type: { type: String, default: 'freshcut' } } + var type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type) + ? obj[options.typeKey] + : {}; + + if (utils.getFunctionName(type.constructor) === 'Object' || type === 'mixed') { + return new MongooseTypes.Mixed(path, obj); + } + + if (Array.isArray(type) || Array === type || type === 'array') { + // if it was specified through { type } look for `cast` + var cast = (Array === type || type === 'array') + ? obj.cast + : type[0]; + + if (cast && cast.instanceOfSchema) { + return new MongooseTypes.DocumentArray(path, cast, obj); + } + + if (typeof cast === 'string') { + cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; + } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type)) + && utils.getFunctionName(cast.constructor) === 'Object' + && Object.keys(cast).length) { + // The `minimize` and `typeKey` options propagate to child schemas + // declared inline, like `{ arr: [{ val: { $type: String } }] }`. + // See gh-3560 + var childSchemaOptions = {minimize: options.minimize}; + if (options.typeKey) { + childSchemaOptions.typeKey = options.typeKey; + } + var childSchema = new Schema(cast, childSchemaOptions); + return new MongooseTypes.DocumentArray(path, childSchema, obj); + } + + return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj); + } + + if (type && type.instanceOfSchema) { + return new MongooseTypes.Embedded(type, path, obj); + } + + var name; + if (Buffer.isBuffer(type)) { + name = 'Buffer'; + } else { + name = typeof type === 'string' + ? type + // If not string, `type` is a function. Outside of IE, function.name + // gives you the function name. In IE, you need to compute it + : type.schemaName || utils.getFunctionName(type); + } + + if (name) { + name = name.charAt(0).toUpperCase() + name.substring(1); + } + + if (undefined == MongooseTypes[name]) { + throw new TypeError('Undefined type `' + name + '` at `' + path + + '`\n Did you try nesting Schemas? ' + + 'You can only nest using refs or arrays.'); + } + + return new MongooseTypes[name](path, obj); +}; + +/** + * Iterates the schemas paths similar to Array#forEach. + * + * The callback is passed the pathname and schemaType as arguments on each iteration. + * + * @param {Function} fn callback function + * @return {Schema} this + * @api public + */ + +Schema.prototype.eachPath = function(fn) { + var keys = Object.keys(this.paths), + len = keys.length; + + for (var i = 0; i < len; ++i) { + fn(keys[i], this.paths[keys[i]]); + } + + return this; +}; + +/** + * Returns an Array of path strings that are required by this schema. + * + * @api public + * @param {Boolean} invalidate refresh the cache + * @return {Array} + */ + +Schema.prototype.requiredPaths = function requiredPaths(invalidate) { + if (this._requiredpaths && !invalidate) { + return this._requiredpaths; + } + + var paths = Object.keys(this.paths), + i = paths.length, + ret = []; + + while (i--) { + var path = paths[i]; + if (this.paths[path].isRequired) { + ret.push(path); + } + } + this._requiredpaths = ret; + return this._requiredpaths; +}; + +/** + * Returns indexes from fields and schema-level indexes (cached). + * + * @api private + * @return {Array} + */ + +Schema.prototype.indexedPaths = function indexedPaths() { + if (this._indexedpaths) { + return this._indexedpaths; + } + this._indexedpaths = this.indexes(); + return this._indexedpaths; +}; + +/** + * Returns the pathType of `path` for this schema. + * + * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. + * + * @param {String} path + * @return {String} + * @api public + */ + +Schema.prototype.pathType = function(path) { + if (path in this.paths) { + return 'real'; + } + if (path in this.virtuals) { + return 'virtual'; + } + if (path in this.nested) { + return 'nested'; + } + if (path in this.subpaths) { + return 'real'; + } + if (path in this.singleNestedPaths) { + return 'real'; + } + + if (/\.\d+\.|\.\d+$/.test(path)) { + return getPositionalPathType(this, path); + } + return 'adhocOrUndefined'; +}; + +/** + * Returns true iff this path is a child of a mixed schema. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Schema.prototype.hasMixedParent = function(path) { + var subpaths = path.split(/\./g); + path = ''; + for (var i = 0; i < subpaths.length; ++i) { + path = i > 0 ? path + '.' + subpaths[i] : subpaths[i]; + if (path in this.paths && + this.paths[path] instanceof MongooseTypes.Mixed) { + return true; + } + } + + return false; +}; + +/*! + * ignore + */ + +function getPositionalPathType(self, path) { + var subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); + if (subpaths.length < 2) { + return self.paths[subpaths[0]]; + } + + var val = self.path(subpaths[0]); + var isNested = false; + if (!val) { + return val; + } + + var last = subpaths.length - 1, + subpath, + i = 1; + + for (; i < subpaths.length; ++i) { + isNested = false; + subpath = subpaths[i]; + + if (i === last && val && !val.schema && !/\D/.test(subpath)) { + if (val instanceof MongooseTypes.Array) { + // StringSchema, NumberSchema, etc + val = val.caster; + } else { + val = undefined; + } + break; + } + + // ignore if its just a position segment: path.0.subpath + if (!/\D/.test(subpath)) { + continue; + } + + if (!(val && val.schema)) { + val = undefined; + break; + } + + var type = val.schema.pathType(subpath); + isNested = (type === 'nested'); + val = val.schema.path(subpath); + } + + self.subpaths[path] = val; + if (val) { + return 'real'; + } + if (isNested) { + return 'nested'; + } + return 'adhocOrUndefined'; +} + + +/*! + * ignore + */ + +function getPositionalPath(self, path) { + getPositionalPathType(self, path); + return self.subpaths[path]; +} + +/** + * Adds a method call to the queue. + * + * @param {String} name name of the document method to call later + * @param {Array} args arguments to pass to the method + * @api public + */ + +Schema.prototype.queue = function(name, args) { + this.callQueue.push([name, args]); + return this; +}; + +/** + * Defines a pre hook for the document. + * + * ####Example + * + * var toySchema = new Schema(..); + * + * toySchema.pre('save', function (next) { + * if (!this.created) this.created = new Date; + * next(); + * }) + * + * toySchema.pre('validate', function (next) { + * if (this.name !== 'Woody') this.name = 'Woody'; + * next(); + * }) + * + * @param {String} method + * @param {Function} callback + * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 + * @api public + */ + +Schema.prototype.pre = function() { + var name = arguments[0]; + if (IS_QUERY_HOOK[name]) { + this.s.hooks.pre.apply(this.s.hooks, arguments); + return this; + } + return this.queue('pre', arguments); +}; + +/** + * Defines a post hook for the document + * + * Post hooks fire `on` the event emitted from document instances of Models compiled from this schema. + * + * var schema = new Schema(..); + * schema.post('save', function (doc) { + * console.log('this fired after a document was saved'); + * }); + * + * var Model = mongoose.model('Model', schema); + * + * var m = new Model(..); + * m.save(function (err) { + * console.log('this fires after the `post` hook'); + * }); + * + * @param {String} method name of the method to hook + * @param {Function} fn callback + * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 + * @api public + */ + +Schema.prototype.post = function(method, fn) { + if (IS_QUERY_HOOK[method]) { + this.s.hooks.post.apply(this.s.hooks, arguments); + return this; + } + // assuming that all callbacks with arity < 2 are synchronous post hooks + if (fn.length < 2) { + return this.queue('on', [arguments[0], function(doc) { + return fn.call(doc, doc); + }]); + } + + return this.queue('post', [arguments[0], function(next) { + // wrap original function so that the callback goes last, + // for compatibility with old code that is using synchronous post hooks + var _this = this; + var args = Array.prototype.slice.call(arguments, 1); + fn.call(this, this, function(err) { + return next.apply(_this, [err].concat(args)); + }); + }]); +}; + +/** + * Registers a plugin for this schema. + * + * @param {Function} plugin callback + * @param {Object} [opts] + * @see plugins + * @api public + */ + +Schema.prototype.plugin = function(fn, opts) { + fn(this, opts); + return this; +}; + +/** + * Adds an instance method to documents constructed from Models compiled from this schema. + * + * ####Example + * + * var schema = kittySchema = new Schema(..); + * + * schema.method('meow', function () { + * console.log('meeeeeoooooooooooow'); + * }) + * + * var Kitty = mongoose.model('Kitty', schema); + * + * var fizz = new Kitty; + * fizz.meow(); // meeeeeooooooooooooow + * + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. + * + * schema.method({ + * purr: function () {} + * , scratch: function () {} + * }); + * + * // later + * fizz.purr(); + * fizz.scratch(); + * + * @param {String|Object} method name + * @param {Function} [fn] + * @api public + */ + +Schema.prototype.method = function(name, fn) { + if (typeof name !== 'string') { + for (var i in name) { + this.methods[i] = name[i]; + } + } else { + this.methods[name] = fn; + } + return this; +}; + +/** + * Adds static "class" methods to Models compiled from this schema. + * + * ####Example + * + * var schema = new Schema(..); + * schema.static('findByName', function (name, callback) { + * return this.find({ name: name }, callback); + * }); + * + * var Drink = mongoose.model('Drink', schema); + * Drink.findByName('sanpellegrino', function (err, drinks) { + * // + * }); + * + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. + * + * @param {String} name + * @param {Function} fn + * @api public + */ + +Schema.prototype.static = function(name, fn) { + if (typeof name !== 'string') { + for (var i in name) { + this.statics[i] = name[i]; + } + } else { + this.statics[name] = fn; + } + return this; +}; + +/** + * Defines an index (most likely compound) for this schema. + * + * ####Example + * + * schema.index({ first: 1, last: -1 }) + * + * @param {Object} fields + * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex) + * @param {String} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link. + * @api public + */ + +Schema.prototype.index = function(fields, options) { + options || (options = {}); + + if (options.expires) { + utils.expires(options); + } + + this._indexes.push([fields, options]); + return this; +}; + +/** + * Sets/gets a schema option. + * + * ####Example + * + * schema.set('strict'); // 'true' by default + * schema.set('strict', false); // Sets 'strict' to false + * schema.set('strict'); // 'false' + * + * @param {String} key option name + * @param {Object} [value] if not passed, the current option value is returned + * @see Schema ./ + * @api public + */ + +Schema.prototype.set = function(key, value, _tags) { + if (arguments.length === 1) { + return this.options[key]; + } + + switch (key) { + case 'read': + this.options[key] = readPref(value, _tags); + break; + case 'safe': + this.options[key] = value === false + ? {w: 0} + : value; + break; + default: + this.options[key] = value; + } + + return this; +}; + +/** + * Gets a schema option. + * + * @param {String} key option name + * @api public + */ + +Schema.prototype.get = function(key) { + return this.options[key]; +}; + +/** + * The allowed index types + * + * @static indexTypes + * @receiver Schema + * @api public + */ + +var indexTypes = '2d 2dsphere hashed text'.split(' '); + +Object.defineProperty(Schema, 'indexTypes', { + get: function() { + return indexTypes; + }, + set: function() { + throw new Error('Cannot overwrite Schema.indexTypes'); + } +}); + +/** + * Compiles indexes from fields and schema-level indexes + * + * @api public + */ + +Schema.prototype.indexes = function() { + 'use strict'; + + var indexes = []; + var seenPrefix = {}; + + var collectIndexes = function(schema, prefix) { + if (seenPrefix[prefix]) { + return; + } + seenPrefix[prefix] = true; + + prefix = prefix || ''; + var key, path, index, field, isObject, options, type; + var keys = Object.keys(schema.paths); + + for (var i = 0; i < keys.length; ++i) { + key = keys[i]; + path = schema.paths[key]; + + if ((path instanceof MongooseTypes.DocumentArray) || path.$isSingleNested) { + collectIndexes(path.schema, key + '.'); + } else { + index = path._index; + + if (index !== false && index !== null && index !== undefined) { + field = {}; + isObject = utils.isObject(index); + options = isObject ? index : {}; + type = typeof index === 'string' ? index : + isObject ? index.type : + false; + + if (type && ~Schema.indexTypes.indexOf(type)) { + field[prefix + key] = type; + } else if (options.text) { + field[prefix + key] = 'text'; + delete options.text; + } else { + field[prefix + key] = 1; + } + + delete options.type; + if (!('background' in options)) { + options.background = true; + } + + indexes.push([field, options]); + } + } + } + + if (prefix) { + fixSubIndexPaths(schema, prefix); + } else { + schema._indexes.forEach(function(index) { + if (!('background' in index[1])) { + index[1].background = true; + } + }); + indexes = indexes.concat(schema._indexes); + } + }; + + collectIndexes(this); + return indexes; + + /*! + * Checks for indexes added to subdocs using Schema.index(). + * These indexes need their paths prefixed properly. + * + * schema._indexes = [ [indexObj, options], [indexObj, options] ..] + */ + + function fixSubIndexPaths(schema, prefix) { + var subindexes = schema._indexes, + len = subindexes.length, + indexObj, + newindex, + klen, + keys, + key, + i = 0, + j; + + for (i = 0; i < len; ++i) { + indexObj = subindexes[i][0]; + keys = Object.keys(indexObj); + klen = keys.length; + newindex = {}; + + // use forward iteration, order matters + for (j = 0; j < klen; ++j) { + key = keys[j]; + newindex[prefix + key] = indexObj[key]; + } + + indexes.push([newindex, subindexes[i][1]]); + } + } +}; + +/** + * Creates a virtual type with the given name. + * + * @param {String} name + * @param {Object} [options] + * @return {VirtualType} + */ + +Schema.prototype.virtual = function(name, options) { + var virtuals = this.virtuals; + var parts = name.split('.'); + virtuals[name] = parts.reduce(function(mem, part, i) { + mem[part] || (mem[part] = (i === parts.length - 1) + ? new VirtualType(options, name) + : {}); + return mem[part]; + }, this.tree); + return virtuals[name]; +}; + +/** + * Returns the virtual type with the given `name`. + * + * @param {String} name + * @return {VirtualType} + */ + +Schema.prototype.virtualpath = function(name) { + return this.virtuals[name]; +}; + +/** + * Removes the given `path` (or [`paths`]). + * + * @param {String|Array} path + * + * @api public + */ +Schema.prototype.remove = function(path) { + if (typeof path === 'string') { + path = [path]; + } + if (Array.isArray(path)) { + path.forEach(function(name) { + if (this.path(name)) { + delete this.paths[name]; + } + }, this); + } +}; + +/*! + * ignore + */ + +Schema.prototype._getSchema = function(path) { + var _this = this; + var pathschema = _this.path(path); + + if (pathschema) { + return pathschema; + } + + function search(parts, schema) { + var p = parts.length + 1, + foundschema, + trypath; + + while (p--) { + trypath = parts.slice(0, p).join('.'); + foundschema = schema.path(trypath); + if (foundschema) { + if (foundschema.caster) { + // array of Mixed? + if (foundschema.caster instanceof MongooseTypes.Mixed) { + return foundschema.caster; + } + + // Now that we found the array, we need to check if there + // are remaining document paths to look up for casting. + // Also we need to handle array.$.path since schema.path + // doesn't work for that. + // If there is no foundschema.schema we are dealing with + // a path like array.$ + if (p !== parts.length && foundschema.schema) { + if (parts[p] === '$') { + // comments.$.comments.$.title + return search(parts.slice(p + 1), foundschema.schema); + } + // this is the last path of the selector + return search(parts.slice(p), foundschema.schema); + } + } + return foundschema; + } + } + } + + // look for arrays + return search(path.split('.'), _this); +}; + +/*! + * ignore + */ + +Schema.prototype._getPathType = function(path) { + var _this = this; + var pathschema = _this.path(path); + + if (pathschema) { + return 'real'; + } + + function search(parts, schema) { + var p = parts.length + 1, + foundschema, + trypath; + + while (p--) { + trypath = parts.slice(0, p).join('.'); + foundschema = schema.path(trypath); + if (foundschema) { + if (foundschema.caster) { + // array of Mixed? + if (foundschema.caster instanceof MongooseTypes.Mixed) { + return 'mixed'; + } + + // Now that we found the array, we need to check if there + // are remaining document paths to look up for casting. + // Also we need to handle array.$.path since schema.path + // doesn't work for that. + // If there is no foundschema.schema we are dealing with + // a path like array.$ + if (p !== parts.length && foundschema.schema) { + if (parts[p] === '$') { + if (p === parts.length - 1) { + return 'nested'; + } + // comments.$.comments.$.title + return search(parts.slice(p + 1), foundschema.schema); + } + // this is the last path of the selector + return search(parts.slice(p), foundschema.schema); + } + return foundschema.$isSingleNested ? 'nested' : 'array'; + } + return 'real'; + } else if (p === parts.length && schema.nested[trypath]) { + return 'nested'; + } + } + return 'undefined'; + } + + // look for arrays + return search(path.split('.'), _this); +}; + + +/*! + * Module exports. + */ + +module.exports = exports = Schema; + +// require down here because of reference issues + +/** + * The various built-in Mongoose Schema Types. + * + * ####Example: + * + * var mongoose = require('mongoose'); + * var ObjectId = mongoose.Schema.Types.ObjectId; + * + * ####Types: + * + * - [String](#schema-string-js) + * - [Number](#schema-number-js) + * - [Boolean](#schema-boolean-js) | Bool + * - [Array](#schema-array-js) + * - [Buffer](#schema-buffer-js) + * - [Date](#schema-date-js) + * - [ObjectId](#schema-objectid-js) | Oid + * - [Mixed](#schema-mixed-js) + * + * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. + * + * var Mixed = mongoose.Schema.Types.Mixed; + * new mongoose.Schema({ _user: Mixed }) + * + * @api public + */ + +Schema.Types = MongooseTypes = require('./schema/index'); + +/*! + * ignore + */ + +exports.ObjectId = MongooseTypes.ObjectId; diff --git a/5-3/node_modules/mongoose/lib/schema/array.js b/5-3/node_modules/mongoose/lib/schema/array.js new file mode 100644 index 0000000..7fec9e8 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/array.js @@ -0,0 +1,391 @@ +/*! + * Module dependencies. + */ + +var SchemaType = require('../schematype'), + CastError = SchemaType.CastError, + Types = { + Boolean: require('./boolean'), + Date: require('./date'), + Number: require('./number'), + String: require('./string'), + ObjectId: require('./objectid'), + Buffer: require('./buffer') + }, + MongooseArray = require('../types').Array, + EmbeddedDoc = require('../types').Embedded, + Mixed = require('./mixed'), + cast = require('../cast'), + utils = require('../utils'), + isMongooseObject = utils.isMongooseObject; + +/** + * Array SchemaType constructor + * + * @param {String} key + * @param {SchemaType} cast + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaArray(key, cast, options) { + if (cast) { + var castOptions = {}; + + if (utils.getFunctionName(cast.constructor) === 'Object') { + if (cast.type) { + // support { type: Woot } + castOptions = utils.clone(cast); // do not alter user arguments + delete castOptions.type; + cast = cast.type; + } else { + cast = Mixed; + } + } + + // support { type: 'String' } + var name = typeof cast === 'string' + ? cast + : utils.getFunctionName(cast); + + var caster = name in Types + ? Types[name] + : cast; + + this.casterConstructor = caster; + this.caster = new caster(null, castOptions); + if (!(this.caster instanceof EmbeddedDoc)) { + this.caster.path = key; + } + } + + SchemaType.call(this, key, options, 'Array'); + + var _this = this, + defaultArr, + fn; + + if (this.defaultValue) { + defaultArr = this.defaultValue; + fn = typeof defaultArr === 'function'; + } + + this.default(function() { + var arr = fn ? defaultArr() : defaultArr || []; + return new MongooseArray(arr, _this.path, this); + }); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaArray.schemaName = 'Array'; + +/*! + * Inherits from SchemaType. + */ +SchemaArray.prototype = Object.create(SchemaType.prototype); +SchemaArray.prototype.constructor = SchemaArray; + +/** + * Check required + * + * @param {Array} value + * @api private + */ + +SchemaArray.prototype.checkRequired = function(value) { + return !!(value && value.length); +}; + +/** + * Overrides the getters application for the population special-case + * + * @param {Object} value + * @param {Object} scope + * @api private + */ + +SchemaArray.prototype.applyGetters = function(value, scope) { + if (this.caster.options && this.caster.options.ref) { + // means the object id was populated + return value; + } + + return SchemaType.prototype.applyGetters.call(this, value, scope); +}; + +/** + * Casts values for set(). + * + * @param {Object} value + * @param {Document} doc document that triggers the casting + * @param {Boolean} init whether this is an initialization cast + * @api private + */ + +SchemaArray.prototype.cast = function(value, doc, init) { + if (Array.isArray(value)) { + if (!value.length && doc) { + var indexes = doc.schema.indexedPaths(); + + for (var i = 0, l = indexes.length; i < l; ++i) { + var pathIndex = indexes[i][0][this.path]; + if (pathIndex === '2dsphere' || pathIndex === '2d') { + return; + } + } + } + + if (!(value && value.isMongooseArray)) { + value = new MongooseArray(value, this.path, doc); + } + + if (this.caster) { + try { + for (i = 0, l = value.length; i < l; i++) { + value[i] = this.caster.cast(value[i], doc, init); + } + } catch (e) { + // rethrow + throw new CastError(e.type, value, this.path); + } + } + + return value; + } + // gh-2442: if we're loading this from the db and its not an array, mark + // the whole array as modified. + if (!!doc && !!init) { + doc.markModified(this.path); + } + return this.cast([value], doc, init); +}; + +/** + * Casts values for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaArray.prototype.castForQuery = function($conditional, value) { + var handler, + val; + + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Array.'); + } + + val = handler.call(this, value); + } else { + val = $conditional; + var proto = this.casterConstructor.prototype; + var method = proto.castForQuery || proto.cast; + var caster = this.caster; + + if (Array.isArray(val)) { + val = val.map(function(v) { + if (utils.isObject(v) && v.$elemMatch) { + return v; + } + if (method) { + v = method.call(caster, v); + } + return isMongooseObject(v) ? + v.toObject({virtuals: false}) : + v; + }); + } else if (method) { + val = method.call(caster, val); + } + } + + return val && isMongooseObject(val) ? + val.toObject({virtuals: false}) : + val; +}; + +/*! + * @ignore + * + * $atomic cast helpers + */ + +function castToNumber(val) { + return Types.Number.prototype.cast.call(this, val); +} + +function castArraysOfNumbers(arr, self) { + arr.forEach(function(v, i) { + if (Array.isArray(v)) { + castArraysOfNumbers(v, self); + } else { + arr[i] = castToNumber.call(self, v); + } + }); +} + +function cast$near(val) { + if (Array.isArray(val)) { + castArraysOfNumbers(val, this); + return val; + } + + if (val && val.$geometry) { + return cast$geometry(val, this); + } + + return SchemaArray.prototype.castForQuery.call(this, val); +} + +function cast$geometry(val, self) { + switch (val.$geometry.type) { + case 'Polygon': + case 'LineString': + case 'Point': + castArraysOfNumbers(val.$geometry.coordinates, self); + break; + default: + // ignore unknowns + break; + } + + if (val.$maxDistance) { + val.$maxDistance = castToNumber.call(self, val.$maxDistance); + } + + return val; +} + +function cast$within(val) { + var _this = this; + + if (val.$maxDistance) { + val.$maxDistance = castToNumber.call(_this, val.$maxDistance); + } + + if (val.$box || val.$polygon) { + var type = val.$box ? '$box' : '$polygon'; + val[type].forEach(function(arr) { + if (!Array.isArray(arr)) { + var msg = 'Invalid $within $box argument. ' + + 'Expected an array, received ' + arr; + throw new TypeError(msg); + } + arr.forEach(function(v, i) { + arr[i] = castToNumber.call(this, v); + }); + }); + } else if (val.$center || val.$centerSphere) { + type = val.$center ? '$center' : '$centerSphere'; + val[type].forEach(function(item, i) { + if (Array.isArray(item)) { + item.forEach(function(v, j) { + item[j] = castToNumber.call(this, v); + }); + } else { + val[type][i] = castToNumber.call(this, item); + } + }); + } else if (val.$geometry) { + cast$geometry(val, this); + } + + return val; +} + +function cast$all(val) { + if (!Array.isArray(val)) { + val = [val]; + } + + val = val.map(function(v) { + if (utils.isObject(v)) { + var o = {}; + o[this.path] = v; + return cast(this.casterConstructor.schema, o)[this.path]; + } + return v; + }, this); + + return this.castForQuery(val); +} + +function cast$elemMatch(val) { + var keys = Object.keys(val); + var numKeys = keys.length; + var key; + var value; + for (var i = 0; i < numKeys; ++i) { + key = keys[i]; + value = val[key]; + if (key.indexOf('$') === 0 && value) { + val[key] = this.castForQuery(key, value); + } + } + + return cast(this.casterConstructor.schema, val); +} + +function cast$geoIntersects(val) { + var geo = val.$geometry; + if (!geo) { + return; + } + + cast$geometry(val, this); + return val; +} + +var handle = SchemaArray.prototype.$conditionalHandlers = {}; + +handle.$all = cast$all; +handle.$options = String; +handle.$elemMatch = cast$elemMatch; +handle.$geoIntersects = cast$geoIntersects; +handle.$or = handle.$and = function(val) { + if (!Array.isArray(val)) { + throw new TypeError('conditional $or/$and require array'); + } + + var ret = []; + for (var i = 0; i < val.length; ++i) { + ret.push(cast(this.casterConstructor.schema, val[i])); + } + + return ret; +}; + +handle.$near = +handle.$nearSphere = cast$near; + +handle.$within = +handle.$geoWithin = cast$within; + +handle.$size = +handle.$maxDistance = castToNumber; + +handle.$eq = +handle.$gt = +handle.$gte = +handle.$in = +handle.$lt = +handle.$lte = +handle.$ne = +handle.$nin = +handle.$regex = SchemaArray.prototype.castForQuery; + +/*! + * Module exports. + */ + +module.exports = SchemaArray; diff --git a/5-3/node_modules/mongoose/lib/schema/boolean.js b/5-3/node_modules/mongoose/lib/schema/boolean.js new file mode 100644 index 0000000..6ca03ec --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/boolean.js @@ -0,0 +1,99 @@ +/*! + * Module dependencies. + */ + +var utils = require('../utils'); + +var SchemaType = require('../schematype'); + +/** + * Boolean SchemaType constructor. + * + * @param {String} path + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaBoolean(path, options) { + SchemaType.call(this, path, options, 'Boolean'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaBoolean.schemaName = 'Boolean'; + +/*! + * Inherits from SchemaType. + */ +SchemaBoolean.prototype = Object.create(SchemaType.prototype); +SchemaBoolean.prototype.constructor = SchemaBoolean; + +/** + * Required validator + * + * @api private + */ + +SchemaBoolean.prototype.checkRequired = function(value) { + return value === true || value === false; +}; + +/** + * Casts to boolean + * + * @param {Object} value + * @api private + */ + +SchemaBoolean.prototype.cast = function(value) { + if (value === null) { + return value; + } + if (value === '0') { + return false; + } + if (value === 'true') { + return true; + } + if (value === 'false') { + return false; + } + return !!value; +}; + +SchemaBoolean.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, {}); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} val + * @api private + */ + +SchemaBoolean.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = SchemaBoolean.$conditionalHandlers[$conditional]; + + if (handler) { + return handler.call(this, val); + } + + return this.cast(val); + } + + return this.cast($conditional); +}; + +/*! + * Module exports. + */ + +module.exports = SchemaBoolean; diff --git a/5-3/node_modules/mongoose/lib/schema/buffer.js b/5-3/node_modules/mongoose/lib/schema/buffer.js new file mode 100644 index 0000000..16432b4 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/buffer.js @@ -0,0 +1,183 @@ +/*! + * Module dependencies. + */ + +var handleBitwiseOperator = require('./operators/bitwise'); +var utils = require('../utils'); + +var MongooseBuffer = require('../types').Buffer; +var SchemaType = require('../schematype'); + +var Binary = MongooseBuffer.Binary; +var CastError = SchemaType.CastError; +var Document; + +/** + * Buffer SchemaType constructor + * + * @param {String} key + * @param {SchemaType} cast + * @inherits SchemaType + * @api public + */ + +function SchemaBuffer(key, options) { + SchemaType.call(this, key, options, 'Buffer'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaBuffer.schemaName = 'Buffer'; + +/*! + * Inherits from SchemaType. + */ +SchemaBuffer.prototype = Object.create(SchemaType.prototype); +SchemaBuffer.prototype.constructor = SchemaBuffer; + +/** + * Check required + * + * @api private + */ + +SchemaBuffer.prototype.checkRequired = function(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + return !!(value && value.length); +}; + +/** + * Casts contents + * + * @param {Object} value + * @param {Document} doc document that triggers the casting + * @param {Boolean} init + * @api private + */ + +SchemaBuffer.prototype.cast = function(value, doc, init) { + var ret; + if (SchemaType._isRef(this, value, doc, init)) { + // wait! we may need to cast this to a document + + if (value === null || value === undefined) { + return value; + } + + // lazy load + Document || (Document = require('./../document')); + + if (value instanceof Document) { + value.$__.wasPopulated = true; + return value; + } + + // setting a populated path + if (Buffer.isBuffer(value)) { + return value; + } else if (!utils.isObject(value)) { + throw new CastError('buffer', value, this.path); + } + + // Handle the case where user directly sets a populated + // path to a plain object; cast to the Model used in + // the population query. + var path = doc.$__fullPath(this.path); + var owner = doc.ownerDocument ? doc.ownerDocument() : doc; + var pop = owner.populated(path, true); + ret = new pop.options.model(value); + ret.$__.wasPopulated = true; + return ret; + } + + // documents + if (value && value._id) { + value = value._id; + } + + if (value && value.isMongooseBuffer) { + return value; + } + + if (Buffer.isBuffer(value)) { + if (!value || !value.isMongooseBuffer) { + value = new MongooseBuffer(value, [this.path, doc]); + } + + return value; + } else if (value instanceof Binary) { + ret = new MongooseBuffer(value.value(true), [this.path, doc]); + if (typeof value.sub_type !== 'number') { + throw new CastError('buffer', value, this.path); + } + ret._subtype = value.sub_type; + return ret; + } + + if (value === null) { + return value; + } + + var type = typeof value; + if (type === 'string' || type === 'number' || Array.isArray(value)) { + if (type === 'number') { + value = [value]; + } + ret = new MongooseBuffer(value, [this.path, doc]); + return ret; + } + + throw new CastError('buffer', value, this.path); +}; + +/*! + * ignore + */ +function handleSingle(val) { + return this.castForQuery(val); +} + +SchemaBuffer.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $bitsAllClear: handleBitwiseOperator, + $bitsAnyClear: handleBitwiseOperator, + $bitsAllSet: handleBitwiseOperator, + $bitsAnySet: handleBitwiseOperator, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaBuffer.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Buffer.'); + } + return handler.call(this, val); + } + val = $conditional; + return this.cast(val).toObject(); +}; + +/*! + * Module exports. + */ + +module.exports = SchemaBuffer; diff --git a/5-3/node_modules/mongoose/lib/schema/date.js b/5-3/node_modules/mongoose/lib/schema/date.js new file mode 100644 index 0000000..6794056 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/date.js @@ -0,0 +1,284 @@ +/*! + * Module requirements. + */ + +var errorMessages = require('../error').messages; +var utils = require('../utils'); + +var SchemaType = require('../schematype'); + +var CastError = SchemaType.CastError; + +/** + * Date SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaDate(key, options) { + SchemaType.call(this, key, options, 'Date'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaDate.schemaName = 'Date'; + +/*! + * Inherits from SchemaType. + */ +SchemaDate.prototype = Object.create(SchemaType.prototype); +SchemaDate.prototype.constructor = SchemaDate; + +/** + * Declares a TTL index (rounded to the nearest second) for _Date_ types only. + * + * This sets the `expireAfterSeconds` index option available in MongoDB >= 2.1.2. + * This index type is only compatible with Date types. + * + * ####Example: + * + * // expire in 24 hours + * new Schema({ createdAt: { type: Date, expires: 60*60*24 }}); + * + * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: + * + * ####Example: + * + * // expire in 24 hours + * new Schema({ createdAt: { type: Date, expires: '24h' }}); + * + * // expire in 1.5 hours + * new Schema({ createdAt: { type: Date, expires: '1.5h' }}); + * + * // expire in 7 days + * var schema = new Schema({ createdAt: Date }); + * schema.path('createdAt').expires('7d'); + * + * @param {Number|String} when + * @added 3.0.0 + * @return {SchemaType} this + * @api public + */ + +SchemaDate.prototype.expires = function(when) { + if (!this._index || this._index.constructor.name !== 'Object') { + this._index = {}; + } + + this._index.expires = when; + utils.expires(this._index); + return this; +}; + +/** + * Required validator for date + * + * @api private + */ + +SchemaDate.prototype.checkRequired = function(value) { + return value instanceof Date; +}; + +/** + * Sets a minimum date validator. + * + * ####Example: + * + * var s = new Schema({ d: { type: Date, min: Date('1970-01-01') }) + * var M = db.model('M', s) + * var m = new M({ d: Date('1969-12-31') }) + * m.save(function (err) { + * console.error(err) // validator error + * m.d = Date('2014-12-08'); + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MIN} token which will be replaced with the invalid value + * var min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; + * var schema = new Schema({ d: { type: Date, min: min }) + * var M = mongoose.model('M', schema); + * var s= new M({ d: Date('1969-12-31') }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01). + * }) + * + * @param {Date} value minimum date + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaDate.prototype.min = function(value, message) { + if (this.minValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minValidator; + }, this); + } + + if (value) { + var msg = message || errorMessages.Date.min; + msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString())); + var _this = this; + this.validators.push({ + validator: this.minValidator = function(val) { + var min = (value === Date.now ? value() : _this.cast(value)); + return val === null || val.valueOf() >= min.valueOf(); + }, + message: msg, + type: 'min', + min: value + }); + } + + return this; +}; + +/** + * Sets a maximum date validator. + * + * ####Example: + * + * var s = new Schema({ d: { type: Date, max: Date('2014-01-01') }) + * var M = db.model('M', s) + * var m = new M({ d: Date('2014-12-08') }) + * m.save(function (err) { + * console.error(err) // validator error + * m.d = Date('2013-12-31'); + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAX} token which will be replaced with the invalid value + * var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; + * var schema = new Schema({ d: { type: Date, max: max }) + * var M = mongoose.model('M', schema); + * var s= new M({ d: Date('2014-12-08') }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01). + * }) + * + * @param {Date} maximum date + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaDate.prototype.max = function(value, message) { + if (this.maxValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxValidator; + }, this); + } + + if (value) { + var msg = message || errorMessages.Date.max; + msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString())); + var _this = this; + this.validators.push({ + validator: this.maxValidator = function(val) { + var max = (value === Date.now ? value() : _this.cast(value)); + return val === null || val.valueOf() <= max.valueOf(); + }, + message: msg, + type: 'max', + max: value + }); + } + + return this; +}; + +/** + * Casts to date + * + * @param {Object} value to cast + * @api private + */ + +SchemaDate.prototype.cast = function(value) { + // If null or undefined + if (value === null || value === void 0 || value === '') { + return null; + } + + if (value instanceof Date) { + return value; + } + + var date; + + if (value instanceof Number || typeof value === 'number' + || String(value) == Number(value)) { + // support for timestamps + date = new Date(Number(value)); + } else if (value.valueOf) { + // support for moment.js + date = new Date(value.valueOf()); + } + + if (!isNaN(date.valueOf())) { + return date; + } + + throw new CastError('date', value, this.path); +}; + +/*! + * Date Query casting. + * + * @api private + */ + +function handleSingle(val) { + return this.cast(val); +} + +SchemaDate.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); + + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaDate.prototype.castForQuery = function($conditional, val) { + var handler; + + if (arguments.length !== 2) { + return this.cast($conditional); + } + + handler = this.$conditionalHandlers[$conditional]; + + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Date.'); + } + + return handler.call(this, val); +}; + +/*! + * Module exports. + */ + +module.exports = SchemaDate; diff --git a/5-3/node_modules/mongoose/lib/schema/documentarray.js b/5-3/node_modules/mongoose/lib/schema/documentarray.js new file mode 100644 index 0000000..e41f674 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/documentarray.js @@ -0,0 +1,290 @@ +/* eslint no-empty: 1 */ + +/*! + * Module dependencies. + */ + +var ArrayType = require('./array'); +var CastError = require('../error/cast'); +var MongooseDocumentArray = require('../types/documentarray'); +var SchemaType = require('../schematype'); +var Subdocument = require('../types/embedded'); + +/** + * SubdocsArray SchemaType constructor + * + * @param {String} key + * @param {Schema} schema + * @param {Object} options + * @inherits SchemaArray + * @api public + */ + +function DocumentArray(key, schema, options) { + // compile an embedded document for this schema + function EmbeddedDocument() { + Subdocument.apply(this, arguments); + } + + EmbeddedDocument.prototype = Object.create(Subdocument.prototype); + EmbeddedDocument.prototype.$__setSchema(schema); + EmbeddedDocument.schema = schema; + + // apply methods + for (var i in schema.methods) { + EmbeddedDocument.prototype[i] = schema.methods[i]; + } + + // apply statics + for (i in schema.statics) { + EmbeddedDocument[i] = schema.statics[i]; + } + + EmbeddedDocument.options = options; + + ArrayType.call(this, key, EmbeddedDocument, options); + + this.schema = schema; + var path = this.path; + var fn = this.defaultValue; + + this.default(function() { + var arr = fn.call(this); + if (!Array.isArray(arr)) { + arr = [arr]; + } + return new MongooseDocumentArray(arr, path, this); + }); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +DocumentArray.schemaName = 'DocumentArray'; + +/*! + * Inherits from ArrayType. + */ +DocumentArray.prototype = Object.create(ArrayType.prototype); +DocumentArray.prototype.constructor = DocumentArray; + +/** + * Performs local validations first, then validations on each embedded doc + * + * @api private + */ + +DocumentArray.prototype.doValidate = function(array, fn, scope, options) { + SchemaType.prototype.doValidate.call(this, array, function(err) { + if (err) { + return fn(err); + } + + var count = array && array.length; + var error; + + if (!count) { + return fn(); + } + if (options && options.updateValidator) { + return fn(); + } + + // handle sparse arrays, do not use array.forEach which does not + // iterate over sparse elements yet reports array.length including + // them :( + + function callback(err) { + if (err) { + error = err; + } + --count || fn(error); + } + + for (var i = 0, len = count; i < len; ++i) { + // sidestep sparse entries + var doc = array[i]; + if (!doc) { + --count || fn(error); + continue; + } + + // HACK: use $__original_validate to avoid promises so bluebird doesn't + // complain + if (doc.$__original_validate) { + doc.$__original_validate({__noPromise: true}, callback); + } else { + doc.validate({__noPromise: true}, callback); + } + } + }, scope); +}; + +/** + * Performs local validations first, then validations on each embedded doc. + * + * ####Note: + * + * This method ignores the asynchronous validators. + * + * @return {MongooseError|undefined} + * @api private + */ + +DocumentArray.prototype.doValidateSync = function(array, scope) { + var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); + if (schemaTypeError) { + return schemaTypeError; + } + + var count = array && array.length, + resultError = null; + + if (!count) { + return; + } + + // handle sparse arrays, do not use array.forEach which does not + // iterate over sparse elements yet reports array.length including + // them :( + + for (var i = 0, len = count; i < len; ++i) { + // only first error + if (resultError) { + break; + } + // sidestep sparse entries + var doc = array[i]; + if (!doc) { + continue; + } + + var subdocValidateError = doc.validateSync(); + + if (subdocValidateError) { + resultError = subdocValidateError; + } + } + + return resultError; +}; + +/** + * Casts contents + * + * @param {Object} value + * @param {Document} document that triggers the casting + * @api private + */ + +DocumentArray.prototype.cast = function(value, doc, init, prev, options) { + var selected, + subdoc, + i; + + if (!Array.isArray(value)) { + // gh-2442 mark whole array as modified if we're initializing a doc from + // the db and the path isn't an array in the document + if (!!doc && init) { + doc.markModified(this.path); + } + return this.cast([value], doc, init, prev); + } + + if (!(value && value.isMongooseDocumentArray) && + (!options || !options.skipDocumentArrayCast)) { + value = new MongooseDocumentArray(value, this.path, doc); + if (prev && prev._handlers) { + for (var key in prev._handlers) { + doc.removeListener(key, prev._handlers[key]); + } + } + } + + i = value.length; + + while (i--) { + if (!value[i]) { + continue; + } + // Check if the document has a different schema (re gh-3701) + if ((value[i] instanceof Subdocument) && + value[i].schema !== this.casterConstructor.schema) { + value[i] = value[i].toObject({virtuals: false}); + } + if (!(value[i] instanceof Subdocument) && value[i]) { + if (init) { + selected || (selected = scopePaths(this, doc.$__.selected, init)); + subdoc = new this.casterConstructor(null, value, true, selected, i); + value[i] = subdoc.init(value[i]); + } else { + try { + subdoc = prev.id(value[i]._id); + } catch (e) { + } + + if (prev && subdoc) { + // handle resetting doc with existing id but differing data + // doc.array = [{ doc: 'val' }] + subdoc.set(value[i]); + // if set() is hooked it will have no return value + // see gh-746 + value[i] = subdoc; + } else { + try { + subdoc = new this.casterConstructor(value[i], value, undefined, + undefined, i); + // if set() is hooked it will have no return value + // see gh-746 + value[i] = subdoc; + } catch (error) { + throw new CastError('embedded', value[i], value._path); + } + } + } + } + } + + return value; +}; + +/*! + * Scopes paths selected in a query to this array. + * Necessary for proper default application of subdocument values. + * + * @param {DocumentArray} array - the array to scope `fields` paths + * @param {Object|undefined} fields - the root fields selected in the query + * @param {Boolean|undefined} init - if we are being created part of a query result + */ + +function scopePaths(array, fields, init) { + if (!(init && fields)) { + return undefined; + } + + var path = array.path + '.', + keys = Object.keys(fields), + i = keys.length, + selected = {}, + hasKeys, + key; + + while (i--) { + key = keys[i]; + if (key.indexOf(path) === 0) { + hasKeys || (hasKeys = true); + selected[key.substring(path.length)] = fields[key]; + } + } + + return hasKeys && selected || undefined; +} + +/*! + * Module exports. + */ + +module.exports = DocumentArray; diff --git a/5-3/node_modules/mongoose/lib/schema/embedded.js b/5-3/node_modules/mongoose/lib/schema/embedded.js new file mode 100644 index 0000000..f0444f5 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/embedded.js @@ -0,0 +1,135 @@ +var SchemaType = require('../schematype'); +var Subdocument = require('../types/subdocument'); + +module.exports = Embedded; + +/** + * Sub-schema schematype constructor + * + * @param {Schema} schema + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function Embedded(schema, path, options) { + var _embedded = function(value, path, parent) { + var _this = this; + Subdocument.apply(this, arguments); + this.$parent = parent; + if (parent) { + parent.on('save', function() { + _this.emit('save', _this); + }); + } + }; + _embedded.prototype = Object.create(Subdocument.prototype); + _embedded.prototype.$__setSchema(schema); + _embedded.schema = schema; + _embedded.$isSingleNested = true; + _embedded.prototype.$basePath = path; + + // apply methods + for (var i in schema.methods) { + _embedded.prototype[i] = schema.methods[i]; + } + + // apply statics + for (i in schema.statics) { + _embedded[i] = schema.statics[i]; + } + + this.caster = _embedded; + this.schema = schema; + this.$isSingleNested = true; + SchemaType.call(this, path, options, 'Embedded'); +} + +Embedded.prototype = Object.create(SchemaType.prototype); + +/** + * Casts contents + * + * @param {Object} value + * @api private + */ + +Embedded.prototype.cast = function(val, doc, init) { + if (val && val.$isSingleNested) { + return val; + } + var subdoc = new this.caster(undefined, undefined, doc); + if (init) { + subdoc.init(val); + } else { + subdoc.set(val, undefined, true); + } + return subdoc; +}; + +/** + * Casts contents for query + * + * @param {string} [$conditional] optional query operator (like `$eq` or `$in`) + * @param {any} value + * @api private + */ + +Embedded.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional); + } + return handler.call(this, val); + } + val = $conditional; + return new this.caster(val).toObject({virtuals: false}); +}; + +/** + * Async validation on this single nested doc. + * + * @api private + */ + +Embedded.prototype.doValidate = function(value, fn) { + SchemaType.prototype.doValidate.call(this, value, function(error) { + if (error) { + return fn(error); + } + if (!value) { + return fn(null); + } + value.validate(fn, {__noPromise: true}); + }); +}; + +/** + * Synchronously validate this single nested doc + * + * @api private + */ + +Embedded.prototype.doValidateSync = function(value) { + var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value); + if (schemaTypeError) { + return schemaTypeError; + } + if (!value) { + return; + } + return value.validateSync(); +}; + +/** + * Required validator for single nested docs + * + * @api private + */ + +Embedded.prototype.checkRequired = function(value) { + return !!value && value.$isSingleNested; +}; diff --git a/5-3/node_modules/mongoose/lib/schema/index.js b/5-3/node_modules/mongoose/lib/schema/index.js new file mode 100644 index 0000000..f2935c1 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/index.js @@ -0,0 +1,30 @@ + +/*! + * Module exports. + */ + +exports.String = require('./string'); + +exports.Number = require('./number'); + +exports.Boolean = require('./boolean'); + +exports.DocumentArray = require('./documentarray'); + +exports.Embedded = require('./embedded'); + +exports.Array = require('./array'); + +exports.Buffer = require('./buffer'); + +exports.Date = require('./date'); + +exports.ObjectId = require('./objectid'); + +exports.Mixed = require('./mixed'); + +// alias + +exports.Oid = exports.ObjectId; +exports.Object = exports.Mixed; +exports.Bool = exports.Boolean; diff --git a/5-3/node_modules/mongoose/lib/schema/mixed.js b/5-3/node_modules/mongoose/lib/schema/mixed.js new file mode 100644 index 0000000..c1b4cab --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/mixed.js @@ -0,0 +1,90 @@ +/*! + * Module dependencies. + */ + +var SchemaType = require('../schematype'); +var utils = require('../utils'); + +/** + * Mixed SchemaType constructor. + * + * @param {String} path + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function Mixed(path, options) { + if (options && options.default) { + var def = options.default; + if (Array.isArray(def) && def.length === 0) { + // make sure empty array defaults are handled + options.default = Array; + } else if (!options.shared && utils.isObject(def) && Object.keys(def).length === 0) { + // prevent odd "shared" objects between documents + options.default = function() { + return {}; + }; + } + } + + SchemaType.call(this, path, options, 'Mixed'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +Mixed.schemaName = 'Mixed'; + +/*! + * Inherits from SchemaType. + */ +Mixed.prototype = Object.create(SchemaType.prototype); +Mixed.prototype.constructor = Mixed; + +/** + * Required validator + * + * @api private + */ + +Mixed.prototype.checkRequired = function(val) { + return (val !== undefined) && (val !== null); +}; + +/** + * Casts `val` for Mixed. + * + * _this is a no-op_ + * + * @param {Object} value to cast + * @api private + */ + +Mixed.prototype.cast = function(val) { + return val; +}; + +/** + * Casts contents for queries. + * + * @param {String} $cond + * @param {any} [val] + * @api private + */ + +Mixed.prototype.castForQuery = function($cond, val) { + if (arguments.length === 2) { + return val; + } + return $cond; +}; + +/*! + * Module exports. + */ + +module.exports = Mixed; diff --git a/5-3/node_modules/mongoose/lib/schema/number.js b/5-3/node_modules/mongoose/lib/schema/number.js new file mode 100644 index 0000000..ff8f500 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/number.js @@ -0,0 +1,287 @@ +/*! + * Module requirements. + */ + +var SchemaType = require('../schematype'); +var CastError = SchemaType.CastError; +var handleBitwiseOperator = require('./operators/bitwise'); +var errorMessages = require('../error').messages; +var utils = require('../utils'); +var Document; + +/** + * Number SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaNumber(key, options) { + SchemaType.call(this, key, options, 'Number'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaNumber.schemaName = 'Number'; + +/*! + * Inherits from SchemaType. + */ +SchemaNumber.prototype = Object.create(SchemaType.prototype); +SchemaNumber.prototype.constructor = SchemaNumber; + +/** + * Required validator for number + * + * @api private + */ + +SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + return typeof value === 'number' || value instanceof Number; +}; + +/** + * Sets a minimum number validator. + * + * ####Example: + * + * var s = new Schema({ n: { type: Number, min: 10 }) + * var M = db.model('M', s) + * var m = new M({ n: 9 }) + * m.save(function (err) { + * console.error(err) // validator error + * m.n = 10; + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MIN} token which will be replaced with the invalid value + * var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; + * var schema = new Schema({ n: { type: Number, min: min }) + * var M = mongoose.model('Measurement', schema); + * var s= new M({ n: 4 }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). + * }) + * + * @param {Number} value minimum number + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaNumber.prototype.min = function(value, message) { + if (this.minValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minValidator; + }, this); + } + + if (value !== null && value !== undefined) { + var msg = message || errorMessages.Number.min; + msg = msg.replace(/{MIN}/, value); + this.validators.push({ + validator: this.minValidator = function(v) { + return v == null || v >= value; + }, + message: msg, + type: 'min', + min: value + }); + } + + return this; +}; + +/** + * Sets a maximum number validator. + * + * ####Example: + * + * var s = new Schema({ n: { type: Number, max: 10 }) + * var M = db.model('M', s) + * var m = new M({ n: 11 }) + * m.save(function (err) { + * console.error(err) // validator error + * m.n = 10; + * m.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAX} token which will be replaced with the invalid value + * var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; + * var schema = new Schema({ n: { type: Number, max: max }) + * var M = mongoose.model('Measurement', schema); + * var s= new M({ n: 4 }); + * s.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). + * }) + * + * @param {Number} maximum number + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaNumber.prototype.max = function(value, message) { + if (this.maxValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxValidator; + }, this); + } + + if (value !== null && value !== undefined) { + var msg = message || errorMessages.Number.max; + msg = msg.replace(/{MAX}/, value); + this.validators.push({ + validator: this.maxValidator = function(v) { + return v == null || v <= value; + }, + message: msg, + type: 'max', + max: value + }); + } + + return this; +}; + +/** + * Casts to number + * + * @param {Object} value value to cast + * @param {Document} doc document that triggers the casting + * @param {Boolean} init + * @api private + */ + +SchemaNumber.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + // wait! we may need to cast this to a document + + if (value === null || value === undefined) { + return value; + } + + // lazy load + Document || (Document = require('./../document')); + + if (value instanceof Document) { + value.$__.wasPopulated = true; + return value; + } + + // setting a populated path + if (typeof value === 'number') { + return value; + } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { + throw new CastError('number', value, this.path); + } + + // Handle the case where user directly sets a populated + // path to a plain object; cast to the Model used in + // the population query. + var path = doc.$__fullPath(this.path); + var owner = doc.ownerDocument ? doc.ownerDocument() : doc; + var pop = owner.populated(path, true); + var ret = new pop.options.model(value); + ret.$__.wasPopulated = true; + return ret; + } + + var val = value && value._id + ? value._id // documents + : value; + + if (!isNaN(val)) { + if (val === null) { + return val; + } + if (val === '') { + return null; + } + if (typeof val === 'string' || typeof val === 'boolean') { + val = Number(val); + } + if (val instanceof Number) { + return val; + } + if (typeof val === 'number') { + return val; + } + if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) { + return new Number(val); + } + } + + throw new CastError('number', value, this.path); +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.cast(val); +} + +function handleArray(val) { + var _this = this; + if (!Array.isArray(val)) { + return [this.cast(val)]; + } + return val.map(function(m) { + return _this.cast(m); + }); +} + +SchemaNumber.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $bitsAllClear: handleBitwiseOperator, + $bitsAnyClear: handleBitwiseOperator, + $bitsAllSet: handleBitwiseOperator, + $bitsAnySet: handleBitwiseOperator, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle, + $mod: handleArray + }); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [value] + * @api private + */ + +SchemaNumber.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with Number.'); + } + return handler.call(this, val); + } + val = this.cast($conditional); + return val; +}; + +/*! + * Module exports. + */ + +module.exports = SchemaNumber; diff --git a/5-3/node_modules/mongoose/lib/schema/objectid.js b/5-3/node_modules/mongoose/lib/schema/objectid.js new file mode 100644 index 0000000..51bcb49 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/objectid.js @@ -0,0 +1,196 @@ +/* eslint no-empty: 1 */ + +/*! + * Module dependencies. + */ + +var SchemaType = require('../schematype'), + CastError = SchemaType.CastError, + oid = require('../types/objectid'), + utils = require('../utils'), + Document; + +/** + * ObjectId SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function ObjectId(key, options) { + SchemaType.call(this, key, options, 'ObjectID'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +ObjectId.schemaName = 'ObjectId'; + +/*! + * Inherits from SchemaType. + */ +ObjectId.prototype = Object.create(SchemaType.prototype); +ObjectId.prototype.constructor = ObjectId; + +/** + * Adds an auto-generated ObjectId default if turnOn is true. + * @param {Boolean} turnOn auto generated ObjectId defaults + * @api public + * @return {SchemaType} this + */ + +ObjectId.prototype.auto = function(turnOn) { + if (turnOn) { + this.default(defaultId); + this.set(resetId); + } + + return this; +}; + +/** + * Check required + * + * @api private + */ + +ObjectId.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + return value instanceof oid; +}; + +/** + * Casts to ObjectId + * + * @param {Object} value + * @param {Object} doc + * @param {Boolean} init whether this is an initialization cast + * @api private + */ + +ObjectId.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + // wait! we may need to cast this to a document + + if (value === null || value === undefined) { + return value; + } + + // lazy load + Document || (Document = require('./../document')); + + if (value instanceof Document) { + value.$__.wasPopulated = true; + return value; + } + + // setting a populated path + if (value instanceof oid) { + return value; + } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { + throw new CastError('ObjectId', value, this.path); + } + + // Handle the case where user directly sets a populated + // path to a plain object; cast to the Model used in + // the population query. + var path = doc.$__fullPath(this.path); + var owner = doc.ownerDocument ? doc.ownerDocument() : doc; + var pop = owner.populated(path, true); + var ret = new pop.options.model(value); + ret.$__.wasPopulated = true; + return ret; + } + + if (value === null || value === undefined) { + return value; + } + + if (value instanceof oid) { + return value; + } + + if (value._id) { + if (value._id instanceof oid) { + return value._id; + } + if (value._id.toString instanceof Function) { + try { + return oid.createFromHexString(value._id.toString()); + } catch (e) { + } + } + } + + if (value.toString instanceof Function) { + try { + return oid.createFromHexString(value.toString()); + } catch (err) { + throw new CastError('ObjectId', value, this.path); + } + } + + throw new CastError('ObjectId', value, this.path); +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.cast(val); +} + +ObjectId.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle + }); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [val] + * @api private + */ + +ObjectId.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with ObjectId.'); + } + return handler.call(this, val); + } + return this.cast($conditional); +}; + +/*! + * ignore + */ + +function defaultId() { + return new oid(); +} + +function resetId(v) { + this.$__._id = null; + return v; +} + +/*! + * Module exports. + */ + +module.exports = ObjectId; diff --git a/5-3/node_modules/mongoose/lib/schema/operators/bitwise.js b/5-3/node_modules/mongoose/lib/schema/operators/bitwise.js new file mode 100644 index 0000000..c1fdd34 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/operators/bitwise.js @@ -0,0 +1,36 @@ +/*! + * Module requirements. + */ + +var CastError = require('../../error/cast'); + +/*! + * ignore + */ + +function handleBitwiseOperator(val) { + var _this = this; + if (Array.isArray(val)) { + return val.map(function(v) { + return _castNumber(_this.path, v); + }); + } else if (Buffer.isBuffer(val)) { + return val; + } + // Assume trying to cast to number + return _castNumber(_this.path, val); +} + +/*! + * ignore + */ + +function _castNumber(path, num) { + var v = Number(num); + if (isNaN(v)) { + throw new CastError('number', num, path); + } + return v; +} + +module.exports = handleBitwiseOperator; diff --git a/5-3/node_modules/mongoose/lib/schema/string.js b/5-3/node_modules/mongoose/lib/schema/string.js new file mode 100644 index 0000000..6213471 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schema/string.js @@ -0,0 +1,504 @@ +/*! + * Module dependencies. + */ + +var SchemaType = require('../schematype'); +var CastError = SchemaType.CastError; +var errorMessages = require('../error').messages; +var utils = require('../utils'); +var Document; + +/** + * String SchemaType constructor. + * + * @param {String} key + * @param {Object} options + * @inherits SchemaType + * @api public + */ + +function SchemaString(key, options) { + this.enumValues = []; + this.regExp = null; + SchemaType.call(this, key, options, 'String'); +} + +/** + * This schema type's name, to defend against minifiers that mangle + * function names. + * + * @api public + */ +SchemaString.schemaName = 'String'; + +/*! + * Inherits from SchemaType. + */ +SchemaString.prototype = Object.create(SchemaType.prototype); +SchemaString.prototype.constructor = SchemaString; + +/** + * Adds an enum validator + * + * ####Example: + * + * var states = 'opening open closing closed'.split(' ') + * var s = new Schema({ state: { type: String, enum: states }}) + * var M = db.model('M', s) + * var m = new M({ state: 'invalid' }) + * m.save(function (err) { + * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. + * m.state = 'open' + * m.save(callback) // success + * }) + * + * // or with custom error messages + * var enu = { + * values: 'opening open closing closed'.split(' '), + * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' + * } + * var s = new Schema({ state: { type: String, enum: enu }) + * var M = db.model('M', s) + * var m = new M({ state: 'invalid' }) + * m.save(function (err) { + * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` + * m.state = 'open' + * m.save(callback) // success + * }) + * + * @param {String|Object} [args...] enumeration values + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.enum = function() { + if (this.enumValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.enumValidator; + }, this); + this.enumValidator = false; + } + + if (arguments[0] === void 0 || arguments[0] === false) { + return this; + } + + var values; + var errorMessage; + + if (utils.isObject(arguments[0])) { + values = arguments[0].values; + errorMessage = arguments[0].message; + } else { + values = arguments; + errorMessage = errorMessages.String.enum; + } + + for (var i = 0; i < values.length; i++) { + if (undefined !== values[i]) { + this.enumValues.push(this.cast(values[i])); + } + } + + var vals = this.enumValues; + this.enumValidator = function(v) { + return undefined === v || ~vals.indexOf(v); + }; + this.validators.push({ + validator: this.enumValidator, + message: errorMessage, + type: 'enum', + enumValues: vals + }); + + return this; +}; + +/** + * Adds a lowercase setter. + * + * ####Example: + * + * var s = new Schema({ email: { type: String, lowercase: true }}) + * var M = db.model('M', s); + * var m = new M({ email: 'SomeEmail@example.COM' }); + * console.log(m.email) // someemail@example.com + * + * @api public + * @return {SchemaType} this + */ + +SchemaString.prototype.lowercase = function() { + return this.set(function(v, self) { + if (typeof v !== 'string') { + v = self.cast(v); + } + if (v) { + return v.toLowerCase(); + } + return v; + }); +}; + +/** + * Adds an uppercase setter. + * + * ####Example: + * + * var s = new Schema({ caps: { type: String, uppercase: true }}) + * var M = db.model('M', s); + * var m = new M({ caps: 'an example' }); + * console.log(m.caps) // AN EXAMPLE + * + * @api public + * @return {SchemaType} this + */ + +SchemaString.prototype.uppercase = function() { + return this.set(function(v, self) { + if (typeof v !== 'string') { + v = self.cast(v); + } + if (v) { + return v.toUpperCase(); + } + return v; + }); +}; + +/** + * Adds a trim setter. + * + * The string value will be trimmed when set. + * + * ####Example: + * + * var s = new Schema({ name: { type: String, trim: true }}) + * var M = db.model('M', s) + * var string = ' some name ' + * console.log(string.length) // 11 + * var m = new M({ name: string }) + * console.log(m.name.length) // 9 + * + * @api public + * @return {SchemaType} this + */ + +SchemaString.prototype.trim = function() { + return this.set(function(v, self) { + if (typeof v !== 'string') { + v = self.cast(v); + } + if (v) { + return v.trim(); + } + return v; + }); +}; + +/** + * Sets a minimum length validator. + * + * ####Example: + * + * var schema = new Schema({ postalCode: { type: String, minlength: 5 }) + * var Address = db.model('Address', schema) + * var address = new Address({ postalCode: '9512' }) + * address.save(function (err) { + * console.error(err) // validator error + * address.postalCode = '95125'; + * address.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length + * var minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).']; + * var schema = new Schema({ postalCode: { type: String, minlength: minlength }) + * var Address = mongoose.model('Address', schema); + * var address = new Address({ postalCode: '9512' }); + * address.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5). + * }) + * + * @param {Number} value minimum string length + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.minlength = function(value, message) { + if (this.minlengthValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.minlengthValidator; + }, this); + } + + if (value !== null && value !== undefined) { + var msg = message || errorMessages.String.minlength; + msg = msg.replace(/{MINLENGTH}/, value); + this.validators.push({ + validator: this.minlengthValidator = function(v) { + return v === null || v.length >= value; + }, + message: msg, + type: 'minlength', + minlength: value + }); + } + + return this; +}; + +/** + * Sets a maximum length validator. + * + * ####Example: + * + * var schema = new Schema({ postalCode: { type: String, maxlength: 9 }) + * var Address = db.model('Address', schema) + * var address = new Address({ postalCode: '9512512345' }) + * address.save(function (err) { + * console.error(err) // validator error + * address.postalCode = '95125'; + * address.save() // success + * }) + * + * // custom error messages + * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length + * var maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).']; + * var schema = new Schema({ postalCode: { type: String, maxlength: maxlength }) + * var Address = mongoose.model('Address', schema); + * var address = new Address({ postalCode: '9512512345' }); + * address.validate(function (err) { + * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9). + * }) + * + * @param {Number} value maximum string length + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.maxlength = function(value, message) { + if (this.maxlengthValidator) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.maxlengthValidator; + }, this); + } + + if (value !== null && value !== undefined) { + var msg = message || errorMessages.String.maxlength; + msg = msg.replace(/{MAXLENGTH}/, value); + this.validators.push({ + validator: this.maxlengthValidator = function(v) { + return v === null || v.length <= value; + }, + message: msg, + type: 'maxlength', + maxlength: value + }); + } + + return this; +}; + +/** + * Sets a regexp validator. + * + * Any value that does not pass `regExp`.test(val) will fail validation. + * + * ####Example: + * + * var s = new Schema({ name: { type: String, match: /^a/ }}) + * var M = db.model('M', s) + * var m = new M({ name: 'I am invalid' }) + * m.validate(function (err) { + * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)." + * m.name = 'apples' + * m.validate(function (err) { + * assert.ok(err) // success + * }) + * }) + * + * // using a custom error message + * var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; + * var s = new Schema({ file: { type: String, match: match }}) + * var M = db.model('M', s); + * var m = new M({ file: 'invalid' }); + * m.validate(function (err) { + * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)" + * }) + * + * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also. + * + * var s = new Schema({ name: { type: String, match: /^a/, required: true }}) + * + * @param {RegExp} regExp regular expression to test against + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaString.prototype.match = function match(regExp, message) { + // yes, we allow multiple match validators + + var msg = message || errorMessages.String.match; + + var matchValidator = function(v) { + if (!regExp) { + return false; + } + + var ret = ((v != null && v !== '') + ? regExp.test(v) + : true); + return ret; + }; + + this.validators.push({ + validator: matchValidator, + message: msg, + type: 'regexp', + regexp: regExp + }); + return this; +}; + +/** + * Check required + * + * @param {String|null|undefined} value + * @api private + */ + +SchemaString.prototype.checkRequired = function checkRequired(value, doc) { + if (SchemaType._isRef(this, value, doc, true)) { + return !!value; + } + return (value instanceof String || typeof value === 'string') && value.length; +}; + +/** + * Casts to String + * + * @api private + */ + +SchemaString.prototype.cast = function(value, doc, init) { + if (SchemaType._isRef(this, value, doc, init)) { + // wait! we may need to cast this to a document + + if (value === null || value === undefined) { + return value; + } + + // lazy load + Document || (Document = require('./../document')); + + if (value instanceof Document) { + value.$__.wasPopulated = true; + return value; + } + + // setting a populated path + if (typeof value === 'string') { + return value; + } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { + throw new CastError('string', value, this.path); + } + + // Handle the case where user directly sets a populated + // path to a plain object; cast to the Model used in + // the population query. + var path = doc.$__fullPath(this.path); + var owner = doc.ownerDocument ? doc.ownerDocument() : doc; + var pop = owner.populated(path, true); + var ret = new pop.options.model(value); + ret.$__.wasPopulated = true; + return ret; + } + + // If null or undefined + if (value === null || value === undefined) { + return value; + } + + if (typeof value !== 'undefined') { + // handle documents being passed + if (value._id && typeof value._id === 'string') { + return value._id; + } + + // Re: gh-647 and gh-3030, we're ok with casting using `toString()` + // **unless** its the default Object.toString, because "[object Object]" + // doesn't really qualify as useful data + if (value.toString && value.toString !== Object.prototype.toString) { + return value.toString(); + } + } + + throw new CastError('string', value, this.path); +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.castForQuery(val); +} + +function handleArray(val) { + var _this = this; + if (!Array.isArray(val)) { + return [this.castForQuery(val)]; + } + return val.map(function(m) { + return _this.castForQuery(m); + }); +} + +SchemaString.prototype.$conditionalHandlers = + utils.options(SchemaType.prototype.$conditionalHandlers, { + $all: handleArray, + $gt: handleSingle, + $gte: handleSingle, + $lt: handleSingle, + $lte: handleSingle, + $options: handleSingle, + $regex: handleSingle + }); + +/** + * Casts contents for queries. + * + * @param {String} $conditional + * @param {any} [val] + * @api private + */ + +SchemaString.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional + ' with String.'); + } + return handler.call(this, val); + } + val = $conditional; + if (Object.prototype.toString.call(val) === '[object RegExp]') { + return val; + } + return this.cast(val); +}; + +/*! + * Module exports. + */ + +module.exports = SchemaString; diff --git a/5-3/node_modules/mongoose/lib/schematype.js b/5-3/node_modules/mongoose/lib/schematype.js new file mode 100644 index 0000000..bfab06b --- /dev/null +++ b/5-3/node_modules/mongoose/lib/schematype.js @@ -0,0 +1,887 @@ +/*! + * Module dependencies. + */ + +var utils = require('./utils'); +var error = require('./error'); +var errorMessages = error.messages; +var CastError = error.CastError; +var ValidatorError = error.ValidatorError; + +/** + * SchemaType constructor + * + * @param {String} path + * @param {Object} [options] + * @param {String} [instance] + * @api public + */ + +function SchemaType(path, options, instance) { + this.path = path; + this.instance = instance; + this.validators = []; + this.setters = []; + this.getters = []; + this.options = options; + this._index = null; + this.selected; + + for (var i in options) { + if (this[i] && typeof this[i] === 'function') { + // { unique: true, index: true } + if (i === 'index' && this._index) { + continue; + } + + var opts = Array.isArray(options[i]) + ? options[i] + : [options[i]]; + + this[i].apply(this, opts); + } + } +} + +/** + * Sets a default value for this SchemaType. + * + * ####Example: + * + * var schema = new Schema({ n: { type: Number, default: 10 }) + * var M = db.model('M', schema) + * var m = new M; + * console.log(m.n) // 10 + * + * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. + * + * ####Example: + * + * // values are cast: + * var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }}) + * var M = db.model('M', schema) + * var m = new M; + * console.log(m.aNumber) // 4.815162342 + * + * // default unique objects for Mixed types: + * var schema = new Schema({ mixed: Schema.Types.Mixed }); + * schema.path('mixed').default(function () { + * return {}; + * }); + * + * // if we don't use a function to return object literals for Mixed defaults, + * // each document will receive a reference to the same object literal creating + * // a "shared" object instance: + * var schema = new Schema({ mixed: Schema.Types.Mixed }); + * schema.path('mixed').default({}); + * var M = db.model('M', schema); + * var m1 = new M; + * m1.mixed.added = 1; + * console.log(m1.mixed); // { added: 1 } + * var m2 = new M; + * console.log(m2.mixed); // { added: 1 } + * + * @param {Function|any} val the default value + * @return {defaultValue} + * @api public + */ + +SchemaType.prototype.default = function(val) { + if (arguments.length === 1) { + this.defaultValue = typeof val === 'function' + ? val + : this.cast(val); + return this; + } else if (arguments.length > 1) { + this.defaultValue = utils.args(arguments); + } + return this.defaultValue; +}; + +/** + * Declares the index options for this schematype. + * + * ####Example: + * + * var s = new Schema({ name: { type: String, index: true }) + * var s = new Schema({ loc: { type: [Number], index: 'hashed' }) + * var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) + * var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) + * var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) + * Schema.path('my.path').index(true); + * Schema.path('my.date').index({ expires: 60 }); + * Schema.path('my.path').index({ unique: true, sparse: true }); + * + * ####NOTE: + * + * _Indexes are created in the background by default. Specify `background: false` to override._ + * + * [Direction doesn't matter for single key indexes](http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes) + * + * @param {Object|Boolean|String} options + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.index = function(options) { + this._index = options; + utils.expires(this._index); + return this; +}; + +/** + * Declares an unique index. + * + * ####Example: + * + * var s = new Schema({ name: { type: String, unique: true }}); + * Schema.path('name').index({ unique: true }); + * + * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ + * + * @param {Boolean} bool + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.unique = function(bool) { + if (this._index === null || this._index === undefined || + typeof this._index === 'boolean') { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = {type: this._index}; + } + + this._index.unique = bool; + return this; +}; + +/** + * Declares a full text index. + * + * ###Example: + * + * var s = new Schema({name : {type: String, text : true }) + * Schema.path('name').index({text : true}); + * @param bool + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.text = function(bool) { + if (this._index === null || this._index === undefined || + typeof this._index === 'boolean') { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = {type: this._index}; + } + + this._index.text = bool; + return this; +}; + +/** + * Declares a sparse index. + * + * ####Example: + * + * var s = new Schema({ name: { type: String, sparse: true }) + * Schema.path('name').index({ sparse: true }); + * + * @param {Boolean} bool + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.sparse = function(bool) { + if (this._index === null || this._index === undefined || + typeof this._index === 'boolean') { + this._index = {}; + } else if (typeof this._index === 'string') { + this._index = {type: this._index}; + } + + this._index.sparse = bool; + return this; +}; + +/** + * Adds a setter to this schematype. + * + * ####Example: + * + * function capitalize (val) { + * if (typeof val !== 'string') val = ''; + * return val.charAt(0).toUpperCase() + val.substring(1); + * } + * + * // defining within the schema + * var s = new Schema({ name: { type: String, set: capitalize }}) + * + * // or by retreiving its SchemaType + * var s = new Schema({ name: String }) + * s.path('name').set(capitalize) + * + * Setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key. + * + * Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. + * + * You can set up email lower case normalization easily via a Mongoose setter. + * + * function toLower (v) { + * return v.toLowerCase(); + * } + * + * var UserSchema = new Schema({ + * email: { type: String, set: toLower } + * }) + * + * var User = db.model('User', UserSchema) + * + * var user = new User({email: 'AVENUE@Q.COM'}) + * console.log(user.email); // 'avenue@q.com' + * + * // or + * var user = new User + * user.email = 'Avenue@Q.com' + * console.log(user.email) // 'avenue@q.com' + * + * As you can see above, setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key. + * + * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ + * + * new Schema({ email: { type: String, lowercase: true }}) + * + * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. + * + * function inspector (val, schematype) { + * if (schematype.options.required) { + * return schematype.path + ' is required'; + * } else { + * return val; + * } + * } + * + * var VirusSchema = new Schema({ + * name: { type: String, required: true, set: inspector }, + * taxonomy: { type: String, set: inspector } + * }) + * + * var Virus = db.model('Virus', VirusSchema); + * var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); + * + * console.log(v.name); // name is required + * console.log(v.taxonomy); // Parvovirinae + * + * @param {Function} fn + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.set = function(fn) { + if (typeof fn !== 'function') { + throw new TypeError('A setter must be a function.'); + } + this.setters.push(fn); + return this; +}; + +/** + * Adds a getter to this schematype. + * + * ####Example: + * + * function dob (val) { + * if (!val) return val; + * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); + * } + * + * // defining within the schema + * var s = new Schema({ born: { type: Date, get: dob }) + * + * // or by retreiving its SchemaType + * var s = new Schema({ born: Date }) + * s.path('born').get(dob) + * + * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. + * + * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: + * + * function obfuscate (cc) { + * return '****-****-****-' + cc.slice(cc.length-4, cc.length); + * } + * + * var AccountSchema = new Schema({ + * creditCardNumber: { type: String, get: obfuscate } + * }); + * + * var Account = db.model('Account', AccountSchema); + * + * Account.findById(id, function (err, found) { + * console.log(found.creditCardNumber); // '****-****-****-1234' + * }); + * + * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. + * + * function inspector (val, schematype) { + * if (schematype.options.required) { + * return schematype.path + ' is required'; + * } else { + * return schematype.path + ' is not'; + * } + * } + * + * var VirusSchema = new Schema({ + * name: { type: String, required: true, get: inspector }, + * taxonomy: { type: String, get: inspector } + * }) + * + * var Virus = db.model('Virus', VirusSchema); + * + * Virus.findById(id, function (err, virus) { + * console.log(virus.name); // name is required + * console.log(virus.taxonomy); // taxonomy is not + * }) + * + * @param {Function} fn + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.get = function(fn) { + if (typeof fn !== 'function') { + throw new TypeError('A getter must be a function.'); + } + this.getters.push(fn); + return this; +}; + +/** + * Adds validator(s) for this document path. + * + * Validators always receive the value to validate as their first argument and must return `Boolean`. Returning `false` means validation failed. + * + * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. + * + * ####Examples: + * + * // make sure every value is equal to "something" + * function validator (val) { + * return val == 'something'; + * } + * new Schema({ name: { type: String, validate: validator }}); + * + * // with a custom error message + * + * var custom = [validator, 'Uh oh, {PATH} does not equal "something".'] + * new Schema({ name: { type: String, validate: custom }}); + * + * // adding many validators at a time + * + * var many = [ + * { validator: validator, msg: 'uh oh' } + * , { validator: anotherValidator, msg: 'failed' } + * ] + * new Schema({ name: { type: String, validate: many }}); + * + * // or utilizing SchemaType methods directly: + * + * var schema = new Schema({ name: 'string' }); + * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); + * + * ####Error message templates: + * + * From the examples above, you may have noticed that error messages support basic templating. There are a few other template keywords besides `{PATH}` and `{VALUE}` too. To find out more, details are available [here](#error_messages_MongooseError-messages) + * + * ####Asynchronous validation: + * + * Passing a validator function that receives two arguments tells mongoose that the validator is an asynchronous validator. The first argument passed to the validator function is the value being validated. The second argument is a callback function that must called when you finish validating the value and passed either `true` or `false` to communicate either success or failure respectively. + * + * schema.path('name').validate(function (value, respond) { + * doStuff(value, function () { + * ... + * respond(false); // validation failed + * }) + * }, '{PATH} failed validation.'); + * + * // or with dynamic message + * + * schema.path('name').validate(function (value, respond) { + * doStuff(value, function () { + * ... + * respond(false, 'this message gets to the validation error'); + * }); + * }, 'this message does not matter'); + * + * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. + * + * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). + * + * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. + * + * var conn = mongoose.createConnection(..); + * conn.on('error', handleError); + * + * var Product = conn.model('Product', yourSchema); + * var dvd = new Product(..); + * dvd.save(); // emits error on the `conn` above + * + * If you desire handling these errors at the Model level, attach an `error` listener to your Model and the event will instead be emitted there. + * + * // registering an error listener on the Model lets us handle errors more locally + * Product.on('error', handleError); + * + * @param {RegExp|Function|Object} obj validator + * @param {String} [errorMsg] optional error message + * @param {String} [type] optional validator type + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.validate = function(obj, message, type) { + if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') { + var properties; + if (message instanceof Object && !type) { + properties = utils.clone(message); + if (!properties.message) { + properties.message = properties.msg; + } + properties.validator = obj; + properties.type = properties.type || 'user defined'; + } else { + if (!message) { + message = errorMessages.general.default; + } + if (!type) { + type = 'user defined'; + } + properties = {message: message, type: type, validator: obj}; + } + this.validators.push(properties); + return this; + } + + var i, + length, + arg; + + for (i = 0, length = arguments.length; i < length; i++) { + arg = arguments[i]; + if (!(arg && utils.getFunctionName(arg.constructor) === 'Object')) { + var msg = 'Invalid validator. Received (' + typeof arg + ') ' + + arg + + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; + + throw new Error(msg); + } + this.validate(arg.validator, arg); + } + + return this; +}; + +/** + * Adds a required validator to this schematype. The required validator is added + * to the front of the validators array using `unshift()`. + * + * ####Example: + * + * var s = new Schema({ born: { type: Date, required: true }) + * + * // or with custom error message + * + * var s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) + * + * // or through the path API + * + * Schema.path('name').required(true); + * + * // with custom error messaging + * + * Schema.path('name').required(true, 'grrr :( '); + * + * + * @param {Boolean} required enable/disable the validator + * @param {String} [message] optional custom error message + * @return {SchemaType} this + * @see Customized Error Messages #error_messages_MongooseError-messages + * @api public + */ + +SchemaType.prototype.required = function(required, message) { + if (required === false) { + this.validators = this.validators.filter(function(v) { + return v.validator !== this.requiredValidator; + }, this); + + this.isRequired = false; + return this; + } + + var _this = this; + this.isRequired = true; + + this.requiredValidator = function(v) { + // in here, `this` refers to the validating document. + // no validation when this path wasn't selected in the query. + if ('isSelected' in this && !this.isSelected(_this.path) && !this.isModified(_this.path)) { + return true; + } + + return ((typeof required === 'function') && !required.apply(this)) || + _this.checkRequired(v, this); + }; + + if (typeof required === 'string') { + message = required; + required = undefined; + } + + var msg = message || errorMessages.general.required; + this.validators.unshift({ + validator: this.requiredValidator, + message: msg, + type: 'required' + }); + + return this; +}; + +/** + * Gets the default value + * + * @param {Object} scope the scope which callback are executed + * @param {Boolean} init + * @api private + */ + +SchemaType.prototype.getDefault = function(scope, init) { + var ret = typeof this.defaultValue === 'function' + ? this.defaultValue.call(scope) + : this.defaultValue; + + if (ret !== null && ret !== undefined) { + return this.cast(ret, scope, init); + } + return ret; +}; + +/** + * Applies setters + * + * @param {Object} value + * @param {Object} scope + * @param {Boolean} init + * @api private + */ + +SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) { + var v = value, + setters = this.setters, + len = setters.length, + caster = this.caster; + + while (len--) { + v = setters[len].call(scope, v, this); + } + + if (Array.isArray(v) && caster && caster.setters) { + var newVal = []; + for (var i = 0; i < v.length; i++) { + newVal.push(caster.applySetters(v[i], scope, init, priorVal)); + } + v = newVal; + } + + if (v === null || v === undefined) { + return v; + } + + // do not cast until all setters are applied #665 + v = this.cast(v, scope, init, priorVal, options); + + return v; +}; + +/** + * Applies getters to a value + * + * @param {Object} value + * @param {Object} scope + * @api private + */ + +SchemaType.prototype.applyGetters = function(value, scope) { + var v = value, + getters = this.getters, + len = getters.length; + + if (!len) { + return v; + } + + while (len--) { + v = getters[len].call(scope, v, this); + } + + return v; +}; + +/** + * Sets default `select()` behavior for this path. + * + * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. + * + * ####Example: + * + * T = db.model('T', new Schema({ x: { type: String, select: true }})); + * T.find(..); // field x will always be selected .. + * // .. unless overridden; + * T.find().select('-x').exec(callback); + * + * @param {Boolean} val + * @return {SchemaType} this + * @api public + */ + +SchemaType.prototype.select = function select(val) { + this.selected = !!val; + return this; +}; + +/** + * Performs a validation of `value` using the validators declared for this SchemaType. + * + * @param {any} value + * @param {Function} callback + * @param {Object} scope + * @api private + */ + +SchemaType.prototype.doValidate = function(value, fn, scope) { + var err = false, + path = this.path, + count = this.validators.length; + + if (!count) { + return fn(null); + } + + var validate = function(ok, validatorProperties) { + if (err) { + return; + } + if (ok === undefined || ok) { + --count || fn(null); + } else { + err = new ValidatorError(validatorProperties); + fn(err); + } + }; + + var _this = this; + this.validators.forEach(function(v) { + if (err) { + return; + } + + var validator = v.validator; + + var validatorProperties = utils.clone(v); + validatorProperties.path = path; + validatorProperties.value = value; + + if (validator instanceof RegExp) { + validate(validator.test(value), validatorProperties); + } else if (typeof validator === 'function') { + if (value === undefined && !_this.isRequired) { + validate(true, validatorProperties); + return; + } + if (validator.length === 2) { + validator.call(scope, value, function(ok, customMsg) { + if (customMsg) { + validatorProperties.message = customMsg; + } + validate(ok, validatorProperties); + }); + } else { + validate(validator.call(scope, value), validatorProperties); + } + } + }); +}; + +/** + * Performs a validation of `value` using the validators declared for this SchemaType. + * + * ####Note: + * + * This method ignores the asynchronous validators. + * + * @param {any} value + * @param {Object} scope + * @return {MongooseError|undefined} + * @api private + */ + +SchemaType.prototype.doValidateSync = function(value, scope) { + var err = null, + path = this.path, + count = this.validators.length; + + if (!count) { + return null; + } + + var validate = function(ok, validatorProperties) { + if (err) { + return; + } + if (ok !== undefined && !ok) { + err = new ValidatorError(validatorProperties); + } + }; + + var _this = this; + if (value === undefined && !_this.isRequired) { + return null; + } + + this.validators.forEach(function(v) { + if (err) { + return; + } + + var validator = v.validator; + var validatorProperties = utils.clone(v); + validatorProperties.path = path; + validatorProperties.value = value; + + if (validator instanceof RegExp) { + validate(validator.test(value), validatorProperties); + } else if (typeof validator === 'function') { + // if not async validators + if (validator.length !== 2) { + validate(validator.call(scope, value), validatorProperties); + } + } + }); + + return err; +}; + +/** + * Determines if value is a valid Reference. + * + * @param {SchemaType} self + * @param {Object} value + * @param {Document} doc + * @param {Boolean} init + * @return {Boolean} + * @api private + */ + +SchemaType._isRef = function(self, value, doc, init) { + // fast path + var ref = init && self.options && self.options.ref; + + if (!ref && doc && doc.$__fullPath) { + // checks for + // - this populated with adhoc model and no ref was set in schema OR + // - setting / pushing values after population + var path = doc.$__fullPath(self.path); + var owner = doc.ownerDocument ? doc.ownerDocument() : doc; + ref = owner.populated(path); + } + + if (ref) { + if (value == null) { + return true; + } + if (!Buffer.isBuffer(value) && // buffers are objects too + value._bsontype !== 'Binary' // raw binary value from the db + && utils.isObject(value) // might have deselected _id in population query + ) { + return true; + } + } + + return false; +}; + +/*! + * ignore + */ + +function handleSingle(val) { + return this.castForQuery(val); +} + +/*! + * ignore + */ + +function handleArray(val) { + var _this = this; + if (!Array.isArray(val)) { + return [this.castForQuery(val)]; + } + return val.map(function(m) { + return _this.castForQuery(m); + }); +} + +/*! + * ignore + */ + +SchemaType.prototype.$conditionalHandlers = { + $all: handleArray, + $eq: handleSingle, + $in: handleArray, + $ne: handleSingle, + $nin: handleArray +}; + +/** + * Cast the given value with the given optional query operator. + * + * @param {String} [$conditional] query operator, like `$eq` or `$in` + * @param {any} val + * @api private + */ + +SchemaType.prototype.castForQuery = function($conditional, val) { + var handler; + if (arguments.length === 2) { + handler = this.$conditionalHandlers[$conditional]; + if (!handler) { + throw new Error('Can\'t use ' + $conditional); + } + return handler.call(this, val); + } + val = $conditional; + return this.cast(val); +}; + +/** + * Default check for if this path satisfies the `required` validator. + * + * @param {any} val + * @api private + */ + +SchemaType.prototype.checkRequired = function(val) { + return val != null; +}; + +/*! + * Module exports. + */ + +module.exports = exports = SchemaType; + +exports.CastError = CastError; + +exports.ValidatorError = ValidatorError; diff --git a/5-3/node_modules/mongoose/lib/services/updateValidators.js b/5-3/node_modules/mongoose/lib/services/updateValidators.js new file mode 100644 index 0000000..fd12989 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/services/updateValidators.js @@ -0,0 +1,204 @@ +/*! + * Module dependencies. + */ + +var async = require('async'); +var ValidationError = require('../error/validation.js'); +var ObjectId = require('../types/objectid'); + +/** + * Applies validators and defaults to update and findOneAndUpdate operations, + * specifically passing a null doc as `this` to validators and defaults + * + * @param {Query} query + * @param {Schema} schema + * @param {Object} castedDoc + * @param {Object} options + * @method runValidatorsOnUpdate + * @api private + */ + +module.exports = function(query, schema, castedDoc, options) { + var keys = Object.keys(castedDoc || {}); + var updatedKeys = {}; + var updatedValues = {}; + var numKeys = keys.length; + var hasDollarUpdate = false; + var modified = {}; + + for (var i = 0; i < numKeys; ++i) { + if (keys[i].charAt(0) === '$') { + modifiedPaths(castedDoc[keys[i]], '', modified); + var flat = flatten(castedDoc[keys[i]]); + var paths = Object.keys(flat); + var numPaths = paths.length; + for (var j = 0; j < numPaths; ++j) { + var updatedPath = paths[j].replace('.$.', '.0.'); + updatedPath = updatedPath.replace(/\.\$$/, '.0'); + if (keys[i] === '$set' || keys[i] === '$setOnInsert') { + updatedValues[updatedPath] = flat[paths[j]]; + } else if (keys[i] === '$unset') { + updatedValues[updatedPath] = undefined; + } + updatedKeys[updatedPath] = true; + } + hasDollarUpdate = true; + } + } + + if (!hasDollarUpdate) { + modifiedPaths(castedDoc, '', modified); + updatedValues = flatten(castedDoc); + updatedKeys = Object.keys(updatedValues); + } + + if (options && options.upsert) { + paths = Object.keys(query._conditions); + numPaths = keys.length; + for (i = 0; i < numPaths; ++i) { + var path = paths[i]; + var condition = query._conditions[path]; + if (condition && typeof condition === 'object') { + var conditionKeys = Object.keys(condition); + var numConditionKeys = conditionKeys.length; + var hasDollarKey = false; + for (j = 0; j < numConditionKeys; ++j) { + if (conditionKeys[j].charAt(0) === '$') { + hasDollarKey = true; + break; + } + } + if (hasDollarKey) { + continue; + } + } + updatedKeys[path] = true; + modified[path] = true; + } + + if (options.setDefaultsOnInsert) { + schema.eachPath(function(path, schemaType) { + if (path === '_id') { + // Ignore _id for now because it causes bugs in 2.4 + return; + } + if (schemaType.$isSingleNested) { + // Only handle nested schemas 1-level deep to avoid infinite + // recursion re: https://github.com/mongodb-js/mongoose-autopopulate/issues/11 + schemaType.schema.eachPath(function(_path, _schemaType) { + if (path === '_id') { + // Ignore _id for now because it causes bugs in 2.4 + return; + } + + var def = _schemaType.getDefault(null, true); + if (!modified[path + '.' + _path] && typeof def !== 'undefined') { + castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; + castedDoc.$setOnInsert[path + '.' + _path] = def; + updatedValues[path + '.' + _path] = def; + } + }); + } else { + var def = schemaType.getDefault(null, true); + if (!modified[path] && typeof def !== 'undefined') { + castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; + castedDoc.$setOnInsert[path] = def; + updatedValues[path] = def; + } + } + }); + } + } + + var updates = Object.keys(updatedValues); + var numUpdates = updates.length; + var validatorsToExecute = []; + var validationErrors = []; + function iter(i) { + var schemaPath = schema._getSchema(updates[i]); + if (schemaPath) { + validatorsToExecute.push(function(callback) { + schemaPath.doValidate( + updatedValues[updates[i]], + function(err) { + if (err) { + err.path = updates[i]; + validationErrors.push(err); + } + callback(null); + }, + options && options.context === 'query' ? query : null, + {updateValidator: true}); + }); + } + } + for (i = 0; i < numUpdates; ++i) { + iter(i); + } + + return function(callback) { + async.parallel(validatorsToExecute, function() { + if (validationErrors.length) { + var err = new ValidationError(null); + for (var i = 0; i < validationErrors.length; ++i) { + err.errors[validationErrors[i].path] = validationErrors[i]; + } + return callback(err); + } + callback(null); + }); + }; +}; + +function modifiedPaths(update, path, result) { + var keys = Object.keys(update); + var numKeys = keys.length; + result = result || {}; + path = path ? path + '.' : ''; + + for (var i = 0; i < numKeys; ++i) { + var key = keys[i]; + var val = update[key]; + + result[path + key] = true; + if (shouldFlatten(val)) { + modifiedPaths(val, path + key, result); + } + } + + return result; +} + +function flatten(update, path) { + var keys = Object.keys(update); + var numKeys = keys.length; + var result = {}; + path = path ? path + '.' : ''; + + for (var i = 0; i < numKeys; ++i) { + var key = keys[i]; + var val = update[key]; + if (shouldFlatten(val)) { + var flat = flatten(val, path + key); + for (var k in flat) { + result[k] = flat[k]; + } + if (Array.isArray(val)) { + result[path + key] = val; + } + } else { + result[path + key] = val; + } + } + + return result; +} + +function shouldFlatten(val) { + return val && + typeof val === 'object' && + !(val instanceof Date) && + !(val instanceof ObjectId) && + (!Array.isArray(val) || val.length > 0) && + !(val instanceof Buffer); +} diff --git a/5-3/node_modules/mongoose/lib/statemachine.js b/5-3/node_modules/mongoose/lib/statemachine.js new file mode 100644 index 0000000..3bba519 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/statemachine.js @@ -0,0 +1,178 @@ + +/*! + * Module dependencies. + */ + +var utils = require('./utils'); + +/*! + * StateMachine represents a minimal `interface` for the + * constructors it builds via StateMachine.ctor(...). + * + * @api private + */ + +var StateMachine = module.exports = exports = function StateMachine() { +}; + +/*! + * StateMachine.ctor('state1', 'state2', ...) + * A factory method for subclassing StateMachine. + * The arguments are a list of states. For each state, + * the constructor's prototype gets state transition + * methods named after each state. These transition methods + * place their path argument into the given state. + * + * @param {String} state + * @param {String} [state] + * @return {Function} subclass constructor + * @private + */ + +StateMachine.ctor = function() { + var states = utils.args(arguments); + + var ctor = function() { + StateMachine.apply(this, arguments); + this.paths = {}; + this.states = {}; + this.stateNames = states; + + var i = states.length, + state; + + while (i--) { + state = states[i]; + this.states[state] = {}; + } + }; + + ctor.prototype = new StateMachine(); + + states.forEach(function(state) { + // Changes the `path`'s state to `state`. + ctor.prototype[state] = function(path) { + this._changeState(path, state); + }; + }); + + return ctor; +}; + +/*! + * This function is wrapped by the state change functions: + * + * - `require(path)` + * - `modify(path)` + * - `init(path)` + * + * @api private + */ + +StateMachine.prototype._changeState = function _changeState(path, nextState) { + var prevBucket = this.states[this.paths[path]]; + if (prevBucket) delete prevBucket[path]; + + this.paths[path] = nextState; + this.states[nextState][path] = true; +}; + +/*! + * ignore + */ + +StateMachine.prototype.clear = function clear(state) { + var keys = Object.keys(this.states[state]), + i = keys.length, + path; + + while (i--) { + path = keys[i]; + delete this.states[state][path]; + delete this.paths[path]; + } +}; + +/*! + * Checks to see if at least one path is in the states passed in via `arguments` + * e.g., this.some('required', 'inited') + * + * @param {String} state that we want to check for. + * @private + */ + +StateMachine.prototype.some = function some() { + var _this = this; + var what = arguments.length ? arguments : this.stateNames; + return Array.prototype.some.call(what, function(state) { + return Object.keys(_this.states[state]).length; + }); +}; + +/*! + * This function builds the functions that get assigned to `forEach` and `map`, + * since both of those methods share a lot of the same logic. + * + * @param {String} iterMethod is either 'forEach' or 'map' + * @return {Function} + * @api private + */ + +StateMachine.prototype._iter = function _iter(iterMethod) { + return function() { + var numArgs = arguments.length, + states = utils.args(arguments, 0, numArgs - 1), + callback = arguments[numArgs - 1]; + + if (!states.length) states = this.stateNames; + + var _this = this; + + var paths = states.reduce(function(paths, state) { + return paths.concat(Object.keys(_this.states[state])); + }, []); + + return paths[iterMethod](function(path, i, paths) { + return callback(path, i, paths); + }); + }; +}; + +/*! + * Iterates over the paths that belong to one of the parameter states. + * + * The function profile can look like: + * this.forEach(state1, fn); // iterates over all paths in state1 + * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 + * this.forEach(fn); // iterates over all paths in all states + * + * @param {String} [state] + * @param {String} [state] + * @param {Function} callback + * @private + */ + +StateMachine.prototype.forEach = function forEach() { + this.forEach = this._iter('forEach'); + return this.forEach.apply(this, arguments); +}; + +/*! + * Maps over the paths that belong to one of the parameter states. + * + * The function profile can look like: + * this.forEach(state1, fn); // iterates over all paths in state1 + * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 + * this.forEach(fn); // iterates over all paths in all states + * + * @param {String} [state] + * @param {String} [state] + * @param {Function} callback + * @return {Array} + * @private + */ + +StateMachine.prototype.map = function map() { + this.map = this._iter('map'); + return this.map.apply(this, arguments); +}; diff --git a/5-3/node_modules/mongoose/lib/types/array.js b/5-3/node_modules/mongoose/lib/types/array.js new file mode 100644 index 0000000..5bb07f2 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/types/array.js @@ -0,0 +1,786 @@ +/*! + * Module dependencies. + */ + +var EmbeddedDocument = require('./embedded'); +var Document = require('../document'); +var ObjectId = require('./objectid'); +var utils = require('../utils'); +var isMongooseObject = utils.isMongooseObject; + +/** + * Mongoose Array constructor. + * + * ####NOTE: + * + * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ + * + * @param {Array} values + * @param {String} path + * @param {Document} doc parent document + * @api private + * @inherits Array + * @see http://bit.ly/f6CnZU + */ + +function MongooseArray(values, path, doc) { + var arr = [].concat(values); + var props = { + isMongooseArray: true, + validators: [], + _path: path, + _atomics: {}, + _schema: void 0 + }; + var tmp = {}; + + var keysMA = Object.keys(MongooseArray.mixin); + for (var i = 0; i < keysMA.length; ++i) { + tmp[keysMA[i]] = {enumerable: false, configurable: true, writable: true, value: MongooseArray.mixin[keysMA[i]]}; + } + + var keysP = Object.keys(props); + for (var j = 0; j < keysP.length; ++j) { + tmp[keysP[j]] = {enumerable: false, configurable: true, writable: true, value: props[keysP[j]]}; + } + + Object.defineProperties(arr, tmp); + + // Because doc comes from the context of another function, doc === global + // can happen if there was a null somewhere up the chain (see #3020) + // RB Jun 17, 2015 updated to check for presence of expected paths instead + // to make more proof against unusual node environments + if (doc && doc instanceof Document) { + arr._parent = doc; + arr._schema = doc.schema.path(path); + } + + return arr; +} + +MongooseArray.mixin = { + + /** + * Stores a queue of atomic operations to perform + * + * @property _atomics + * @api private + */ + + _atomics: undefined, + + /** + * Parent owner document + * + * @property _parent + * @api private + * @receiver MongooseArray + */ + + _parent: undefined, + + /** + * Casts a member based on this arrays schema. + * + * @param {any} value + * @return value the casted value + * @method _cast + * @api private + * @receiver MongooseArray + */ + + _cast: function(value) { + var owner = this._owner; + var populated = false; + var Model; + + if (this._parent) { + // if a populated array, we must cast to the same model + // instance as specified in the original query. + if (!owner) { + owner = this._owner = this._parent.ownerDocument + ? this._parent.ownerDocument() + : this._parent; + } + + populated = owner.populated(this._path, true); + } + + if (populated && value !== null && value !== undefined) { + // cast to the populated Models schema + Model = populated.options.model; + + // only objects are permitted so we can safely assume that + // non-objects are to be interpreted as _id + if (Buffer.isBuffer(value) || + value instanceof ObjectId || !utils.isObject(value)) { + value = {_id: value}; + } + + // gh-2399 + // we should cast model only when it's not a discriminator + var isDisc = value.schema && value.schema.discriminatorMapping && + value.schema.discriminatorMapping.key !== undefined; + if (!isDisc) { + value = new Model(value); + } + return this._schema.caster.cast(value, this._parent, true); + } + + return this._schema.caster.cast(value, this._parent, false); + }, + + /** + * Marks this array as modified. + * + * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) + * + * @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array + * @param {String} embeddedPath the path which changed in the embeddedDoc + * @method _markModified + * @api private + * @receiver MongooseArray + */ + + _markModified: function(elem, embeddedPath) { + var parent = this._parent, + dirtyPath; + + if (parent) { + dirtyPath = this._path; + + if (arguments.length) { + if (embeddedPath != null) { + // an embedded doc bubbled up the change + dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath; + } else { + // directly set an index + dirtyPath = dirtyPath + '.' + elem; + } + } + + parent.markModified(dirtyPath); + } + + return this; + }, + + /** + * Register an atomic operation with the parent. + * + * @param {Array} op operation + * @param {any} val + * @method _registerAtomic + * @api private + * @receiver MongooseArray + */ + + _registerAtomic: function(op, val) { + if (op === '$set') { + // $set takes precedence over all other ops. + // mark entire array modified. + this._atomics = {$set: val}; + return this; + } + + var atomics = this._atomics; + + // reset pop/shift after save + if (op === '$pop' && !('$pop' in atomics)) { + var _this = this; + this._parent.once('save', function() { + _this._popped = _this._shifted = null; + }); + } + + // check for impossible $atomic combos (Mongo denies more than one + // $atomic op on a single path + if (this._atomics.$set || + Object.keys(atomics).length && !(op in atomics)) { + // a different op was previously registered. + // save the entire thing. + this._atomics = {$set: this}; + return this; + } + + var selector; + + if (op === '$pullAll' || op === '$pushAll' || op === '$addToSet') { + atomics[op] || (atomics[op] = []); + atomics[op] = atomics[op].concat(val); + } else if (op === '$pullDocs') { + var pullOp = atomics['$pull'] || (atomics['$pull'] = {}); + if (val[0] instanceof EmbeddedDocument) { + selector = pullOp['$or'] || (pullOp['$or'] = []); + Array.prototype.push.apply(selector, val.map(function(v) { + return v.toObject({virtuals: false}); + })); + } else { + selector = pullOp['_id'] || (pullOp['_id'] = {$in: []}); + selector['$in'] = selector['$in'].concat(val); + } + } else { + atomics[op] = val; + } + + return this; + }, + + /** + * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. + * + * If no atomics exist, we return all array values after conversion. + * + * @return {Array} + * @method $__getAtomics + * @memberOf MongooseArray + * @api private + */ + + $__getAtomics: function() { + var ret = []; + var keys = Object.keys(this._atomics); + var i = keys.length; + + if (i === 0) { + ret[0] = ['$set', this.toObject({depopulate: 1, transform: false})]; + return ret; + } + + while (i--) { + var op = keys[i]; + var val = this._atomics[op]; + + // the atomic values which are arrays are not MongooseArrays. we + // need to convert their elements as if they were MongooseArrays + // to handle populated arrays versus DocumentArrays properly. + if (isMongooseObject(val)) { + val = val.toObject({depopulate: 1, transform: false}); + } else if (Array.isArray(val)) { + val = this.toObject.call(val, {depopulate: 1, transform: false}); + } else if (val.valueOf) { + val = val.valueOf(); + } + + if (op === '$addToSet') { + val = {$each: val}; + } + + ret.push([op, val]); + } + + return ret; + }, + + /** + * Returns the number of pending atomic operations to send to the db for this array. + * + * @api private + * @return {Number} + * @method hasAtomics + * @receiver MongooseArray + */ + + hasAtomics: function hasAtomics() { + if (!(this._atomics && this._atomics.constructor.name === 'Object')) { + return 0; + } + + return Object.keys(this._atomics).length; + }, + + /** + * Internal helper for .map() + * + * @api private + * @return {Number} + * @method _mapCast + * @receiver MongooseArray + */ + _mapCast: function(val, index) { + return this._cast(val, this.length + index); + }, + + /** + * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. + * + * @param {Object} [args...] + * @api public + * @method push + * @receiver MongooseArray + */ + + push: function() { + var values = [].map.call(arguments, this._mapCast, this); + values = this._schema.applySetters(values, this._parent, undefined, + undefined, {skipDocumentArrayCast: true}); + var ret = [].push.apply(this, values); + + // $pushAll might be fibbed (could be $push). But it makes it easier to + // handle what could have been $push, $pushAll combos + this._registerAtomic('$pushAll', values); + this._markModified(); + return ret; + }, + + /** + * Pushes items to the array non-atomically. + * + * ####NOTE: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @param {any} [args...] + * @api public + * @method nonAtomicPush + * @receiver MongooseArray + */ + + nonAtomicPush: function() { + var values = [].map.call(arguments, this._mapCast, this); + var ret = [].push.apply(this, values); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Pops the array atomically at most one time per document `save()`. + * + * #### NOTE: + * + * _Calling this mulitple times on an array before saving sends the same command as calling it once._ + * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ + * + * doc.array = [1,2,3]; + * + * var popped = doc.array.$pop(); + * console.log(popped); // 3 + * console.log(doc.array); // [1,2] + * + * // no affect + * popped = doc.array.$pop(); + * console.log(doc.array); // [1,2] + * + * doc.save(function (err) { + * if (err) return handleError(err); + * + * // we saved, now $pop works again + * popped = doc.array.$pop(); + * console.log(popped); // 2 + * console.log(doc.array); // [1] + * }) + * + * @api public + * @method $pop + * @memberOf MongooseArray + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop + * @method $pop + * @receiver MongooseArray + */ + + $pop: function() { + this._registerAtomic('$pop', 1); + this._markModified(); + + // only allow popping once + if (this._popped) { + return; + } + this._popped = true; + + return [].pop.call(this); + }, + + /** + * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. + * + * ####Note: + * + * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @see MongooseArray#$pop #types_array_MongooseArray-%24pop + * @api public + * @method pop + * @receiver MongooseArray + */ + + pop: function() { + var ret = [].pop.call(this); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Atomically shifts the array at most one time per document `save()`. + * + * ####NOTE: + * + * _Calling this mulitple times on an array before saving sends the same command as calling it once._ + * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ + * + * doc.array = [1,2,3]; + * + * var shifted = doc.array.$shift(); + * console.log(shifted); // 1 + * console.log(doc.array); // [2,3] + * + * // no affect + * shifted = doc.array.$shift(); + * console.log(doc.array); // [2,3] + * + * doc.save(function (err) { + * if (err) return handleError(err); + * + * // we saved, now $shift works again + * shifted = doc.array.$shift(); + * console.log(shifted ); // 2 + * console.log(doc.array); // [3] + * }) + * + * @api public + * @memberOf MongooseArray + * @method $shift + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop + */ + + $shift: function $shift() { + this._registerAtomic('$pop', -1); + this._markModified(); + + // only allow shifting once + if (this._shifted) { + return; + } + this._shifted = true; + + return [].shift.call(this); + }, + + /** + * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + * + * ####Example: + * + * doc.array = [2,3]; + * var res = doc.array.shift(); + * console.log(res) // 2 + * console.log(doc.array) // [3] + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method shift + * @receiver MongooseArray + */ + + shift: function() { + var ret = [].shift.call(this); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Pulls items from the array atomically. Equality is determined by casting + * the provided value to an embedded document and comparing using + * [the `Document.equals()` function.](./api.html#document_Document-equals) + * + * ####Examples: + * + * doc.array.pull(ObjectId) + * doc.array.pull({ _id: 'someId' }) + * doc.array.pull(36) + * doc.array.pull('tag 1', 'tag 2') + * + * To remove a document from a subdocument array we may pass an object with a matching `_id`. + * + * doc.subdocs.push({ _id: 4815162342 }) + * doc.subdocs.pull({ _id: 4815162342 }) // removed + * + * Or we may passing the _id directly and let mongoose take care of it. + * + * doc.subdocs.push({ _id: 4815162342 }) + * doc.subdocs.pull(4815162342); // works + * + * @param {any} [args...] + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull + * @api public + * @method pull + * @receiver MongooseArray + */ + + pull: function() { + var values = [].map.call(arguments, this._cast, this), + cur = this._parent.get(this._path), + i = cur.length, + mem; + + while (i--) { + mem = cur[i]; + if (mem instanceof Document) { + var some = values.some(function(v) { + return v.equals(mem); + }); + if (some) { + [].splice.call(cur, i, 1); + } + } else if (~cur.indexOf.call(values, mem)) { + [].splice.call(cur, i, 1); + } + } + + if (values[0] instanceof EmbeddedDocument) { + this._registerAtomic('$pullDocs', values.map(function(v) { + return v._id || v; + })); + } else { + this._registerAtomic('$pullAll', values); + } + + this._markModified(); + return this; + }, + + /** + * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method splice + * @receiver MongooseArray + */ + + splice: function splice() { + var ret, vals, i; + + if (arguments.length) { + vals = []; + for (i = 0; i < arguments.length; ++i) { + vals[i] = i < 2 + ? arguments[i] + : this._cast(arguments[i], arguments[0] + (i - 2)); + } + ret = [].splice.apply(this, vals); + this._registerAtomic('$set', this); + this._markModified(); + } + + return ret; + }, + + /** + * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. + * + * ####Note: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method unshift + * @receiver MongooseArray + */ + + unshift: function() { + var values = [].map.call(arguments, this._cast, this); + values = this._schema.applySetters(values, this._parent); + [].unshift.apply(this, values); + this._registerAtomic('$set', this); + this._markModified(); + return this.length; + }, + + /** + * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. + * + * ####NOTE: + * + * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ + * + * @api public + * @method sort + * @receiver MongooseArray + */ + + sort: function() { + var ret = [].sort.apply(this, arguments); + this._registerAtomic('$set', this); + this._markModified(); + return ret; + }, + + /** + * Adds values to the array if not already present. + * + * ####Example: + * + * console.log(doc.array) // [2,3,4] + * var added = doc.array.addToSet(4,5); + * console.log(doc.array) // [2,3,4,5] + * console.log(added) // [5] + * + * @param {any} [args...] + * @return {Array} the values that were added + * @receiver MongooseArray + * @api public + * @method addToSet + */ + + addToSet: function addToSet() { + var values = [].map.call(arguments, this._mapCast, this); + values = this._schema.applySetters(values, this._parent); + var added = []; + var type = ''; + if (values[0] instanceof EmbeddedDocument) { + type = 'doc'; + } else if (values[0] instanceof Date) { + type = 'date'; + } + + values.forEach(function(v) { + var found; + switch (type) { + case 'doc': + found = this.some(function(doc) { + return doc.equals(v); + }); + break; + case 'date': + var val = +v; + found = this.some(function(d) { + return +d === val; + }); + break; + default: + found = ~this.indexOf(v); + } + + if (!found) { + [].push.call(this, v); + this._registerAtomic('$addToSet', v); + this._markModified(); + [].push.call(added, v); + } + }, this); + + return added; + }, + + /** + * Sets the casted `val` at index `i` and marks the array modified. + * + * ####Example: + * + * // given documents based on the following + * var Doc = mongoose.model('Doc', new Schema({ array: [Number] })); + * + * var doc = new Doc({ array: [2,3,4] }) + * + * console.log(doc.array) // [2,3,4] + * + * doc.array.set(1,"5"); + * console.log(doc.array); // [2,5,4] // properly cast to number + * doc.save() // the change is saved + * + * // VS not using array#set + * doc.array[1] = "5"; + * console.log(doc.array); // [2,"5",4] // no casting + * doc.save() // change is not saved + * + * @return {Array} this + * @api public + * @method set + * @receiver MongooseArray + */ + + set: function set(i, val) { + var value = this._cast(val, i); + value = this._schema.caster instanceof EmbeddedDocument ? + value : + this._schema.caster.applySetters(val, this._parent) + ; + this[i] = value; + this._markModified(i); + return this; + }, + + /** + * Returns a native js Array. + * + * @param {Object} options + * @return {Array} + * @api public + * @method toObject + * @receiver MongooseArray + */ + + toObject: function(options) { + if (options && options.depopulate) { + return this.map(function(doc) { + return doc instanceof Document + ? doc.toObject(options) + : doc; + }); + } + + return this.slice(); + }, + + /** + * Helper for console.log + * + * @api public + * @method inspect + * @receiver MongooseArray + */ + + inspect: function() { + return JSON.stringify(this); + }, + + /** + * Return the index of `obj` or `-1` if not found. + * + * @param {Object} obj the item to look for + * @return {Number} + * @api public + * @method indexOf + * @receiver MongooseArray + */ + + indexOf: function indexOf(obj) { + if (obj instanceof ObjectId) { + obj = obj.toString(); + } + for (var i = 0, len = this.length; i < len; ++i) { + if (obj == this[i]) { + return i; + } + } + return -1; + } +}; + +/** + * Alias of [pull](#types_array_MongooseArray-pull) + * + * @see MongooseArray#pull #types_array_MongooseArray-pull + * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull + * @api public + * @memberOf MongooseArray + * @method remove + */ + +MongooseArray.mixin.remove = MongooseArray.mixin.pull; + +/*! + * Module exports. + */ + +module.exports = exports = MongooseArray; diff --git a/5-3/node_modules/mongoose/lib/types/buffer.js b/5-3/node_modules/mongoose/lib/types/buffer.js new file mode 100644 index 0000000..0c7bbe3 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/types/buffer.js @@ -0,0 +1,273 @@ +/*! + * Module dependencies. + */ + +var Binary = require('../drivers').Binary, + utils = require('../utils'); + +/** + * Mongoose Buffer constructor. + * + * Values always have to be passed to the constructor to initialize. + * + * @param {Buffer} value + * @param {String} encode + * @param {Number} offset + * @api private + * @inherits Buffer + * @see http://bit.ly/f6CnZU + */ + +function MongooseBuffer(value, encode, offset) { + var length = arguments.length; + var val; + + if (length === 0 || arguments[0] === null || arguments[0] === undefined) { + val = 0; + } else { + val = value; + } + + var encoding; + var path; + var doc; + + if (Array.isArray(encode)) { + // internal casting + path = encode[0]; + doc = encode[1]; + } else { + encoding = encode; + } + + var buf = new Buffer(val, encoding, offset); + utils.decorate(buf, MongooseBuffer.mixin); + buf.isMongooseBuffer = true; + + // make sure these internal props don't show up in Object.keys() + Object.defineProperties(buf, { + validators: {value: []}, + _path: {value: path}, + _parent: {value: doc} + }); + + if (doc && typeof path === 'string') { + Object.defineProperty(buf, '_schema', { + value: doc.schema.path(path) + }); + } + + buf._subtype = 0; + return buf; +} + +/*! + * Inherit from Buffer. + */ + +// MongooseBuffer.prototype = new Buffer(0); + +MongooseBuffer.mixin = { + + /** + * Parent owner document + * + * @api private + * @property _parent + * @receiver MongooseBuffer + */ + + _parent: undefined, + + /** + * Default subtype for the Binary representing this Buffer + * + * @api private + * @property _subtype + * @receiver MongooseBuffer + */ + + _subtype: undefined, + + /** + * Marks this buffer as modified. + * + * @api private + * @method _markModified + * @receiver MongooseBuffer + */ + + _markModified: function() { + var parent = this._parent; + + if (parent) { + parent.markModified(this._path); + } + return this; + }, + + /** + * Writes the buffer. + * + * @api public + * @method write + * @receiver MongooseBuffer + */ + + write: function() { + var written = Buffer.prototype.write.apply(this, arguments); + + if (written > 0) { + this._markModified(); + } + + return written; + }, + + /** + * Copies the buffer. + * + * ####Note: + * + * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. + * + * @return {MongooseBuffer} + * @param {Buffer} target + * @method copy + * @receiver MongooseBuffer + */ + + copy: function(target) { + var ret = Buffer.prototype.copy.apply(this, arguments); + + if (target && target.isMongooseBuffer) { + target._markModified(); + } + + return ret; + } +}; + +/*! + * Compile other Buffer methods marking this buffer as modified. + */ + +( +// node < 0.5 + 'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' + + 'writeFloat writeDouble fill ' + + 'utf8Write binaryWrite asciiWrite set ' + + +// node >= 0.5 + 'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' + + 'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' + + 'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE' +).split(' ').forEach(function(method) { + if (!Buffer.prototype[method]) { + return; + } + MongooseBuffer.mixin[method] = function() { + var ret = Buffer.prototype[method].apply(this, arguments); + this._markModified(); + return ret; + }; +}); + +/** + * Converts this buffer to its Binary type representation. + * + * ####SubTypes: + * + * var bson = require('bson') + * bson.BSON_BINARY_SUBTYPE_DEFAULT + * bson.BSON_BINARY_SUBTYPE_FUNCTION + * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY + * bson.BSON_BINARY_SUBTYPE_UUID + * bson.BSON_BINARY_SUBTYPE_MD5 + * bson.BSON_BINARY_SUBTYPE_USER_DEFINED + * + * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED); + * + * @see http://bsonspec.org/#/specification + * @param {Hex} [subtype] + * @return {Binary} + * @api public + * @method toObject + * @receiver MongooseBuffer + */ + +MongooseBuffer.mixin.toObject = function(options) { + var subtype = typeof options === 'number' + ? options + : (this._subtype || 0); + return new Binary(this, subtype); +}; + +/** + * Determines if this buffer is equals to `other` buffer + * + * @param {Buffer} other + * @return {Boolean} + * @method equals + * @receiver MongooseBuffer + */ + +MongooseBuffer.mixin.equals = function(other) { + if (!Buffer.isBuffer(other)) { + return false; + } + + if (this.length !== other.length) { + return false; + } + + for (var i = 0; i < this.length; ++i) { + if (this[i] !== other[i]) { + return false; + } + } + + return true; +}; + +/** + * Sets the subtype option and marks the buffer modified. + * + * ####SubTypes: + * + * var bson = require('bson') + * bson.BSON_BINARY_SUBTYPE_DEFAULT + * bson.BSON_BINARY_SUBTYPE_FUNCTION + * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY + * bson.BSON_BINARY_SUBTYPE_UUID + * bson.BSON_BINARY_SUBTYPE_MD5 + * bson.BSON_BINARY_SUBTYPE_USER_DEFINED + * + * doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID); + * + * @see http://bsonspec.org/#/specification + * @param {Hex} subtype + * @api public + * @method subtype + * @receiver MongooseBuffer + */ + +MongooseBuffer.mixin.subtype = function(subtype) { + if (typeof subtype !== 'number') { + throw new TypeError('Invalid subtype. Expected a number'); + } + + if (this._subtype !== subtype) { + this._markModified(); + } + + this._subtype = subtype; +}; + +/*! + * Module exports. + */ + +MongooseBuffer.Binary = Binary; + +module.exports = MongooseBuffer; diff --git a/5-3/node_modules/mongoose/lib/types/documentarray.js b/5-3/node_modules/mongoose/lib/types/documentarray.js new file mode 100644 index 0000000..5382b35 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/types/documentarray.js @@ -0,0 +1,245 @@ +/*! + * Module dependencies. + */ + +var MongooseArray = require('./array'), + ObjectId = require('./objectid'), + ObjectIdSchema = require('../schema/objectid'), + utils = require('../utils'), + Document = require('../document'); + +/** + * DocumentArray constructor + * + * @param {Array} values + * @param {String} path the path to this array + * @param {Document} doc parent document + * @api private + * @return {MongooseDocumentArray} + * @inherits MongooseArray + * @see http://bit.ly/f6CnZU + */ + +function MongooseDocumentArray(values, path, doc) { + var arr = [].concat(values); + var props = { + isMongooseArray: true, + isMongooseDocumentArray: true, + validators: [], + _path: path, + _atomics: {}, + _schema: void 0, + _handlers: void 0 + }; + var tmp = {}; + + // Values always have to be passed to the constructor to initialize, since + // otherwise MongooseArray#push will mark the array as modified to the parent. + var keysMA = Object.keys(MongooseArray.mixin); + for (var j = 0; j < keysMA.length; ++j) { + tmp[keysMA[j]] = {enumerable: false, configurable: true, writable: true, value: MongooseArray.mixin[keysMA[j]]}; + } + + var keysMDA = Object.keys(MongooseDocumentArray.mixin); + for (var i = 0; i < keysMDA.length; ++i) { + tmp[keysMDA[i]] = {enumerable: false, configurable: true, writable: true, value: MongooseDocumentArray.mixin[keysMDA[i]]}; + } + + var keysP = Object.keys(props); + for (var k = 0; k < keysP.length; ++k) { + tmp[keysP[k]] = {enumerable: false, configurable: true, writable: true, value: props[keysP[k]]}; + } + + Object.defineProperties(arr, tmp); + + // Because doc comes from the context of another function, doc === global + // can happen if there was a null somewhere up the chain (see #3020 && #3034) + // RB Jun 17, 2015 updated to check for presence of expected paths instead + // to make more proof against unusual node environments + if (doc && doc instanceof Document) { + arr._parent = doc; + arr._schema = doc.schema.path(path); + arr._handlers = { + isNew: arr.notify('isNew'), + save: arr.notify('save') + }; + + doc.on('save', arr._handlers.save); + doc.on('isNew', arr._handlers.isNew); + } + + return arr; +} + +/*! + * Inherits from MongooseArray + */ +// MongooseDocumentArray.mixin = Object.create( MongooseArray.mixin ); +MongooseDocumentArray.mixin = { + + /** + * Overrides MongooseArray#cast + * + * @method _cast + * @api private + * @receiver MongooseDocumentArray + */ + + _cast: function(value, index) { + if (value instanceof this._schema.casterConstructor) { + if (!(value.__parent && value.__parentArray)) { + // value may have been created using array.create() + value.__parent = this._parent; + value.__parentArray = this; + } + value.__index = index; + return value; + } + + // handle cast('string') or cast(ObjectId) etc. + // only objects are permitted so we can safely assume that + // non-objects are to be interpreted as _id + if (Buffer.isBuffer(value) || + value instanceof ObjectId || !utils.isObject(value)) { + value = {_id: value}; + } + return new this._schema.casterConstructor(value, this, undefined, undefined, index); + }, + + /** + * Searches array items for the first document with a matching _id. + * + * ####Example: + * + * var embeddedDoc = m.array.id(some_id); + * + * @return {EmbeddedDocument|null} the subdocument or null if not found. + * @param {ObjectId|String|Number|Buffer} id + * @TODO cast to the _id based on schema for proper comparison + * @method id + * @api public + * @receiver MongooseDocumentArray + */ + + id: function(id) { + var casted, + sid, + _id; + + try { + var casted_ = ObjectIdSchema.prototype.cast.call({}, id); + if (casted_) { + casted = String(casted_); + } + } catch (e) { + casted = null; + } + + for (var i = 0, l = this.length; i < l; i++) { + _id = this[i].get('_id'); + + if (_id === null || typeof _id === 'undefined') { + continue; + } else if (_id instanceof Document) { + sid || (sid = String(id)); + if (sid == _id._id) { + return this[i]; + } + } else if (!(_id instanceof ObjectId)) { + if (utils.deepEqual(id, _id)) { + return this[i]; + } + } else if (casted == _id) { + return this[i]; + } + } + + return null; + }, + + /** + * Returns a native js Array of plain js objects + * + * ####NOTE: + * + * _Each sub-document is converted to a plain object by calling its `#toObject` method._ + * + * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion + * @return {Array} + * @method toObject + * @api public + * @receiver MongooseDocumentArray + */ + + toObject: function(options) { + return this.map(function(doc) { + return doc && doc.toObject(options) || null; + }); + }, + + /** + * Helper for console.log + * + * @method inspect + * @api public + * @receiver MongooseDocumentArray + */ + + inspect: function() { + return Array.prototype.slice.call(this); + }, + + /** + * Creates a subdocument casted to this schema. + * + * This is the same subdocument constructor used for casting. + * + * @param {Object} obj the value to cast to this arrays SubDocument schema + * @method create + * @api public + * @receiver MongooseDocumentArray + */ + + create: function(obj) { + return new this._schema.casterConstructor(obj); + }, + + /** + * Creates a fn that notifies all child docs of `event`. + * + * @param {String} event + * @return {Function} + * @method notify + * @api private + * @receiver MongooseDocumentArray + */ + + notify: function notify(event) { + var _this = this; + return function notify(val) { + var i = _this.length; + while (i--) { + if (!_this[i]) { + continue; + } + switch (event) { + // only swap for save event for now, we may change this to all event types later + case 'save': + val = _this[i]; + break; + default: + // NO-OP + break; + } + _this[i].emit(event, val); + } + }; + } + +}; + +/*! + * Module exports. + */ + +module.exports = MongooseDocumentArray; diff --git a/5-3/node_modules/mongoose/lib/types/embedded.js b/5-3/node_modules/mongoose/lib/types/embedded.js new file mode 100644 index 0000000..feecf12 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/types/embedded.js @@ -0,0 +1,319 @@ +/* eslint no-func-assign: 1 */ + +/*! + * Module dependencies. + */ + +var Document = require('../document_provider')(); +var PromiseProvider = require('../promise_provider'); + +/** + * EmbeddedDocument constructor. + * + * @param {Object} obj js object returned from the db + * @param {MongooseDocumentArray} parentArr the parent array of this document + * @param {Boolean} skipId + * @inherits Document + * @api private + */ + +function EmbeddedDocument(obj, parentArr, skipId, fields, index) { + if (parentArr) { + this.__parentArray = parentArr; + this.__parent = parentArr._parent; + } else { + this.__parentArray = undefined; + this.__parent = undefined; + } + this.__index = index; + + Document.call(this, obj, fields, skipId); + + var _this = this; + this.on('isNew', function(val) { + _this.isNew = val; + }); +} + +/*! + * Inherit from Document + */ +EmbeddedDocument.prototype = Object.create(Document.prototype); +EmbeddedDocument.prototype.constructor = EmbeddedDocument; + +/** + * Marks the embedded doc modified. + * + * ####Example: + * + * var doc = blogpost.comments.id(hexstring); + * doc.mixed.type = 'changed'; + * doc.markModified('mixed.type'); + * + * @param {String} path the path which changed + * @api public + * @receiver EmbeddedDocument + */ + +EmbeddedDocument.prototype.markModified = function(path) { + this.$__.activePaths.modify(path); + if (!this.__parentArray) { + return; + } + + if (this.isNew) { + // Mark the WHOLE parent array as modified + // if this is a new document (i.e., we are initializing + // a document), + this.__parentArray._markModified(); + } else { + this.__parentArray._markModified(this, path); + } +}; + +/** + * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) + * + * ####NOTE: + * + * _This is a no-op. Does not actually save the doc to the db._ + * + * @param {Function} [fn] + * @return {Promise} resolved Promise + * @api private + */ + +EmbeddedDocument.prototype.save = function(fn) { + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve) { + fn && fn(); + resolve(); + }); +}; + +/*! + * Registers remove event listeners for triggering + * on subdocuments. + * + * @param {EmbeddedDocument} sub + * @api private + */ + +function registerRemoveListener(sub) { + var owner = sub.ownerDocument(); + + function emitRemove() { + owner.removeListener('save', emitRemove); + owner.removeListener('remove', emitRemove); + sub.emit('remove', sub); + owner = sub = null; + } + + owner.on('save', emitRemove); + owner.on('remove', emitRemove); +} + +/** + * Removes the subdocument from its parent array. + * + * @param {Function} [fn] + * @api public + */ + +EmbeddedDocument.prototype.remove = function(fn) { + if (!this.__parentArray) { + return this; + } + + var _id; + if (!this.willRemove) { + _id = this._doc._id; + if (!_id) { + throw new Error('For your own good, Mongoose does not know ' + + 'how to remove an EmbeddedDocument that has no _id'); + } + this.__parentArray.pull({_id: _id}); + this.willRemove = true; + registerRemoveListener(this); + } + + if (fn) { + fn(null); + } + + return this; +}; + +/** + * Override #update method of parent documents. + * @api private + */ + +EmbeddedDocument.prototype.update = function() { + throw new Error('The #update method is not available on EmbeddedDocuments'); +}; + +/** + * Helper for console.log + * + * @api public + */ + +EmbeddedDocument.prototype.inspect = function() { + return this.toObject(); +}; + +/** + * Marks a path as invalid, causing validation to fail. + * + * @param {String} path the field to invalidate + * @param {String|Error} err error which states the reason `path` was invalid + * @return {Boolean} + * @api public + */ + +EmbeddedDocument.prototype.invalidate = function(path, err, val, first) { + if (!this.__parent) { + var msg = 'Unable to invalidate a subdocument that has not been added to an array.'; + throw new Error(msg); + } + + var index = this.__index; + if (typeof index !== 'undefined') { + var parentPath = this.__parentArray._path; + var fullPath = [parentPath, index, path].join('.'); + this.__parent.invalidate(fullPath, err, val); + } + + if (first) { + this.$__.validationError = this.ownerDocument().$__.validationError; + } + + return true; +}; + +/** + * Marks a path as valid, removing existing validation errors. + * + * @param {String} path the field to mark as valid + * @api private + * @method $markValid + * @receiver EmbeddedDocument + */ + +EmbeddedDocument.prototype.$markValid = function(path) { + if (!this.__parent) { + return; + } + + var index = this.__index; + if (typeof index !== 'undefined') { + var parentPath = this.__parentArray._path; + var fullPath = [parentPath, index, path].join('.'); + this.__parent.$markValid(fullPath); + } +}; + +/** + * Checks if a path is invalid + * + * @param {String} path the field to check + * @api private + * @method $isValid + * @receiver EmbeddedDocument + */ + +EmbeddedDocument.prototype.$isValid = function(path) { + var index = this.__index; + if (typeof index !== 'undefined') { + return !this.__parent.$__.validationError || !this.__parent.$__.validationError.errors[path]; + } + + return true; +}; + +/** + * Returns the top level document of this sub-document. + * + * @return {Document} + */ + +EmbeddedDocument.prototype.ownerDocument = function() { + if (this.$__.ownerDocument) { + return this.$__.ownerDocument; + } + + var parent = this.__parent; + if (!parent) { + return this; + } + + while (parent.__parent) { + parent = parent.__parent; + } + + this.$__.ownerDocument = parent; + return this.$__.ownerDocument; +}; + +/** + * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. + * + * @param {String} [path] + * @return {String} + * @api private + * @method $__fullPath + * @memberOf EmbeddedDocument + */ + +EmbeddedDocument.prototype.$__fullPath = function(path) { + if (!this.$__.fullPath) { + var parent = this; // eslint-disable-line consistent-this + if (!parent.__parent) { + return path; + } + + var paths = []; + while (parent.__parent) { + paths.unshift(parent.__parentArray._path); + parent = parent.__parent; + } + + this.$__.fullPath = paths.join('.'); + + if (!this.$__.ownerDocument) { + // optimization + this.$__.ownerDocument = parent; + } + } + + return path + ? this.$__.fullPath + '.' + path + : this.$__.fullPath; +}; + +/** + * Returns this sub-documents parent document. + * + * @api public + */ + +EmbeddedDocument.prototype.parent = function() { + return this.__parent; +}; + +/** + * Returns this sub-documents parent array. + * + * @api public + */ + +EmbeddedDocument.prototype.parentArray = function() { + return this.__parentArray; +}; + +/*! + * Module exports. + */ + +module.exports = EmbeddedDocument; diff --git a/5-3/node_modules/mongoose/lib/types/index.js b/5-3/node_modules/mongoose/lib/types/index.js new file mode 100644 index 0000000..0d01923 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/types/index.js @@ -0,0 +1,15 @@ + +/*! + * Module exports. + */ + +exports.Array = require('./array'); +exports.Buffer = require('./buffer'); + +exports.Document = // @deprecate +exports.Embedded = require('./embedded'); + +exports.DocumentArray = require('./documentarray'); +exports.ObjectId = require('./objectid'); + +exports.Subdocument = require('./subdocument'); diff --git a/5-3/node_modules/mongoose/lib/types/objectid.js b/5-3/node_modules/mongoose/lib/types/objectid.js new file mode 100644 index 0000000..9fe0b97 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/types/objectid.js @@ -0,0 +1,13 @@ +/** + * ObjectId type constructor + * + * ####Example + * + * var id = new mongoose.Types.ObjectId; + * + * @constructor ObjectId + */ + +var ObjectId = require('../drivers').ObjectId; + +module.exports = ObjectId; diff --git a/5-3/node_modules/mongoose/lib/types/subdocument.js b/5-3/node_modules/mongoose/lib/types/subdocument.js new file mode 100644 index 0000000..de127a5 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/types/subdocument.js @@ -0,0 +1,123 @@ +var Document = require('../document'); +var PromiseProvider = require('../promise_provider'); + +module.exports = Subdocument; + +/** + * Subdocument constructor. + * + * @inherits Document + * @api private + */ + +function Subdocument() { + Document.apply(this, arguments); + this.$isSingleNested = true; +} + +Subdocument.prototype = Object.create(Document.prototype); + +/** + * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) + * + * ####NOTE: + * + * _This is a no-op. Does not actually save the doc to the db._ + * + * @param {Function} [fn] + * @return {Promise} resolved Promise + * @api private + */ + +Subdocument.prototype.save = function(fn) { + var Promise = PromiseProvider.get(); + return new Promise.ES6(function(resolve) { + fn && fn(); + resolve(); + }); +}; + +Subdocument.prototype.$isValid = function(path) { + if (this.$parent) { + return this.$parent.$isValid([this.$basePath, path].join('.')); + } +}; + +Subdocument.prototype.markModified = function(path) { + if (this.$parent) { + this.$parent.markModified([this.$basePath, path].join('.')); + } +}; + +Subdocument.prototype.$markValid = function(path) { + if (this.$parent) { + this.$parent.$markValid([this.$basePath, path].join('.')); + } +}; + +Subdocument.prototype.invalidate = function(path, err, val) { + if (this.$parent) { + this.$parent.invalidate([this.$basePath, path].join('.'), err, val); + } else if (err.kind === 'cast' || err.name === 'CastError') { + throw err; + } +}; + +/** + * Returns the top level document of this sub-document. + * + * @return {Document} + */ + +Subdocument.prototype.ownerDocument = function() { + if (this.$__.ownerDocument) { + return this.$__.ownerDocument; + } + + var parent = this.$parent; + if (!parent) { + return this; + } + + while (parent.$parent) { + parent = parent.$parent; + } + this.$__.ownerDocument = parent; + return this.$__.ownerDocument; +}; + +/** + * Null-out this subdoc + * + * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove + */ + +Subdocument.prototype.remove = function(callback) { + this.$parent.set(this.$basePath, null); + registerRemoveListener(this); + if (callback) { + callback(null); + } +}; + +/*! + * Registers remove event listeners for triggering + * on subdocuments. + * + * @param {EmbeddedDocument} sub + * @api private + */ + +function registerRemoveListener(sub) { + var owner = sub.ownerDocument(); + + function emitRemove() { + owner.removeListener('save', emitRemove); + owner.removeListener('remove', emitRemove); + sub.emit('remove', sub); + owner = sub = null; + } + + owner.on('save', emitRemove); + owner.on('remove', emitRemove); +} diff --git a/5-3/node_modules/mongoose/lib/utils.js b/5-3/node_modules/mongoose/lib/utils.js new file mode 100644 index 0000000..8747774 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/utils.js @@ -0,0 +1,841 @@ +/*! + * Module dependencies. + */ + +var ObjectId = require('./types/objectid'); +var cloneRegExp = require('regexp-clone'); +var sliced = require('sliced'); +var mpath = require('mpath'); +var ms = require('ms'); +var MongooseBuffer; +var MongooseArray; +var Document; + +/*! + * Produces a collection name from model `name`. + * + * @param {String} name a model name + * @return {String} a collection name + * @api private + */ + +exports.toCollectionName = function(name, options) { + options = options || {}; + if (name === 'system.profile') { + return name; + } + if (name === 'system.indexes') { + return name; + } + if (options.pluralization === false) { + return name; + } + return pluralize(name.toLowerCase()); +}; + +/** + * Pluralization rules. + * + * These rules are applied while processing the argument to `toCollectionName`. + * + * @deprecated remove in 4.x gh-1350 + */ + +exports.pluralization = [ + [/(m)an$/gi, '$1en'], + [/(pe)rson$/gi, '$1ople'], + [/(child)$/gi, '$1ren'], + [/^(ox)$/gi, '$1en'], + [/(ax|test)is$/gi, '$1es'], + [/(octop|vir)us$/gi, '$1i'], + [/(alias|status)$/gi, '$1es'], + [/(bu)s$/gi, '$1ses'], + [/(buffal|tomat|potat)o$/gi, '$1oes'], + [/([ti])um$/gi, '$1a'], + [/sis$/gi, 'ses'], + [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'], + [/(hive)$/gi, '$1s'], + [/([^aeiouy]|qu)y$/gi, '$1ies'], + [/(x|ch|ss|sh)$/gi, '$1es'], + [/(matr|vert|ind)ix|ex$/gi, '$1ices'], + [/([m|l])ouse$/gi, '$1ice'], + [/(kn|w|l)ife$/gi, '$1ives'], + [/(quiz)$/gi, '$1zes'], + [/s$/gi, 's'], + [/([^a-z])$/, '$1'], + [/$/gi, 's'] +]; +var rules = exports.pluralization; + +/** + * Uncountable words. + * + * These words are applied while processing the argument to `toCollectionName`. + * @api public + */ + +exports.uncountables = [ + 'advice', + 'energy', + 'excretion', + 'digestion', + 'cooperation', + 'health', + 'justice', + 'labour', + 'machinery', + 'equipment', + 'information', + 'pollution', + 'sewage', + 'paper', + 'money', + 'species', + 'series', + 'rain', + 'rice', + 'fish', + 'sheep', + 'moose', + 'deer', + 'news', + 'expertise', + 'status', + 'media' +]; +var uncountables = exports.uncountables; + +/*! + * Pluralize function. + * + * @author TJ Holowaychuk (extracted from _ext.js_) + * @param {String} string to pluralize + * @api private + */ + +function pluralize(str) { + var found; + if (!~uncountables.indexOf(str.toLowerCase())) { + found = rules.filter(function(rule) { + return str.match(rule[0]); + }); + if (found[0]) { + return str.replace(found[0][0], found[0][1]); + } + } + return str; +} + +/*! + * Determines if `a` and `b` are deep equal. + * + * Modified from node/lib/assert.js + * + * @param {any} a a value to compare to `b` + * @param {any} b a value to compare to `a` + * @return {Boolean} + * @api private + */ + +exports.deepEqual = function deepEqual(a, b) { + if (a === b) { + return true; + } + + if (a instanceof Date && b instanceof Date) { + return a.getTime() === b.getTime(); + } + + if (a instanceof ObjectId && b instanceof ObjectId) { + return a.toString() === b.toString(); + } + + if (a instanceof RegExp && b instanceof RegExp) { + return a.source === b.source && + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline && + a.global === b.global; + } + + if (typeof a !== 'object' && typeof b !== 'object') { + return a == b; + } + + if (a === null || b === null || a === undefined || b === undefined) { + return false; + } + + if (a.prototype !== b.prototype) { + return false; + } + + // Handle MongooseNumbers + if (a instanceof Number && b instanceof Number) { + return a.valueOf() === b.valueOf(); + } + + if (Buffer.isBuffer(a)) { + return exports.buffer.areEqual(a, b); + } + + if (isMongooseObject(a)) { + a = a.toObject(); + } + if (isMongooseObject(b)) { + b = b.toObject(); + } + + try { + var ka = Object.keys(a), + kb = Object.keys(b), + key, i; + } catch (e) { + // happens when one is a string literal and the other isn't + return false; + } + + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) { + return false; + } + + // the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + + // ~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) { + return false; + } + } + + // equivalent values for every corresponding key, and + // ~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!deepEqual(a[key], b[key])) { + return false; + } + } + + return true; +}; + +/*! + * Object clone with Mongoose natives support. + * + * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. + * + * Functions are never cloned. + * + * @param {Object} obj the object to clone + * @param {Object} options + * @return {Object} the cloned object + * @api private + */ + +exports.clone = function clone(obj, options) { + if (obj === undefined || obj === null) { + return obj; + } + + if (Array.isArray(obj)) { + return cloneArray(obj, options); + } + + if (isMongooseObject(obj)) { + if (options && options.json && typeof obj.toJSON === 'function') { + return obj.toJSON(options); + } + return obj.toObject(options); + } + + if (obj.constructor) { + switch (exports.getFunctionName(obj.constructor)) { + case 'Object': + return cloneObject(obj, options); + case 'Date': + return new obj.constructor(+obj); + case 'RegExp': + return cloneRegExp(obj); + default: + // ignore + break; + } + } + + if (obj instanceof ObjectId) { + return new ObjectId(obj.id); + } + + if (!obj.constructor && exports.isObject(obj)) { + // object created with Object.create(null) + return cloneObject(obj, options); + } + + if (obj.valueOf) { + return obj.valueOf(); + } +}; +var clone = exports.clone; + +/*! + * ignore + */ + +function cloneObject(obj, options) { + var retainKeyOrder = options && options.retainKeyOrder, + minimize = options && options.minimize, + ret = {}, + hasKeys, + keys, + val, + k, + i; + + if (retainKeyOrder) { + for (k in obj) { + val = clone(obj[k], options); + + if (!minimize || (typeof val !== 'undefined')) { + hasKeys || (hasKeys = true); + ret[k] = val; + } + } + } else { + // faster + + keys = Object.keys(obj); + i = keys.length; + + while (i--) { + k = keys[i]; + val = clone(obj[k], options); + + if (!minimize || (typeof val !== 'undefined')) { + if (!hasKeys) { + hasKeys = true; + } + ret[k] = val; + } + } + } + + return minimize + ? hasKeys && ret + : ret; +} + +function cloneArray(arr, options) { + var ret = []; + for (var i = 0, l = arr.length; i < l; i++) { + ret.push(clone(arr[i], options)); + } + return ret; +} + +/*! + * Shallow copies defaults into options. + * + * @param {Object} defaults + * @param {Object} options + * @return {Object} the merged object + * @api private + */ + +exports.options = function(defaults, options) { + var keys = Object.keys(defaults), + i = keys.length, + k; + + options = options || {}; + + while (i--) { + k = keys[i]; + if (!(k in options)) { + options[k] = defaults[k]; + } + } + + return options; +}; + +/*! + * Generates a random string + * + * @api private + */ + +exports.random = function() { + return Math.random().toString().substr(3); +}; + +/*! + * Merges `from` into `to` without overwriting existing properties. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +exports.merge = function merge(to, from) { + var keys = Object.keys(from), + i = keys.length, + key; + + while (i--) { + key = keys[i]; + if (typeof to[key] === 'undefined') { + to[key] = from[key]; + } else if (exports.isObject(from[key])) { + merge(to[key], from[key]); + } + } +}; + +/*! + * toString helper + */ + +var toString = Object.prototype.toString; + +/*! + * Applies toObject recursively. + * + * @param {Document|Array|Object} obj + * @return {Object} + * @api private + */ + +exports.toObject = function toObject(obj) { + var ret; + + if (exports.isNullOrUndefined(obj)) { + return obj; + } + + if (obj instanceof Document) { + return obj.toObject(); + } + + if (Array.isArray(obj)) { + ret = []; + + for (var i = 0, len = obj.length; i < len; ++i) { + ret.push(toObject(obj[i])); + } + + return ret; + } + + if ((obj.constructor && exports.getFunctionName(obj.constructor) === 'Object') || + (!obj.constructor && exports.isObject(obj))) { + ret = {}; + + for (var k in obj) { + ret[k] = toObject(obj[k]); + } + + return ret; + } + + return obj; +}; + +/*! + * Determines if `arg` is an object. + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @api private + * @return {Boolean} + */ + +exports.isObject = function(arg) { + if (Buffer.isBuffer(arg)) { + return true; + } + return toString.call(arg) === '[object Object]'; +}; + +/*! + * A faster Array.prototype.slice.call(arguments) alternative + * @api private + */ + +exports.args = sliced; + +/*! + * process.nextTick helper. + * + * Wraps `callback` in a try/catch + nextTick. + * + * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. + * + * @param {Function} callback + * @api private + */ + +exports.tick = function tick(callback) { + if (typeof callback !== 'function') { + return; + } + return function() { + try { + callback.apply(this, arguments); + } catch (err) { + // only nextTick on err to get out of + // the event loop and avoid state corruption. + process.nextTick(function() { + throw err; + }); + } + }; +}; + +/*! + * Returns if `v` is a mongoose object that has a `toObject()` method we can use. + * + * This is for compatibility with libs like Date.js which do foolish things to Natives. + * + * @param {any} v + * @api private + */ + +exports.isMongooseObject = function(v) { + Document || (Document = require('./document')); + MongooseArray || (MongooseArray = require('./types').Array); + MongooseBuffer || (MongooseBuffer = require('./types').Buffer); + + return v instanceof Document || + (v && v.isMongooseArray) || + (v && v.isMongooseBuffer); +}; +var isMongooseObject = exports.isMongooseObject; + +/*! + * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. + * + * @param {Object} object + * @api private + */ + +exports.expires = function expires(object) { + if (!(object && object.constructor.name === 'Object')) { + return; + } + if (!('expires' in object)) { + return; + } + + var when; + if (typeof object.expires !== 'string') { + when = object.expires; + } else { + when = Math.round(ms(object.expires) / 1000); + } + object.expireAfterSeconds = when; + delete object.expires; +}; + +/*! + * Populate options constructor + */ + +function PopulateOptions(path, select, match, options, model, subPopulate) { + this.path = path; + this.match = match; + this.select = select; + this.options = options; + this.model = model; + if (typeof subPopulate === 'object') { + this.populate = subPopulate; + } + this._docs = {}; +} + +// make it compatible with utils.clone +PopulateOptions.prototype.constructor = Object; + +// expose +exports.PopulateOptions = PopulateOptions; + +/*! + * populate helper + */ + +exports.populate = function populate(path, select, model, match, options, subPopulate) { + // The order of select/conditions args is opposite Model.find but + // necessary to keep backward compatibility (select could be + // an array, string, or object literal). + + // might have passed an object specifying all arguments + if (arguments.length === 1) { + if (path instanceof PopulateOptions) { + return [path]; + } + + if (Array.isArray(path)) { + return path.map(function(o) { + return exports.populate(o)[0]; + }); + } + + if (exports.isObject(path)) { + match = path.match; + options = path.options; + select = path.select; + model = path.model; + subPopulate = path.populate; + path = path.path; + } + } else if (typeof model !== 'string' && typeof model !== 'function') { + options = match; + match = model; + model = undefined; + } + + if (typeof path !== 'string') { + throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); + } + + if (typeof subPopulate === 'object') { + subPopulate = exports.populate(subPopulate); + } + + var ret = []; + var paths = path.split(' '); + for (var i = 0; i < paths.length; ++i) { + ret.push(new PopulateOptions(paths[i], select, match, options, model, subPopulate)); + } + + return ret; +}; + +/*! + * Return the value of `obj` at the given `path`. + * + * @param {String} path + * @param {Object} obj + */ + +exports.getValue = function(path, obj, map) { + return mpath.get(path, obj, '_doc', map); +}; + +/*! + * Sets the value of `obj` at the given `path`. + * + * @param {String} path + * @param {Anything} val + * @param {Object} obj + */ + +exports.setValue = function(path, val, obj, map) { + mpath.set(path, val, obj, '_doc', map); +}; + +/*! + * Returns an array of values from object `o`. + * + * @param {Object} o + * @return {Array} + * @private + */ + +exports.object = {}; +exports.object.vals = function vals(o) { + var keys = Object.keys(o), + i = keys.length, + ret = []; + + while (i--) { + ret.push(o[keys[i]]); + } + + return ret; +}; + +/*! + * @see exports.options + */ + +exports.object.shallowCopy = exports.options; + +/*! + * Safer helper for hasOwnProperty checks + * + * @param {Object} obj + * @param {String} prop + */ + +var hop = Object.prototype.hasOwnProperty; +exports.object.hasOwnProperty = function(obj, prop) { + return hop.call(obj, prop); +}; + +/*! + * Determine if `val` is null or undefined + * + * @return {Boolean} + */ + +exports.isNullOrUndefined = function(val) { + return val === null || val === undefined; +}; + +/*! + * ignore + */ + +exports.array = {}; + +/*! + * Flattens an array. + * + * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] + * + * @param {Array} arr + * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsey value, the item will not be included in the results. + * @return {Array} + * @private + */ + +exports.array.flatten = function flatten(arr, filter, ret) { + ret || (ret = []); + + arr.forEach(function(item) { + if (Array.isArray(item)) { + flatten(item, filter, ret); + } else { + if (!filter || filter(item)) { + ret.push(item); + } + } + }); + + return ret; +}; + +/*! + * Removes duplicate values from an array + * + * [1, 2, 3, 3, 5] => [1, 2, 3, 5] + * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ] + * => [ObjectId("550988ba0c19d57f697dc45e")] + * + * @param {Array} arr + * @return {Array} + * @private + */ + +exports.array.unique = function(arr) { + var primitives = {}; + var ids = {}; + var ret = []; + var length = arr.length; + for (var i = 0; i < length; ++i) { + if (typeof arr[i] === 'number' || typeof arr[i] === 'string') { + if (primitives[arr[i]]) { + continue; + } + ret.push(arr[i]); + primitives[arr[i]] = true; + } else if (arr[i] instanceof ObjectId) { + if (ids[arr[i].toString()]) { + continue; + } + ret.push(arr[i]); + ids[arr[i].toString()] = true; + } else { + ret.push(arr[i]); + } + } + + return ret; +}; + +/*! + * Determines if two buffers are equal. + * + * @param {Buffer} a + * @param {Object} b + */ + +exports.buffer = {}; +exports.buffer.areEqual = function(a, b) { + if (!Buffer.isBuffer(a)) { + return false; + } + if (!Buffer.isBuffer(b)) { + return false; + } + if (a.length !== b.length) { + return false; + } + for (var i = 0, len = a.length; i < len; ++i) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +}; + +exports.getFunctionName = function(fn) { + if (fn.name) { + return fn.name; + } + return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; +}; + +exports.decorate = function(destination, source) { + for (var key in source) { + destination[key] = source[key]; + } +}; + +/** + * merges to with a copy of from + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +exports.mergeClone = function(to, from) { + var keys = Object.keys(from), + i = keys.length, + key; + + while (i--) { + key = keys[i]; + if (typeof to[key] === 'undefined') { + // make sure to retain key order here because of a bug handling the $each + // operator in mongodb 2.4.4 + to[key] = exports.clone(from[key], {retainKeyOrder: 1}); + } else { + if (exports.isObject(from[key])) { + exports.mergeClone(to[key], from[key]); + } else { + // make sure to retain key order here because of a bug handling the + // $each operator in mongodb 2.4.4 + to[key] = exports.clone(from[key], {retainKeyOrder: 1}); + } + } + } +}; + +/** + * Executes a function on each element of an array (like _.each) + * + * @param {Array} arr + * @param {Function} fn + * @api private + */ + +exports.each = function(arr, fn) { + for (var i = 0; i < arr.length; ++i) { + fn(arr[i]); + } +}; diff --git a/5-3/node_modules/mongoose/lib/virtualtype.js b/5-3/node_modules/mongoose/lib/virtualtype.js new file mode 100644 index 0000000..f43cbe2 --- /dev/null +++ b/5-3/node_modules/mongoose/lib/virtualtype.js @@ -0,0 +1,103 @@ + +/** + * VirtualType constructor + * + * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. + * + * ####Example: + * + * var fullname = schema.virtual('fullname'); + * fullname instanceof mongoose.VirtualType // true + * + * @parma {Object} options + * @api public + */ + +function VirtualType(options, name) { + this.path = name; + this.getters = []; + this.setters = []; + this.options = options || {}; +} + +/** + * Defines a getter. + * + * ####Example: + * + * var virtual = schema.virtual('fullname'); + * virtual.get(function () { + * return this.name.first + ' ' + this.name.last; + * }); + * + * @param {Function} fn + * @return {VirtualType} this + * @api public + */ + +VirtualType.prototype.get = function(fn) { + this.getters.push(fn); + return this; +}; + +/** + * Defines a setter. + * + * ####Example: + * + * var virtual = schema.virtual('fullname'); + * virtual.set(function (v) { + * var parts = v.split(' '); + * this.name.first = parts[0]; + * this.name.last = parts[1]; + * }); + * + * @param {Function} fn + * @return {VirtualType} this + * @api public + */ + +VirtualType.prototype.set = function(fn) { + this.setters.push(fn); + return this; +}; + +/** + * Applies getters to `value` using optional `scope`. + * + * @param {Object} value + * @param {Object} scope + * @return {any} the value after applying all getters + * @api public + */ + +VirtualType.prototype.applyGetters = function(value, scope) { + var v = value; + for (var l = this.getters.length - 1; l >= 0; l--) { + v = this.getters[l].call(scope, v, this); + } + return v; +}; + +/** + * Applies setters to `value` using optional `scope`. + * + * @param {Object} value + * @param {Object} scope + * @return {any} the value after applying all setters + * @api public + */ + +VirtualType.prototype.applySetters = function(value, scope) { + var v = value; + for (var l = this.setters.length - 1; l >= 0; l--) { + v = this.setters[l].call(scope, v, this); + } + return v; +}; + +/*! + * exports + */ + +module.exports = VirtualType; diff --git a/5-3/node_modules/mongoose/node_modules/async/CHANGELOG.md b/5-3/node_modules/mongoose/node_modules/async/CHANGELOG.md new file mode 100644 index 0000000..f15e081 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/async/CHANGELOG.md @@ -0,0 +1,125 @@ +# v1.5.2 +- Allow using `"consructor"` as an argument in `memoize` (#998) +- Give a better error messsage when `auto` dependency checking fails (#994) +- Various doc updates (#936, #956, #979, #1002) + +# v1.5.1 +- Fix issue with `pause` in `queue` with concurrency enabled (#946) +- `while` and `until` now pass the final result to callback (#963) +- `auto` will properly handle concurrency when there is no callback (#966) +- `auto` will now properly stop execution when an error occurs (#988, #993) +- Various doc fixes (#971, #980) + +# v1.5.0 + +- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) (#892) +- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. (#873) +- `auto` now accepts an optional `concurrency` argument to limit the number of running tasks (#637) +- Added `queue#workersList()`, to retrieve the list of currently running tasks. (#891) +- Various code simplifications (#896, #904) +- Various doc fixes :scroll: (#890, #894, #903, #905, #912) + +# v1.4.2 + +- Ensure coverage files don't get published on npm (#879) + +# v1.4.1 + +- Add in overlooked `detectLimit` method (#866) +- Removed unnecessary files from npm releases (#861) +- Removed usage of a reserved word to prevent :boom: in older environments (#870) + +# v1.4.0 + +- `asyncify` now supports promises (#840) +- Added `Limit` versions of `filter` and `reject` (#836) +- Add `Limit` versions of `detect`, `some` and `every` (#828, #829) +- `some`, `every` and `detect` now short circuit early (#828, #829) +- Improve detection of the global object (#804), enabling use in WebWorkers +- `whilst` now called with arguments from iterator (#823) +- `during` now gets called with arguments from iterator (#824) +- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0)) + + +# v1.3.0 + +New Features: +- Added `constant` +- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. (#671, #806) +- Added `during` and `doDuring`, which are like `whilst` with an async truth test. (#800) +- `retry` now accepts an `interval` parameter to specify a delay between retries. (#793) +- `async` should work better in Web Workers due to better `root` detection (#804) +- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` (#642) +- Various internal updates (#786, #801, #802, #803) +- Various doc fixes (#790, #794) + +Bug Fixes: +- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. (#740, #744, #783) + + +# v1.2.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. (#782) + + +# v1.2.0 + +New Features: + +- Added `timesLimit` (#743) +- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. (#747, #772) + +Bug Fixes: + +- Fixed a regression in `each` and family with empty arrays that have additional properties. (#775, #777) + + +# v1.1.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. (#782) + + +# v1.1.0 + +New Features: + +- `cargo` now supports all of the same methods and event callbacks as `queue`. +- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. (#769) +- Optimized `map`, `eachOf`, and `waterfall` families of functions +- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array (#667). +- The callback is now optional for the composed results of `compose` and `seq`. (#618) +- Reduced file size by 4kb, (minified version by 1kb) +- Added code coverage through `nyc` and `coveralls` (#768) + +Bug Fixes: + +- `forever` will no longer stack overflow with a synchronous iterator (#622) +- `eachLimit` and other limit functions will stop iterating once an error occurs (#754) +- Always pass `null` in callbacks when there is no error (#439) +- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue (#668) +- `each` and family will properly handle an empty array (#578) +- `eachSeries` and family will finish if the underlying array is modified during execution (#557) +- `queue` will throw if a non-function is passed to `q.push()` (#593) +- Doc fixes (#629, #766) + + +# v1.0.0 + +No known breaking changes, we are simply complying with semver from here on out. + +Changes: + +- Start using a changelog! +- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) (#168 #704 #321) +- Detect deadlocks in `auto` (#663) +- Better support for require.js (#527) +- Throw if queue created with concurrency `0` (#714) +- Fix unneeded iteration in `queue.resume()` (#758) +- Guard against timer mocking overriding `setImmediate` (#609 #611) +- Miscellaneous doc fixes (#542 #596 #615 #628 #631 #690 #729) +- Use single noop function internally (#546) +- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/5-3/node_modules/mongoose/node_modules/async/LICENSE b/5-3/node_modules/mongoose/node_modules/async/LICENSE new file mode 100644 index 0000000..8f29698 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-2014 Caolan McMahon + +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/5-3/node_modules/mongoose/node_modules/async/README.md b/5-3/node_modules/mongoose/node_modules/async/README.md new file mode 100644 index 0000000..316c405 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/async/README.md @@ -0,0 +1,1877 @@ +# Async.js + +[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async) +[![NPM version](http://img.shields.io/npm/v/async.svg)](https://www.npmjs.org/package/async) +[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master) +[![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + + +Async is a utility module which provides straight-forward, powerful functions +for working with asynchronous JavaScript. Although originally designed for +use with [Node.js](http://nodejs.org) and installable via `npm install async`, +it can also be used directly in the browser. + +Async is also installable via: + +- [bower](http://bower.io/): `bower install async` +- [component](https://github.com/component/component): `component install + caolan/async` +- [jam](http://jamjs.org/): `jam install async` +- [spm](http://spmjs.io/): `spm install async` + +Async provides around 20 functions that include the usual 'functional' +suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns +for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these +functions assume you follow the Node.js convention of providing a single +callback as the last argument of your `async` function. + + +## Quick Examples + +```javascript +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); + +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); + +async.parallel([ + function(){ ... }, + function(){ ... } +], callback); + +async.series([ + function(){ ... }, + function(){ ... } +]); +``` + +There are many more functions available so take a look at the docs below for a +full list. This module aims to be comprehensive, so if you feel anything is +missing please create a GitHub issue for it. + +## Common Pitfalls [(StackOverflow)](http://stackoverflow.com/questions/tagged/async.js) +### Synchronous iteration functions + +If you get an error like `RangeError: Maximum call stack size exceeded.` or other stack overflow issues when using async, you are likely using a synchronous iterator. By *synchronous* we mean a function that calls its callback on the same tick in the javascript event loop, without doing any I/O or using any timers. Calling many callbacks iteratively will quickly overflow the stack. If you run into this issue, just defer your callback with `async.setImmediate` to start a new call stack on the next tick of the event loop. + +This can also arise by accident if you callback early in certain cases: + +```js +async.eachSeries(hugeArray, function iterator(item, callback) { + if (inCache(item)) { + callback(null, cache[item]); // if many items are cached, you'll overflow + } else { + doSomeIO(item, callback); + } +}, function done() { + //... +}); +``` + +Just change it to: + +```js +async.eachSeries(hugeArray, function iterator(item, callback) { + if (inCache(item)) { + async.setImmediate(function () { + callback(null, cache[item]); + }); + } else { + doSomeIO(item, callback); + //... +``` + +Async guards against synchronous functions in some, but not all, cases. If you are still running into stack overflows, you can defer as suggested above, or wrap functions with [`async.ensureAsync`](#ensureAsync) Functions that are asynchronous by their nature do not have this problem and don't need the extra callback deferral. + +If JavaScript's event loop is still a bit nebulous, check out [this article](http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/) or [this talk](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html) for more detailed information about how it works. + + +### Multiple callbacks + +Make sure to always `return` when calling a callback early, otherwise you will cause multiple callbacks and unpredictable behavior in many cases. + +```js +async.waterfall([ + function (callback) { + getSomething(options, function (err, result) { + if (err) { + callback(new Error("failed getting something:" + err.message)); + // we should return here + } + // since we did not return, this callback still will be called and + // `processData` will be called twice + callback(null, result); + }); + }, + processData +], done) +``` + +It is always good practice to `return callback(err, result)` whenever a callback call is not the last statement of a function. + + +### Binding a context to an iterator + +This section is really about `bind`, not about `async`. If you are wondering how to +make `async` execute your iterators in a given context, or are confused as to why +a method of another library isn't working as an iterator, study this example: + +```js +// Here is a simple object with an (unnecessarily roundabout) squaring method +var AsyncSquaringLibrary = { + squareExponent: 2, + square: function(number, callback){ + var result = Math.pow(number, this.squareExponent); + setTimeout(function(){ + callback(null, result); + }, 200); + } +}; + +async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){ + // result is [NaN, NaN, NaN] + // This fails because the `this.squareExponent` expression in the square + // function is not evaluated in the context of AsyncSquaringLibrary, and is + // therefore undefined. +}); + +async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){ + // result is [1, 4, 9] + // With the help of bind we can attach a context to the iterator before + // passing it to async. Now the square function will be executed in its + // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent` + // will be as expected. +}); +``` + +## Download + +The source is available for download from +[GitHub](https://github.com/caolan/async/blob/master/lib/async.js). +Alternatively, you can install using Node Package Manager (`npm`): + + npm install async + +As well as using Bower: + + bower install async + +__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed + +## In the Browser + +So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. + +Usage: + +```html + + +``` + +## Documentation + +Some functions are also available in the following forms: +* `Series` - the same as `` but runs only a single async operation at a time +* `Limit` - the same as `` but runs a maximum of `limit` async operations at a time + +### Collections + +* [`each`](#each), `eachSeries`, `eachLimit` +* [`forEachOf`](#forEachOf), `forEachOfSeries`, `forEachOfLimit` +* [`map`](#map), `mapSeries`, `mapLimit` +* [`filter`](#filter), `filterSeries`, `filterLimit` +* [`reject`](#reject), `rejectSeries`, `rejectLimit` +* [`reduce`](#reduce), [`reduceRight`](#reduceRight) +* [`detect`](#detect), `detectSeries`, `detectLimit` +* [`sortBy`](#sortBy) +* [`some`](#some), `someLimit` +* [`every`](#every), `everyLimit` +* [`concat`](#concat), `concatSeries` + +### Control Flow + +* [`series`](#seriestasks-callback) +* [`parallel`](#parallel), `parallelLimit` +* [`whilst`](#whilst), [`doWhilst`](#doWhilst) +* [`until`](#until), [`doUntil`](#doUntil) +* [`during`](#during), [`doDuring`](#doDuring) +* [`forever`](#forever) +* [`waterfall`](#waterfall) +* [`compose`](#compose) +* [`seq`](#seq) +* [`applyEach`](#applyEach), `applyEachSeries` +* [`queue`](#queue), [`priorityQueue`](#priorityQueue) +* [`cargo`](#cargo) +* [`auto`](#auto) +* [`retry`](#retry) +* [`iterator`](#iterator) +* [`times`](#times), `timesSeries`, `timesLimit` + +### Utils + +* [`apply`](#apply) +* [`nextTick`](#nextTick) +* [`memoize`](#memoize) +* [`unmemoize`](#unmemoize) +* [`ensureAsync`](#ensureAsync) +* [`constant`](#constant) +* [`asyncify`](#asyncify) +* [`wrapSync`](#wrapSync) +* [`log`](#log) +* [`dir`](#dir) +* [`noConflict`](#noConflict) + +## Collections + + + +### each(arr, iterator, [callback]) + +Applies the function `iterator` to each item in `arr`, in parallel. +The `iterator` is called with an item from the list, and a callback for when it +has finished. If the `iterator` passes an error to its `callback`, the main +`callback` (for the `each` function) is immediately called with the error. + +Note, that since this function applies `iterator` to each item in parallel, +there is no guarantee that the iterator functions will complete in order. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the `callback` should be run without + arguments or with an explicit `null` argument. The array index is not passed + to the iterator. If you need the index, use [`forEachOf`](#forEachOf). +* `callback(err)` - *Optional* A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Examples__ + + +```js +// assuming openFiles is an array of file names and saveFile is a function +// to save the modified contents of that file: + +async.each(openFiles, saveFile, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +```js +// assuming openFiles is an array of file names + +async.each(openFiles, function(file, callback) { + + // Perform operation on file here. + console.log('Processing file ' + file); + + if( file.length > 32 ) { + console.log('This file name is too long'); + callback('File name too long'); + } else { + // Do work to process file here + console.log('File processed'); + callback(); + } +}, function(err){ + // if any of the file processing produced an error, err would equal that error + if( err ) { + // One of the iterations produced an error. + // All processing will now stop. + console.log('A file failed to process'); + } else { + console.log('All files have been processed successfully'); + } +}); +``` + +__Related__ + +* eachSeries(arr, iterator, [callback]) +* eachLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + + + +### forEachOf(obj, iterator, [callback]) + +Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator. + +__Arguments__ + +* `obj` - An object or array to iterate over. +* `iterator(item, key, callback)` - A function to apply to each item in `obj`. +The `key` is the item's key, or index in the case of an array. The iterator is +passed a `callback(err)` which must be called once it has completed. If no +error has occurred, the callback should be run without arguments or with an +explicit `null` argument. +* `callback(err)` - *Optional* A callback which is called when all `iterator` functions have finished, or an error occurs. + +__Example__ + +```js +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, function (value, key, callback) { + fs.readFile(__dirname + value, "utf8", function (err, data) { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }) +}, function (err) { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}) +``` + +__Related__ + +* forEachOfSeries(obj, iterator, [callback]) +* forEachOfLimit(obj, limit, iterator, [callback]) + +--------------------------------------- + + +### map(arr, iterator, [callback]) + +Produces a new array of values by mapping each value in `arr` through +the `iterator` function. The `iterator` is called with an item from `arr` and a +callback for when it has finished processing. Each of these callback takes 2 arguments: +an `error`, and the transformed item from `arr`. If `iterator` passes an error to its +callback, the main `callback` (for the `map` function) is immediately called with the error. + +Note, that since this function applies the `iterator` to each item in parallel, +there is no guarantee that the `iterator` functions will complete in order. +However, the results array will be in the same order as the original `arr`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - *Optional* A callback which is called when all `iterator` + functions have finished, or an error occurs. Results is an array of the + transformed items from the `arr`. + +__Example__ + +```js +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +__Related__ +* mapSeries(arr, iterator, [callback]) +* mapLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + + +### filter(arr, iterator, [callback]) + +__Alias:__ `select` + +Returns a new array of all the values in `arr` which pass an async truth test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. This operation is +performed in parallel, but the results array will be in the same order as the +original. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The `iterator` is passed a `callback(truthValue)`, which must be called with a + boolean argument once it has completed. +* `callback(results)` - *Optional* A callback which is called after all the `iterator` + functions have finished. + +__Example__ + +```js +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); +``` + +__Related__ + +* filterSeries(arr, iterator, [callback]) +* filterLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + +### reject(arr, iterator, [callback]) + +The opposite of [`filter`](#filter). Removes values that pass an `async` truth test. + +__Related__ + +* rejectSeries(arr, iterator, [callback]) +* rejectLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + +### reduce(arr, memo, iterator, [callback]) + +__Aliases:__ `inject`, `foldl` + +Reduces `arr` into a single value using an async `iterator` to return +each successive step. `memo` is the initial state of the reduction. +This function only operates in series. + +For performance reasons, it may make sense to split a call to this function into +a parallel map, and then use the normal `Array.prototype.reduce` on the results. +This function is for situations where each step in the reduction needs to be async; +if you can get the data before reducing it, then it's probably a good idea to do so. + +__Arguments__ + +* `arr` - An array to iterate over. +* `memo` - The initial state of the reduction. +* `iterator(memo, item, callback)` - A function applied to each item in the + array to produce the next step in the reduction. The `iterator` is passed a + `callback(err, reduction)` which accepts an optional error as its first + argument, and the state of the reduction as the second. If an error is + passed to the callback, the reduction is stopped and the main `callback` is + immediately called with the error. +* `callback(err, result)` - *Optional* A callback which is called after all the `iterator` + functions have finished. Result is the reduced value. + +__Example__ + +```js +async.reduce([1,2,3], 0, function(memo, item, callback){ + // pointless async: + process.nextTick(function(){ + callback(null, memo + item) + }); +}, function(err, result){ + // result is now equal to the last value of memo, which is 6 +}); +``` + +--------------------------------------- + + +### reduceRight(arr, memo, iterator, [callback]) + +__Alias:__ `foldr` + +Same as [`reduce`](#reduce), only operates on `arr` in reverse order. + + +--------------------------------------- + + +### detect(arr, iterator, [callback]) + +Returns the first value in `arr` that passes an async truth test. The +`iterator` is applied in parallel, meaning the first iterator to return `true` will +fire the detect `callback` with that result. That means the result might not be +the first item in the original `arr` (in terms of order) that passes the test. + +If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries). + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The iterator is passed a `callback(truthValue)` which must be called with a + boolean argument once it has completed. **Note: this callback does not take an error as its first argument.** +* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns + `true`, or after all the `iterator` functions have finished. Result will be + the first item in the array that passes the truth test (iterator) or the + value `undefined` if none passed. **Note: this callback does not take an error as its first argument.** + +__Example__ + +```js +async.detect(['file1','file2','file3'], fs.exists, function(result){ + // result now equals the first file in the list that exists +}); +``` + +__Related__ + +* detectSeries(arr, iterator, [callback]) +* detectLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + +### sortBy(arr, iterator, [callback]) + +Sorts a list by the results of running each `arr` value through an async `iterator`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, sortValue)` which must be called once it + has completed with an error (which can be `null`) and a value to use as the sort + criteria. +* `callback(err, results)` - *Optional* A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is the items from + the original `arr` sorted by the values returned by the `iterator` calls. + +__Example__ + +```js +async.sortBy(['file1','file2','file3'], function(file, callback){ + fs.stat(file, function(err, stats){ + callback(err, stats.mtime); + }); +}, function(err, results){ + // results is now the original array of files sorted by + // modified date +}); +``` + +__Sort Order__ + +By modifying the callback parameter the sorting order can be influenced: + +```js +//ascending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x); +}, function(err,result){ + //result callback +} ); + +//descending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x*-1); //<- x*-1 instead of x, turns the order around +}, function(err,result){ + //result callback +} ); +``` + +--------------------------------------- + + +### some(arr, iterator, [callback]) + +__Alias:__ `any` + +Returns `true` if at least one element in the `arr` satisfies an async test. +_The callback for each iterator call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. Once any iterator +call returns `true`, the main `callback` is immediately called. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a `callback(truthValue)`` which must be + called with a boolean argument once it has completed. +* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns + `true`, or after all the iterator functions have finished. Result will be + either `true` or `false` depending on the values of the async tests. + + **Note: the callbacks do not take an error as their first argument.** +__Example__ + +```js +async.some(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then at least one of the files exists +}); +``` + +__Related__ + +* someLimit(arr, limit, iterator, callback) + +--------------------------------------- + + +### every(arr, iterator, [callback]) + +__Alias:__ `all` + +Returns `true` if every element in `arr` satisfies an async test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a `callback(truthValue)` which must be + called with a boolean argument once it has completed. +* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns + `false`, or after all the iterator functions have finished. Result will be + either `true` or `false` depending on the values of the async tests. + + **Note: the callbacks do not take an error as their first argument.** + +__Example__ + +```js +async.every(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then every file exists +}); +``` + +__Related__ + +* everyLimit(arr, limit, iterator, callback) + +--------------------------------------- + + +### concat(arr, iterator, [callback]) + +Applies `iterator` to each item in `arr`, concatenating the results. Returns the +concatenated list. The `iterator`s are called in parallel, and the results are +concatenated as they return. There is no guarantee that the results array will +be returned in the original order of `arr` passed to the `iterator` function. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, results)` which must be called once it + has completed with an error (which can be `null`) and an array of results. +* `callback(err, results)` - *Optional* A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is an array containing + the concatenated results of the `iterator` function. + +__Example__ + +```js +async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ + // files is now a list of filenames that exist in the 3 directories +}); +``` + +__Related__ + +* concatSeries(arr, iterator, [callback]) + + +## Control Flow + + +### series(tasks, [callback]) + +Run the functions in the `tasks` array in series, each one running once the previous +function has completed. If any functions in the series pass an error to its +callback, no more functions are run, and `callback` is immediately called with the value of the error. +Otherwise, `callback` receives an array of results when `tasks` have completed. + +It is also possible to use an object instead of an array. Each property will be +run as a function, and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`series`](#series). + +**Note** that while many implementations preserve the order of object properties, the +[ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) +explicitly states that + +> The mechanics and order of enumerating the properties is not specified. + +So if you rely on the order in which your series of functions are executed, and want +this to work on all platforms, consider using an array. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +__Example__ + +```js +async.series([ + function(callback){ + // do some stuff ... + callback(null, 'one'); + }, + function(callback){ + // do some more stuff ... + callback(null, 'two'); + } +], +// optional callback +function(err, results){ + // results is now equal to ['one', 'two'] +}); + + +// an example using an object instead of an array +async.series({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equal to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + + +### parallel(tasks, [callback]) + +Run the `tasks` array of functions in parallel, without waiting until the previous +function has completed. If any of the functions pass an error to its +callback, the main `callback` is immediately called with the value of the error. +Once the `tasks` have completed, the results are passed to the final `callback` as an +array. + +**Note:** `parallel` is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded. + +It is also possible to use an object instead of an array. Each property will be +run as a function and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`parallel`](#parallel). + + +__Arguments__ + +* `tasks` - An array or object containing functions to run. Each function is passed + a `callback(err, result)` which it must call on completion with an error `err` + (which can be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed successfully. This function gets a results array (or object) containing all + the result arguments passed to the task callbacks. + +__Example__ + +```js +async.parallel([ + function(callback){ + setTimeout(function(){ + callback(null, 'one'); + }, 200); + }, + function(callback){ + setTimeout(function(){ + callback(null, 'two'); + }, 100); + } +], +// optional callback +function(err, results){ + // the results array will equal ['one','two'] even though + // the second function had a shorter timeout. +}); + + +// an example using an object instead of an array +async.parallel({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equals to: {one: 1, two: 2} +}); +``` + +__Related__ + +* parallelLimit(tasks, limit, [callback]) + +--------------------------------------- + + +### whilst(test, fn, callback) + +Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +__Arguments__ + +* `test()` - synchronous truth test to perform before each execution of `fn`. +* `fn(callback)` - A function which is called each time `test` passes. The function is + passed a `callback(err)`, which must be called once it has completed with an + optional `err` argument. +* `callback(err, [results])` - A callback which is called after the test + function has failed and repeated execution of `fn` has stopped. `callback` + will be passed an error and any arguments passed to the final `fn`'s callback. + +__Example__ + +```js +var count = 0; + +async.whilst( + function () { return count < 5; }, + function (callback) { + count++; + setTimeout(function () { + callback(null, count); + }, 1000); + }, + function (err, n) { + // 5 seconds have passed, n = 5 + } +); +``` + +--------------------------------------- + + +### doWhilst(fn, test, callback) + +The post-check version of [`whilst`](#whilst). To reflect the difference in +the order of operations, the arguments `test` and `fn` are switched. + +`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + +--------------------------------------- + + +### until(test, fn, callback) + +Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped, +or an error occurs. `callback` will be passed an error and any arguments passed +to the final `fn`'s callback. + +The inverse of [`whilst`](#whilst). + +--------------------------------------- + + +### doUntil(fn, test, callback) + +Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`. + +--------------------------------------- + + +### during(test, fn, callback) + +Like [`whilst`](#whilst), except the `test` is an asynchronous function that is passed a callback in the form of `function (err, truth)`. If error is passed to `test` or `fn`, the main callback is immediately called with the value of the error. + +__Example__ + +```js +var count = 0; + +async.during( + function (callback) { + return callback(null, count < 5); + }, + function (callback) { + count++; + setTimeout(callback, 1000); + }, + function (err) { + // 5 seconds have passed + } +); +``` + +--------------------------------------- + + +### doDuring(fn, test, callback) + +The post-check version of [`during`](#during). To reflect the difference in +the order of operations, the arguments `test` and `fn` are switched. + +Also a version of [`doWhilst`](#doWhilst) with asynchronous `test` function. + +--------------------------------------- + + +### forever(fn, [errback]) + +Calls the asynchronous function `fn` with a callback parameter that allows it to +call itself again, in series, indefinitely. + +If an error is passed to the callback then `errback` is called with the +error, and execution stops, otherwise it will never be called. + +```js +async.forever( + function(next) { + // next is suitable for passing to things that need a callback(err [, whatever]); + // it will result in this function being called again. + }, + function(err) { + // if next is called with a value in its first parameter, it will appear + // in here as 'err', and execution will stop. + } +); +``` + +--------------------------------------- + + +### waterfall(tasks, [callback]) + +Runs the `tasks` array of functions in series, each passing their results to the next in +the array. However, if any of the `tasks` pass an error to their own callback, the +next function is not executed, and the main `callback` is immediately called with +the error. + +__Arguments__ + +* `tasks` - An array of functions to run, each function is passed a + `callback(err, result1, result2, ...)` it must call on completion. The first + argument is an error (which can be `null`) and any further arguments will be + passed as arguments in order to the next task. +* `callback(err, [results])` - An optional callback to run once all the functions + have completed. This will be passed the results of the last task's callback. + + + +__Example__ + +```js +async.waterfall([ + function(callback) { + callback(null, 'one', 'two'); + }, + function(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); + }, + function(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); + } +], function (err, result) { + // result now equals 'done' +}); +``` +Or, with named functions: + +```js +async.waterfall([ + myFirstFunction, + mySecondFunction, + myLastFunction, +], function (err, result) { + // result now equals 'done' +}); +function myFirstFunction(callback) { + callback(null, 'one', 'two'); +} +function mySecondFunction(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); +} +function myLastFunction(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); +} +``` + +Or, if you need to pass any argument to the first function: + +```js +async.waterfall([ + async.apply(myFirstFunction, 'zero'), + mySecondFunction, + myLastFunction, +], function (err, result) { + // result now equals 'done' +}); +function myFirstFunction(arg1, callback) { + // arg1 now equals 'zero' + callback(null, 'one', 'two'); +} +function mySecondFunction(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); +} +function myLastFunction(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); +} +``` + +--------------------------------------- + +### compose(fn1, fn2...) + +Creates a function which is a composition of the passed asynchronous +functions. Each function consumes the return value of the function that +follows. Composing functions `f()`, `g()`, and `h()` would produce the result of +`f(g(h()))`, only this version uses callbacks to obtain the return values. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* `functions...` - the asynchronous functions to compose + + +__Example__ + +```js +function add1(n, callback) { + setTimeout(function () { + callback(null, n + 1); + }, 10); +} + +function mul3(n, callback) { + setTimeout(function () { + callback(null, n * 3); + }, 10); +} + +var add1mul3 = async.compose(mul3, add1); + +add1mul3(4, function (err, result) { + // result now equals 15 +}); +``` + +--------------------------------------- + +### seq(fn1, fn2...) + +Version of the compose function that is more natural to read. +Each function consumes the return value of the previous function. +It is the equivalent of [`compose`](#compose) with the arguments reversed. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* `functions...` - the asynchronous functions to compose + + +__Example__ + +```js +// Requires lodash (or underscore), express3 and dresende's orm2. +// Part of an app, that fetches cats of the logged user. +// This example uses `seq` function to avoid overnesting and error +// handling clutter. +app.get('/cats', function(request, response) { + var User = request.models.User; + async.seq( + _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + function(user, fn) { + user.getCats(fn); // 'getCats' has signature (callback(err, data)) + } + )(req.session.user_id, function (err, cats) { + if (err) { + console.error(err); + response.json({ status: 'error', message: err.message }); + } else { + response.json({ status: 'ok', message: 'Cats found', data: cats }); + } + }); +}); +``` + +--------------------------------------- + +### applyEach(fns, args..., callback) + +Applies the provided arguments to each function in the array, calling +`callback` after all functions have completed. If you only provide the first +argument, then it will return a function which lets you pass in the +arguments as if it were a single function call. + +__Arguments__ + +* `fns` - the asynchronous functions to all call with the same arguments +* `args...` - any number of separate arguments to pass to the function +* `callback` - the final argument should be the callback, called when all + functions have completed processing + + +__Example__ + +```js +async.applyEach([enableSearch, updateSchema], 'bucket', callback); + +// partial application example: +async.each( + buckets, + async.applyEach([enableSearch, updateSchema]), + callback +); +``` + +__Related__ + +* applyEachSeries(tasks, args..., [callback]) + +--------------------------------------- + + +### queue(worker, [concurrency]) + +Creates a `queue` object with the specified `concurrency`. Tasks added to the +`queue` are processed in parallel (up to the `concurrency` limit). If all +`worker`s are in progress, the task is queued until one becomes available. +Once a `worker` completes a `task`, that `task`'s callback is called. + +__Arguments__ + +* `worker(task, callback)` - An asynchronous function for processing a queued + task, which must call its `callback(err)` argument when finished, with an + optional `error` as an argument. If you want to handle errors from an individual task, pass a callback to `q.push()`. +* `concurrency` - An `integer` for determining how many `worker` functions should be + run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown. + +__Queue objects__ + +The `queue` object returned by this function has the following properties and +methods: + +* `length()` - a function returning the number of items waiting to be processed. +* `started` - a function returning whether or not any items have been pushed and processed by the queue +* `running()` - a function returning the number of items currently being processed. +* `workersList()` - a function returning the array of items currently being processed. +* `idle()` - a function returning false if there are items waiting or being processed, or true if not. +* `concurrency` - an integer for determining how many `worker` functions should be + run in parallel. This property can be changed after a `queue` is created to + alter the concurrency on-the-fly. +* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once + the `worker` has finished processing the task. Instead of a single task, a `tasks` array + can be submitted. The respective callback is used for every task in the list. +* `unshift(task, [callback])` - add a new task to the front of the `queue`. +* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, + and further tasks will be queued. +* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`. +* `paused` - a boolean for determining whether the queue is in a paused state +* `pause()` - a function that pauses the processing of tasks until `resume()` is called. +* `resume()` - a function that resumes the processing of queued tasks when the queue is paused. +* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle. + +__Example__ + +```js +// create a queue object with concurrency 2 + +var q = async.queue(function (task, callback) { + console.log('hello ' + task.name); + callback(); +}, 2); + + +// assign a callback +q.drain = function() { + console.log('all items have been processed'); +} + +// add some items to the queue + +q.push({name: 'foo'}, function (err) { + console.log('finished processing foo'); +}); +q.push({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); + +// add some items to the queue (batch-wise) + +q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { + console.log('finished processing item'); +}); + +// add some items to the front of the queue + +q.unshift({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); +``` + + +--------------------------------------- + + +### priorityQueue(worker, concurrency) + +The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects: + +* `push(task, priority, [callback])` - `priority` should be a number. If an array of + `tasks` is given, all tasks will be assigned the same priority. +* The `unshift` method was removed. + +--------------------------------------- + + +### cargo(worker, [payload]) + +Creates a `cargo` object with the specified payload. Tasks added to the +cargo will be processed altogether (up to the `payload` limit). If the +`worker` is in progress, the task is queued until it becomes available. Once +the `worker` has completed some tasks, each callback of those tasks is called. +Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work. + +While [queue](#queue) passes only one task to one of a group of workers +at a time, cargo passes an array of tasks to a single worker, repeating +when the worker is finished. + +__Arguments__ + +* `worker(tasks, callback)` - An asynchronous function for processing an array of + queued tasks, which must call its `callback(err)` argument when finished, with + an optional `err` argument. +* `payload` - An optional `integer` for determining how many tasks should be + processed per round; if omitted, the default is unlimited. + +__Cargo objects__ + +The `cargo` object returned by this function has the following properties and +methods: + +* `length()` - A function returning the number of items waiting to be processed. +* `payload` - An `integer` for determining how many tasks should be + process per round. This property can be changed after a `cargo` is created to + alter the payload on-the-fly. +* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called + once the `worker` has finished processing the task. Instead of a single task, an array of `tasks` + can be submitted. The respective callback is used for every task in the list. +* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued. +* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`. +* `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event calbacks as [`queue`](#queue) + +__Example__ + +```js +// create a cargo object with payload 2 + +var cargo = async.cargo(function (tasks, callback) { + for(var i=0; i +### auto(tasks, [concurrency], [callback]) + +Determines the best order for running the functions in `tasks`, based on their requirements. Each function can optionally depend on other functions being completed first, and each function is run as soon as its requirements are satisfied. + +If any of the functions pass an error to their callback, the `auto` sequence will stop. Further tasks will not execute (so any other functions depending on it will not run), and the main `callback` is immediately called with the error. Functions also receive an object containing the results of functions which have completed so far. + +Note, all functions are called with a `results` object as a second argument, +so it is unsafe to pass functions in the `tasks` object which cannot handle the +extra argument. + +For example, this snippet of code: + +```js +async.auto({ + readData: async.apply(fs.readFile, 'data.txt', 'utf-8') +}, callback); +``` + +will have the effect of calling `readFile` with the results object as the last +argument, which will fail: + +```js +fs.readFile('data.txt', 'utf-8', cb, {}); +``` + +Instead, wrap the call to `readFile` in a function which does not forward the +`results` object: + +```js +async.auto({ + readData: function(cb, results){ + fs.readFile('data.txt', 'utf-8', cb); + } +}, callback); +``` + +__Arguments__ + +* `tasks` - An object. Each of its properties is either a function or an array of + requirements, with the function itself the last item in the array. The object's key + of a property serves as the name of the task defined by that property, + i.e. can be used when specifying requirements for other tasks. + The function receives two arguments: (1) a `callback(err, result)` which must be + called when finished, passing an `error` (which can be `null`) and the result of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions. +* `concurrency` - An optional `integer` for determining the maximum number of tasks that can be run in parallel. By default, as many as possible. +* `callback(err, results)` - An optional callback which is called when all the + tasks have been completed. It receives the `err` argument if any `tasks` + pass an error to their callback. Results are always returned; however, if + an error occurs, no further `tasks` will be performed, and the results + object will only contain partial results. + + +__Example__ + +```js +async.auto({ + get_data: function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + make_folder: function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + }, + write_file: ['get_data', 'make_folder', function(callback, results){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + callback(null, 'filename'); + }], + email_link: ['write_file', function(callback, results){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + // results.write_file contains the filename returned by write_file. + callback(null, {'file':results.write_file, 'email':'user@example.com'}); + }] +}, function(err, results) { + console.log('err = ', err); + console.log('results = ', results); +}); +``` + +This is a fairly trivial example, but to do this using the basic parallel and +series functions would look like this: + +```js +async.parallel([ + function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + } +], +function(err, results){ + async.series([ + function(callback){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + results.push('filename'); + callback(null); + }, + function(callback){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + callback(null, {'file':results.pop(), 'email':'user@example.com'}); + } + ]); +}); +``` + +For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding +new tasks much easier (and the code more readable). + + +--------------------------------------- + + +### retry([opts = {times: 5, interval: 0}| 5], task, [callback]) + +Attempts to get a successful response from `task` no more than `times` times before +returning an error. If the task is successful, the `callback` will be passed the result +of the successful task. If all attempts fail, the callback will be passed the error and +result (if any) of the final attempt. + +__Arguments__ + +* `opts` - Can be either an object with `times` and `interval` or a number. + * `times` - The number of attempts to make before giving up. The default is `5`. + * `interval` - The time to wait between retries, in milliseconds. The default is `0`. + * If `opts` is a number, the number specifies the number of times to retry, with the default interval of `0`. +* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)` + which must be called when finished, passing `err` (which can be `null`) and the `result` of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions (if nested inside another control flow). +* `callback(err, results)` - An optional callback which is called when the + task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`. + +The [`retry`](#retry) function can be used as a stand-alone control flow by passing a callback, as shown below: + +```js +// try calling apiMethod 3 times +async.retry(3, apiMethod, function(err, result) { + // do something with the result +}); +``` + +```js +// try calling apiMethod 3 times, waiting 200 ms between each retry +async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + // do something with the result +}); +``` + +```js +// try calling apiMethod the default 5 times no delay between each retry +async.retry(apiMethod, function(err, result) { + // do something with the result +}); +``` + +It can also be embedded within other control flow functions to retry individual methods +that are not as reliable, like this: + +```js +async.auto({ + users: api.getUsers.bind(api), + payments: async.retry(3, api.getPayments.bind(api)) +}, function(err, results) { + // do something with the results +}); +``` + + +--------------------------------------- + + +### iterator(tasks) + +Creates an iterator function which calls the next function in the `tasks` array, +returning a continuation to call the next one after that. It's also possible to +“peek” at the next iterator with `iterator.next()`. + +This function is used internally by the `async` module, but can be useful when +you want to manually control the flow of functions in series. + +__Arguments__ + +* `tasks` - An array of functions to run. + +__Example__ + +```js +var iterator = async.iterator([ + function(){ sys.p('one'); }, + function(){ sys.p('two'); }, + function(){ sys.p('three'); } +]); + +node> var iterator2 = iterator(); +'one' +node> var iterator3 = iterator2(); +'two' +node> iterator3(); +'three' +node> var nextfn = iterator2.next(); +node> nextfn(); +'three' +``` + +--------------------------------------- + + +### apply(function, arguments..) + +Creates a continuation function with some arguments already applied. + +Useful as a shorthand when combined with other control flow functions. Any arguments +passed to the returned function are added to the arguments originally passed +to apply. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to automatically apply when the + continuation is called. + +__Example__ + +```js +// using apply + +async.parallel([ + async.apply(fs.writeFile, 'testfile1', 'test1'), + async.apply(fs.writeFile, 'testfile2', 'test2'), +]); + + +// the same process without using apply + +async.parallel([ + function(callback){ + fs.writeFile('testfile1', 'test1', callback); + }, + function(callback){ + fs.writeFile('testfile2', 'test2', callback); + } +]); +``` + +It's possible to pass any number of additional arguments when calling the +continuation: + +```js +node> var fn = async.apply(sys.puts, 'one'); +node> fn('two', 'three'); +one +two +three +``` + +--------------------------------------- + + +### nextTick(callback), setImmediate(callback) + +Calls `callback` on a later loop around the event loop. In Node.js this just +calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)` +if available, otherwise `setTimeout(callback, 0)`, which means other higher priority +events may precede the execution of `callback`. + +This is used internally for browser-compatibility purposes. + +__Arguments__ + +* `callback` - The function to call on a later loop around the event loop. + +__Example__ + +```js +var call_order = []; +async.nextTick(function(){ + call_order.push('two'); + // call_order now equals ['one','two'] +}); +call_order.push('one') +``` + + +### times(n, iterator, [callback]) + +Calls the `iterator` function `n` times, and accumulates results in the same manner +you would use with [`map`](#map). + +__Arguments__ + +* `n` - The number of times to run the function. +* `iterator` - The function to call `n` times. +* `callback` - see [`map`](#map) + +__Example__ + +```js +// Pretend this is some complicated async factory +var createUser = function(id, callback) { + callback(null, { + id: 'user' + id + }) +} +// generate 5 users +async.times(5, function(n, next){ + createUser(n, function(err, user) { + next(err, user) + }) +}, function(err, users) { + // we should now have 5 users +}); +``` + +__Related__ + +* timesSeries(n, iterator, [callback]) +* timesLimit(n, limit, iterator, [callback]) + + +## Utils + + +### memoize(fn, [hasher]) + +Caches the results of an `async` function. When creating a hash to store function +results against, the callback is omitted from the hash and an optional hash +function can be used. + +If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function. + +The cache of results is exposed as the `memo` property of the function returned +by `memoize`. + +__Arguments__ + +* `fn` - The function to proxy and cache results from. +* `hasher` - An optional function for generating a custom hash for storing + results. It has all the arguments applied to it apart from the callback, and + must be synchronous. + +__Example__ + +```js +var slow_fn = function (name, callback) { + // do something + callback(null, result); +}; +var fn = async.memoize(slow_fn); + +// fn can now be used as if it were slow_fn +fn('some name', function () { + // callback +}); +``` + + +### unmemoize(fn) + +Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized +form. Handy for testing. + +__Arguments__ + +* `fn` - the memoized function + +--------------------------------------- + + +### ensureAsync(fn) + +Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained. + +__Arguments__ + +* `fn` - an async function, one that expects a node-style callback as its last argument + +Returns a wrapped function with the exact same call signature as the function passed in. + +__Example__ + +```js +function sometimesAsync(arg, callback) { + if (cache[arg]) { + return callback(null, cache[arg]); // this would be synchronous!! + } else { + doSomeIO(arg, callback); // this IO would be asynchronous + } +} + +// this has a risk of stack overflows if many results are cached in a row +async.mapSeries(args, sometimesAsync, done); + +// this will defer sometimesAsync's callback if necessary, +// preventing stack overflows +async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + +``` + +--------------------------------------- + + +### constant(values...) + +Returns a function that when called, calls-back with the values provided. Useful as the first function in a `waterfall`, or for plugging values in to `auto`. + +__Example__ + +```js +async.waterfall([ + async.constant(42), + function (value, next) { + // value === 42 + }, + //... +], callback); + +async.waterfall([ + async.constant(filename, "utf8"), + fs.readFile, + function (fileData, next) { + //... + } + //... +], callback); + +async.auto({ + hostname: async.constant("https://server.net/"), + port: findFreePort, + launchServer: ["hostname", "port", function (cb, options) { + startServer(options, cb); + }], + //... +}, callback); + +``` + +--------------------------------------- + + + +### asyncify(func) + +__Alias:__ `wrapSync` + +Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback. + +__Example__ + +```js +async.waterfall([ + async.apply(fs.readFile, filename, "utf8"), + async.asyncify(JSON.parse), + function (data, next) { + // data is the result of parsing the text. + // If there was a parsing error, it would have been caught. + } +], callback) +``` + +If the function passed to `asyncify` returns a Promise, that promises's resolved/rejected state will be used to call the callback, rather than simply the synchronous return value. Example: + +```js +async.waterfall([ + async.apply(fs.readFile, filename, "utf8"), + async.asyncify(function (contents) { + return db.model.create(contents); + }), + function (model, next) { + // `model` is the instantiated model object. + // If there was an error, this function would be skipped. + } +], callback) +``` + +This also means you can asyncify ES2016 `async` functions. + +```js +var q = async.queue(async.asyncify(async function (file) { + var intermediateStep = await processFile(file); + return await somePromise(intermediateStep) +})); + +q.push(files); +``` + +--------------------------------------- + + +### log(function, arguments) + +Logs the result of an `async` function to the `console`. Only works in Node.js or +in browsers that support `console.log` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.log` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, 'hello ' + name); + }, 1000); +}; +``` +```js +node> async.log(hello, 'world'); +'hello world' +``` + +--------------------------------------- + + +### dir(function, arguments) + +Logs the result of an `async` function to the `console` using `console.dir` to +display the properties of the resulting object. Only works in Node.js or +in browsers that support `console.dir` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.dir` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, {hello: name}); + }, 1000); +}; +``` +```js +node> async.dir(hello, 'world'); +{hello: 'world'} +``` + +--------------------------------------- + + +### noConflict() + +Changes the value of `async` back to its original value, returning a reference to the +`async` object. diff --git a/5-3/node_modules/mongoose/node_modules/async/dist/async.js b/5-3/node_modules/mongoose/node_modules/async/dist/async.js new file mode 100644 index 0000000..31e7620 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/async/dist/async.js @@ -0,0 +1,1265 @@ +/*! + * async + * https://github.com/caolan/async + * + * Copyright 2010-2014 Caolan McMahon + * Released under the MIT license + */ +(function () { + + var async = {}; + function noop() {} + function identity(v) { + return v; + } + function toBool(v) { + return !!v; + } + function notId(v) { + return !v; + } + + // global on the server, window in the browser + var previous_async; + + // Establish the root object, `window` (`self`) in the browser, `global` + // on the server, or `this` in some virtual machines. We use `self` + // instead of `window` for `WebWorker` support. + var root = typeof self === 'object' && self.self === self && self || + typeof global === 'object' && global.global === global && global || + this; + + if (root != null) { + previous_async = root.async; + } + + async.noConflict = function () { + root.async = previous_async; + return async; + }; + + function only_once(fn) { + return function() { + if (fn === null) throw new Error("Callback was already called."); + fn.apply(this, arguments); + fn = null; + }; + } + + function _once(fn) { + return function() { + if (fn === null) return; + fn.apply(this, arguments); + fn = null; + }; + } + + //// cross-browser compatiblity functions //// + + var _toString = Object.prototype.toString; + + var _isArray = Array.isArray || function (obj) { + return _toString.call(obj) === '[object Array]'; + }; + + // Ported from underscore.js isObject + var _isObject = function(obj) { + var type = typeof obj; + return type === 'function' || type === 'object' && !!obj; + }; + + function _isArrayLike(arr) { + return _isArray(arr) || ( + // has a positive integer length property + typeof arr.length === "number" && + arr.length >= 0 && + arr.length % 1 === 0 + ); + } + + function _arrayEach(arr, iterator) { + var index = -1, + length = arr.length; + + while (++index < length) { + iterator(arr[index], index, arr); + } + } + + function _map(arr, iterator) { + var index = -1, + length = arr.length, + result = Array(length); + + while (++index < length) { + result[index] = iterator(arr[index], index, arr); + } + return result; + } + + function _range(count) { + return _map(Array(count), function (v, i) { return i; }); + } + + function _reduce(arr, iterator, memo) { + _arrayEach(arr, function (x, i, a) { + memo = iterator(memo, x, i, a); + }); + return memo; + } + + function _forEachOf(object, iterator) { + _arrayEach(_keys(object), function (key) { + iterator(object[key], key); + }); + } + + function _indexOf(arr, item) { + for (var i = 0; i < arr.length; i++) { + if (arr[i] === item) return i; + } + return -1; + } + + var _keys = Object.keys || function (obj) { + var keys = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + }; + + function _keyIterator(coll) { + var i = -1; + var len; + var keys; + if (_isArrayLike(coll)) { + len = coll.length; + return function next() { + i++; + return i < len ? i : null; + }; + } else { + keys = _keys(coll); + len = keys.length; + return function next() { + i++; + return i < len ? keys[i] : null; + }; + } + } + + // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) + // This accumulates the arguments passed into an array, after a given index. + // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). + function _restParam(func, startIndex) { + startIndex = startIndex == null ? func.length - 1 : +startIndex; + return function() { + var length = Math.max(arguments.length - startIndex, 0); + var rest = Array(length); + for (var index = 0; index < length; index++) { + rest[index] = arguments[index + startIndex]; + } + switch (startIndex) { + case 0: return func.call(this, rest); + case 1: return func.call(this, arguments[0], rest); + } + // Currently unused but handle cases outside of the switch statement: + // var args = Array(startIndex + 1); + // for (index = 0; index < startIndex; index++) { + // args[index] = arguments[index]; + // } + // args[startIndex] = rest; + // return func.apply(this, args); + }; + } + + function _withoutIndex(iterator) { + return function (value, index, callback) { + return iterator(value, callback); + }; + } + + //// exported async module functions //// + + //// nextTick implementation with browser-compatible fallback //// + + // capture the global reference to guard against fakeTimer mocks + var _setImmediate = typeof setImmediate === 'function' && setImmediate; + + var _delay = _setImmediate ? function(fn) { + // not a direct alias for IE10 compatibility + _setImmediate(fn); + } : function(fn) { + setTimeout(fn, 0); + }; + + if (typeof process === 'object' && typeof process.nextTick === 'function') { + async.nextTick = process.nextTick; + } else { + async.nextTick = _delay; + } + async.setImmediate = _setImmediate ? _delay : async.nextTick; + + + async.forEach = + async.each = function (arr, iterator, callback) { + return async.eachOf(arr, _withoutIndex(iterator), callback); + }; + + async.forEachSeries = + async.eachSeries = function (arr, iterator, callback) { + return async.eachOfSeries(arr, _withoutIndex(iterator), callback); + }; + + + async.forEachLimit = + async.eachLimit = function (arr, limit, iterator, callback) { + return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); + }; + + async.forEachOf = + async.eachOf = function (object, iterator, callback) { + callback = _once(callback || noop); + object = object || []; + + var iter = _keyIterator(object); + var key, completed = 0; + + while ((key = iter()) != null) { + completed += 1; + iterator(object[key], key, only_once(done)); + } + + if (completed === 0) callback(null); + + function done(err) { + completed--; + if (err) { + callback(err); + } + // Check key is null in case iterator isn't exhausted + // and done resolved synchronously. + else if (key === null && completed <= 0) { + callback(null); + } + } + }; + + async.forEachOfSeries = + async.eachOfSeries = function (obj, iterator, callback) { + callback = _once(callback || noop); + obj = obj || []; + var nextKey = _keyIterator(obj); + var key = nextKey(); + function iterate() { + var sync = true; + if (key === null) { + return callback(null); + } + iterator(obj[key], key, only_once(function (err) { + if (err) { + callback(err); + } + else { + key = nextKey(); + if (key === null) { + return callback(null); + } else { + if (sync) { + async.setImmediate(iterate); + } else { + iterate(); + } + } + } + })); + sync = false; + } + iterate(); + }; + + + + async.forEachOfLimit = + async.eachOfLimit = function (obj, limit, iterator, callback) { + _eachOfLimit(limit)(obj, iterator, callback); + }; + + function _eachOfLimit(limit) { + + return function (obj, iterator, callback) { + callback = _once(callback || noop); + obj = obj || []; + var nextKey = _keyIterator(obj); + if (limit <= 0) { + return callback(null); + } + var done = false; + var running = 0; + var errored = false; + + (function replenish () { + if (done && running <= 0) { + return callback(null); + } + + while (running < limit && !errored) { + var key = nextKey(); + if (key === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iterator(obj[key], key, only_once(function (err) { + running -= 1; + if (err) { + callback(err); + errored = true; + } + else { + replenish(); + } + })); + } + })(); + }; + } + + + function doParallel(fn) { + return function (obj, iterator, callback) { + return fn(async.eachOf, obj, iterator, callback); + }; + } + function doParallelLimit(fn) { + return function (obj, limit, iterator, callback) { + return fn(_eachOfLimit(limit), obj, iterator, callback); + }; + } + function doSeries(fn) { + return function (obj, iterator, callback) { + return fn(async.eachOfSeries, obj, iterator, callback); + }; + } + + function _asyncMap(eachfn, arr, iterator, callback) { + callback = _once(callback || noop); + arr = arr || []; + var results = _isArrayLike(arr) ? [] : {}; + eachfn(arr, function (value, index, callback) { + iterator(value, function (err, v) { + results[index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + + async.map = doParallel(_asyncMap); + async.mapSeries = doSeries(_asyncMap); + async.mapLimit = doParallelLimit(_asyncMap); + + // reduce only has a series version, as doing reduce in parallel won't + // work in many situations. + async.inject = + async.foldl = + async.reduce = function (arr, memo, iterator, callback) { + async.eachOfSeries(arr, function (x, i, callback) { + iterator(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); + }; + + async.foldr = + async.reduceRight = function (arr, memo, iterator, callback) { + var reversed = _map(arr, identity).reverse(); + async.reduce(reversed, memo, iterator, callback); + }; + + async.transform = function (arr, memo, iterator, callback) { + if (arguments.length === 3) { + callback = iterator; + iterator = memo; + memo = _isArray(arr) ? [] : {}; + } + + async.eachOf(arr, function(v, k, cb) { + iterator(memo, v, k, cb); + }, function(err) { + callback(err, memo); + }); + }; + + function _filter(eachfn, arr, iterator, callback) { + var results = []; + eachfn(arr, function (x, index, callback) { + iterator(x, function (v) { + if (v) { + results.push({index: index, value: x}); + } + callback(); + }); + }, function () { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + } + + async.select = + async.filter = doParallel(_filter); + + async.selectLimit = + async.filterLimit = doParallelLimit(_filter); + + async.selectSeries = + async.filterSeries = doSeries(_filter); + + function _reject(eachfn, arr, iterator, callback) { + _filter(eachfn, arr, function(value, cb) { + iterator(value, function(v) { + cb(!v); + }); + }, callback); + } + async.reject = doParallel(_reject); + async.rejectLimit = doParallelLimit(_reject); + async.rejectSeries = doSeries(_reject); + + function _createTester(eachfn, check, getResult) { + return function(arr, limit, iterator, cb) { + function done() { + if (cb) cb(getResult(false, void 0)); + } + function iteratee(x, _, callback) { + if (!cb) return callback(); + iterator(x, function (v) { + if (cb && check(v)) { + cb(getResult(true, x)); + cb = iterator = false; + } + callback(); + }); + } + if (arguments.length > 3) { + eachfn(arr, limit, iteratee, done); + } else { + cb = iterator; + iterator = limit; + eachfn(arr, iteratee, done); + } + }; + } + + async.any = + async.some = _createTester(async.eachOf, toBool, identity); + + async.someLimit = _createTester(async.eachOfLimit, toBool, identity); + + async.all = + async.every = _createTester(async.eachOf, notId, notId); + + async.everyLimit = _createTester(async.eachOfLimit, notId, notId); + + function _findGetResult(v, x) { + return x; + } + async.detect = _createTester(async.eachOf, identity, _findGetResult); + async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); + async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); + + async.sortBy = function (arr, iterator, callback) { + async.map(arr, function (x, callback) { + iterator(x, function (err, criteria) { + if (err) { + callback(err); + } + else { + callback(null, {value: x, criteria: criteria}); + } + }); + }, function (err, results) { + if (err) { + return callback(err); + } + else { + callback(null, _map(results.sort(comparator), function (x) { + return x.value; + })); + } + + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + }; + + async.auto = function (tasks, concurrency, callback) { + if (typeof arguments[1] === 'function') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = _once(callback || noop); + var keys = _keys(tasks); + var remainingTasks = keys.length; + if (!remainingTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = remainingTasks; + } + + var results = {}; + var runningTasks = 0; + + var hasError = false; + + var listeners = []; + function addListener(fn) { + listeners.unshift(fn); + } + function removeListener(fn) { + var idx = _indexOf(listeners, fn); + if (idx >= 0) listeners.splice(idx, 1); + } + function taskComplete() { + remainingTasks--; + _arrayEach(listeners.slice(0), function (fn) { + fn(); + }); + } + + addListener(function () { + if (!remainingTasks) { + callback(null, results); + } + }); + + _arrayEach(keys, function (k) { + if (hasError) return; + var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; + var taskCallback = _restParam(function(err, args) { + runningTasks--; + if (args.length <= 1) { + args = args[0]; + } + if (err) { + var safeResults = {}; + _forEachOf(results, function(val, rkey) { + safeResults[rkey] = val; + }); + safeResults[k] = args; + hasError = true; + + callback(err, safeResults); + } + else { + results[k] = args; + async.setImmediate(taskComplete); + } + }); + var requires = task.slice(0, task.length - 1); + // prevent dead-locks + var len = requires.length; + var dep; + while (len--) { + if (!(dep = tasks[requires[len]])) { + throw new Error('Has nonexistent dependency in ' + requires.join(', ')); + } + if (_isArray(dep) && _indexOf(dep, k) >= 0) { + throw new Error('Has cyclic dependencies'); + } + } + function ready() { + return runningTasks < concurrency && _reduce(requires, function (a, x) { + return (a && results.hasOwnProperty(x)); + }, true) && !results.hasOwnProperty(k); + } + if (ready()) { + runningTasks++; + task[task.length - 1](taskCallback, results); + } + else { + addListener(listener); + } + function listener() { + if (ready()) { + runningTasks++; + removeListener(listener); + task[task.length - 1](taskCallback, results); + } + } + }); + }; + + + + async.retry = function(times, task, callback) { + var DEFAULT_TIMES = 5; + var DEFAULT_INTERVAL = 0; + + var attempts = []; + + var opts = { + times: DEFAULT_TIMES, + interval: DEFAULT_INTERVAL + }; + + function parseTimes(acc, t){ + if(typeof t === 'number'){ + acc.times = parseInt(t, 10) || DEFAULT_TIMES; + } else if(typeof t === 'object'){ + acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; + acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; + } else { + throw new Error('Unsupported argument type for \'times\': ' + typeof t); + } + } + + var length = arguments.length; + if (length < 1 || length > 3) { + throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); + } else if (length <= 2 && typeof times === 'function') { + callback = task; + task = times; + } + if (typeof times !== 'function') { + parseTimes(opts, times); + } + opts.callback = callback; + opts.task = task; + + function wrappedTask(wrappedCallback, wrappedResults) { + function retryAttempt(task, finalAttempt) { + return function(seriesCallback) { + task(function(err, result){ + seriesCallback(!err || finalAttempt, {err: err, result: result}); + }, wrappedResults); + }; + } + + function retryInterval(interval){ + return function(seriesCallback){ + setTimeout(function(){ + seriesCallback(null); + }, interval); + }; + } + + while (opts.times) { + + var finalAttempt = !(opts.times-=1); + attempts.push(retryAttempt(opts.task, finalAttempt)); + if(!finalAttempt && opts.interval > 0){ + attempts.push(retryInterval(opts.interval)); + } + } + + async.series(attempts, function(done, data){ + data = data[data.length - 1]; + (wrappedCallback || opts.callback)(data.err, data.result); + }); + } + + // If a callback is passed, run this as a controll flow + return opts.callback ? wrappedTask() : wrappedTask; + }; + + async.waterfall = function (tasks, callback) { + callback = _once(callback || noop); + if (!_isArray(tasks)) { + var err = new Error('First argument to waterfall must be an array of functions'); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + function wrapIterator(iterator) { + return _restParam(function (err, args) { + if (err) { + callback.apply(null, [err].concat(args)); + } + else { + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } + else { + args.push(callback); + } + ensureAsync(iterator).apply(null, args); + } + }); + } + wrapIterator(async.iterator(tasks))(); + }; + + function _parallel(eachfn, tasks, callback) { + callback = callback || noop; + var results = _isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, function (task, key, callback) { + task(_restParam(function (err, args) { + if (args.length <= 1) { + args = args[0]; + } + results[key] = args; + callback(err); + })); + }, function (err) { + callback(err, results); + }); + } + + async.parallel = function (tasks, callback) { + _parallel(async.eachOf, tasks, callback); + }; + + async.parallelLimit = function(tasks, limit, callback) { + _parallel(_eachOfLimit(limit), tasks, callback); + }; + + async.series = function(tasks, callback) { + _parallel(async.eachOfSeries, tasks, callback); + }; + + async.iterator = function (tasks) { + function makeCallback(index) { + function fn() { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + } + fn.next = function () { + return (index < tasks.length - 1) ? makeCallback(index + 1): null; + }; + return fn; + } + return makeCallback(0); + }; + + async.apply = _restParam(function (fn, args) { + return _restParam(function (callArgs) { + return fn.apply( + null, args.concat(callArgs) + ); + }); + }); + + function _concat(eachfn, arr, fn, callback) { + var result = []; + eachfn(arr, function (x, index, cb) { + fn(x, function (err, y) { + result = result.concat(y || []); + cb(err); + }); + }, function (err) { + callback(err, result); + }); + } + async.concat = doParallel(_concat); + async.concatSeries = doSeries(_concat); + + async.whilst = function (test, iterator, callback) { + callback = callback || noop; + if (test()) { + var next = _restParam(function(err, args) { + if (err) { + callback(err); + } else if (test.apply(this, args)) { + iterator(next); + } else { + callback.apply(null, [null].concat(args)); + } + }); + iterator(next); + } else { + callback(null); + } + }; + + async.doWhilst = function (iterator, test, callback) { + var calls = 0; + return async.whilst(function() { + return ++calls <= 1 || test.apply(this, arguments); + }, iterator, callback); + }; + + async.until = function (test, iterator, callback) { + return async.whilst(function() { + return !test.apply(this, arguments); + }, iterator, callback); + }; + + async.doUntil = function (iterator, test, callback) { + return async.doWhilst(iterator, function() { + return !test.apply(this, arguments); + }, callback); + }; + + async.during = function (test, iterator, callback) { + callback = callback || noop; + + var next = _restParam(function(err, args) { + if (err) { + callback(err); + } else { + args.push(check); + test.apply(this, args); + } + }); + + var check = function(err, truth) { + if (err) { + callback(err); + } else if (truth) { + iterator(next); + } else { + callback(null); + } + }; + + test(check); + }; + + async.doDuring = function (iterator, test, callback) { + var calls = 0; + async.during(function(next) { + if (calls++ < 1) { + next(null, true); + } else { + test.apply(this, arguments); + } + }, iterator, callback); + }; + + function _queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + function _insert(q, data, pos, callback) { + if (callback != null && typeof callback !== "function") { + throw new Error("task callback must be a function"); + } + q.started = true; + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + q.drain(); + }); + } + _arrayEach(data, function(task) { + var item = { + data: task, + callback: callback || noop + }; + + if (pos) { + q.tasks.unshift(item); + } else { + q.tasks.push(item); + } + + if (q.tasks.length === q.concurrency) { + q.saturated(); + } + }); + async.setImmediate(q.process); + } + function _next(q, tasks) { + return function(){ + workers -= 1; + + var removed = false; + var args = arguments; + _arrayEach(tasks, function (task) { + _arrayEach(workersList, function (worker, index) { + if (worker === task && !removed) { + workersList.splice(index, 1); + removed = true; + } + }); + + task.callback.apply(task, args); + }); + if (q.tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + } + + var workers = 0; + var workersList = []; + var q = { + tasks: [], + concurrency: concurrency, + payload: payload, + saturated: noop, + empty: noop, + drain: noop, + started: false, + paused: false, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + kill: function () { + q.drain = noop; + q.tasks = []; + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + while(!q.paused && workers < q.concurrency && q.tasks.length){ + + var tasks = q.payload ? + q.tasks.splice(0, q.payload) : + q.tasks.splice(0, q.tasks.length); + + var data = _map(tasks, function (task) { + return task.data; + }); + + if (q.tasks.length === 0) { + q.empty(); + } + workers += 1; + workersList.push(tasks[0]); + var cb = only_once(_next(q, tasks)); + worker(data, cb); + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + }, + workersList: function () { + return workersList; + }, + idle: function() { + return q.tasks.length + workers === 0; + }, + pause: function () { + q.paused = true; + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + var resumeCount = Math.min(q.concurrency, q.tasks.length); + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= resumeCount; w++) { + async.setImmediate(q.process); + } + } + }; + return q; + } + + async.queue = function (worker, concurrency) { + var q = _queue(function (items, cb) { + worker(items[0], cb); + }, concurrency, 1); + + return q; + }; + + async.priorityQueue = function (worker, concurrency) { + + function _compareTasks(a, b){ + return a.priority - b.priority; + } + + function _binarySearch(sequence, item, compare) { + var beg = -1, + end = sequence.length - 1; + while (beg < end) { + var mid = beg + ((end - beg + 1) >>> 1); + if (compare(item, sequence[mid]) >= 0) { + beg = mid; + } else { + end = mid - 1; + } + } + return beg; + } + + function _insert(q, data, priority, callback) { + if (callback != null && typeof callback !== "function") { + throw new Error("task callback must be a function"); + } + q.started = true; + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + q.drain(); + }); + } + _arrayEach(data, function(task) { + var item = { + data: task, + priority: priority, + callback: typeof callback === 'function' ? callback : noop + }; + + q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); + + if (q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + // Start with a normal queue + var q = async.queue(worker, concurrency); + + // Override push to accept second parameter representing priority + q.push = function (data, priority, callback) { + _insert(q, data, priority, callback); + }; + + // Remove unshift function + delete q.unshift; + + return q; + }; + + async.cargo = function (worker, payload) { + return _queue(worker, 1, payload); + }; + + function _console_fn(name) { + return _restParam(function (fn, args) { + fn.apply(null, args.concat([_restParam(function (err, args) { + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } + else if (console[name]) { + _arrayEach(args, function (x) { + console[name](x); + }); + } + } + })])); + }); + } + async.log = _console_fn('log'); + async.dir = _console_fn('dir'); + /*async.info = _console_fn('info'); + async.warn = _console_fn('warn'); + async.error = _console_fn('error');*/ + + async.memoize = function (fn, hasher) { + var memo = {}; + var queues = {}; + var has = Object.prototype.hasOwnProperty; + hasher = hasher || identity; + var memoized = _restParam(function memoized(args) { + var callback = args.pop(); + var key = hasher.apply(null, args); + if (has.call(memo, key)) { + async.setImmediate(function () { + callback.apply(null, memo[key]); + }); + } + else if (has.call(queues, key)) { + queues[key].push(callback); + } + else { + queues[key] = [callback]; + fn.apply(null, args.concat([_restParam(function (args) { + memo[key] = args; + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, args); + } + })])); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + }; + + async.unmemoize = function (fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + }; + + function _times(mapper) { + return function (count, iterator, callback) { + mapper(_range(count), iterator, callback); + }; + } + + async.times = _times(async.map); + async.timesSeries = _times(async.mapSeries); + async.timesLimit = function (count, limit, iterator, callback) { + return async.mapLimit(_range(count), limit, iterator, callback); + }; + + async.seq = function (/* functions... */) { + var fns = arguments; + return _restParam(function (args) { + var that = this; + + var callback = args[args.length - 1]; + if (typeof callback == 'function') { + args.pop(); + } else { + callback = noop; + } + + async.reduce(fns, args, function (newargs, fn, cb) { + fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { + cb(err, nextargs); + })])); + }, + function (err, results) { + callback.apply(that, [err].concat(results)); + }); + }); + }; + + async.compose = function (/* functions... */) { + return async.seq.apply(null, Array.prototype.reverse.call(arguments)); + }; + + + function _applyEach(eachfn) { + return _restParam(function(fns, args) { + var go = _restParam(function(args) { + var that = this; + var callback = args.pop(); + return eachfn(fns, function (fn, _, cb) { + fn.apply(that, args.concat([cb])); + }, + callback); + }); + if (args.length) { + return go.apply(this, args); + } + else { + return go; + } + }); + } + + async.applyEach = _applyEach(async.eachOf); + async.applyEachSeries = _applyEach(async.eachOfSeries); + + + async.forever = function (fn, callback) { + var done = only_once(callback || noop); + var task = ensureAsync(fn); + function next(err) { + if (err) { + return done(err); + } + task(next); + } + next(); + }; + + function ensureAsync(fn) { + return _restParam(function (args) { + var callback = args.pop(); + args.push(function () { + var innerArgs = arguments; + if (sync) { + async.setImmediate(function () { + callback.apply(null, innerArgs); + }); + } else { + callback.apply(null, innerArgs); + } + }); + var sync = true; + fn.apply(this, args); + sync = false; + }); + } + + async.ensureAsync = ensureAsync; + + async.constant = _restParam(function(values) { + var args = [null].concat(values); + return function (callback) { + return callback.apply(this, args); + }; + }); + + async.wrapSync = + async.asyncify = function asyncify(func) { + return _restParam(function (args) { + var callback = args.pop(); + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (_isObject(result) && typeof result.then === "function") { + result.then(function(value) { + callback(null, value); + })["catch"](function(err) { + callback(err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); + }; + + // Node.js + if (typeof module === 'object' && module.exports) { + module.exports = async; + } + // AMD / RequireJS + else if (typeof define === 'function' && define.amd) { + define([], function () { + return async; + }); + } + // included directly via + + + + + +``` + +A simple example of how to use BSON in `node.js`: + +```javascript +var bson = require("bson"); +var BSON = new 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. + * **promoteBuffers** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. + * @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/5-3/node_modules/mongoose/node_modules/bson/alternate_parsers/bson.js b/5-3/node_modules/mongoose/node_modules/bson/alternate_parsers/bson.js new file mode 100644 index 0000000..555aa79 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/alternate_parsers/bson.js @@ -0,0 +1,1574 @@ +var Long = require('../lib/bson/long').Long + , Double = require('../lib/bson/double').Double + , Timestamp = require('../lib/bson/timestamp').Timestamp + , ObjectID = require('../lib/bson/objectid').ObjectID + , Symbol = require('../lib/bson/symbol').Symbol + , Code = require('../lib/bson/code').Code + , MinKey = require('../lib/bson/min_key').MinKey + , MaxKey = require('../lib/bson/max_key').MaxKey + , DBRef = require('../lib/bson/db_ref').DBRef + , Binary = require('../lib/bson/binary').Binary + , BinaryParser = require('../lib/bson/binary_parser').BinaryParser + , writeIEEE754 = require('../lib/bson/float_parser').writeIEEE754 + , readIEEE754 = require('../lib/bson/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 + */ +module.exports = BSON; +module.exports.Code = Code; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; diff --git a/5-3/node_modules/mongoose/node_modules/bson/alternate_parsers/faster_bson.js b/5-3/node_modules/mongoose/node_modules/bson/alternate_parsers/faster_bson.js new file mode 100644 index 0000000..f19e44f --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/alternate_parsers/faster_bson.js @@ -0,0 +1,429 @@ +/// reduced to ~ 410 LOCs (parser only 300 vs. 1400+) with (some, needed) BSON classes "inlined". +/// Compare ~ 4,300 (22KB vs. 157KB) in browser build at: https://github.com/mongodb/js-bson/blob/master/browser_build/bson.js + +module.exports.calculateObjectSize = calculateObjectSize; + +function calculateObjectSize(object) { + var totalLength = (4 + 1); /// handles the obj.length prefix + terminating '0' ?! + for(var key in object) { /// looks like it handles arrays under the same for...in loop!? + totalLength += calculateElement(key, object[key]) + } + return totalLength; +} + +function calculateElement(name, value) { + var len = 1; /// always starting with 1 for the data type byte! + if (name) len += Buffer.byteLength(name, 'utf8') + 1; /// cstring: name + '0' termination + + if (value === undefined || value === null) return len; /// just the type byte plus name cstring + switch( value.constructor ) { /// removed all checks 'isBuffer' if Node.js Buffer class is present!? + + case ObjectID: /// we want these sorted from most common case to least common/deprecated; + return len + 12; + case String: + return len + 4 + Buffer.byteLength(value, 'utf8') +1; /// + case Number: + if (Math.floor(value) === value) { /// case: integer; pos.# more common, '&&' stops if 1st fails! + if ( value <= 2147483647 && value >= -2147483647 ) // 32 bit + return len + 4; + else return len + 8; /// covers Long-ish JS integers as Longs! + } else return len + 8; /// 8+1 --- covers Double & std. float + case Boolean: + return len + 1; + + case Array: + case Object: + return len + calculateObjectSize(value); + + case Buffer: /// replaces the entire Binary class! + return len + 4 + value.length + 1; + + case Regex: /// these are handled as strings by serializeFast() later, hence 'gim' opts = 3 + 1 chars + return len + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) +1; + case Date: + case Long: + case Timestamp: + case Double: + return len + 8; + + case MinKey: + case MaxKey: + return len; /// these two return the type byte and name cstring only! + } + return 0; +} + +module.exports.serializeFast = serializeFast; +module.exports.serialize = function(object, checkKeys, asBuffer, serializeFunctions, index) { + var buffer = new Buffer(calculateObjectSize(object)); + return serializeFast(object, checkKeys, buffer, 0); +} + +function serializeFast(object, checkKeys, buffer, i) { /// set checkKeys = false in query(..., options object to save performance IFF you're certain your keys are safe/system-set! + var size = buffer.length; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; /// these get overwritten later! + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + if (object.constructor === Array) { /// any need to checkKeys here?!? since we're doing for rather than for...in, should be safe from extra (non-numeric) keys added to the array?! + for(var j = 0; j < object.length; j++) { + i = packElement(j.toString(), object[j], checkKeys, buffer, i); + } + } else { /// checkKeys is needed if any suspicion of end-user key tampering/"injection" (a la SQL) + for(var key in object) { /// mostly there should never be direct access to them!? + if (checkKeys && (key.indexOf('\x00') >= 0 || key === '$where') ) { /// = "no script"?!; could add back key.indexOf('$') or maybe check for 'eval'?! +/// took out: || key.indexOf('.') >= 0... Don't we allow dot notation queries?! + console.log('checkKeys error: '); + return new Error('Illegal object key!'); + } + i = packElement(key, object[key], checkKeys, buffer, i); /// checkKeys pass needed for recursion! + } + } + buffer[i++] = 0; /// write terminating zero; !we do NOT -1 the index increase here as original does! + return i; +} + +function packElement(name, value, checkKeys, buffer, i) { /// serializeFunctions removed! checkKeys needed for Array & Object cases pass through (calling serializeFast recursively!) + if (value === undefined || value === null){ + buffer[i++] = 10; /// = BSON.BSON_DATA_NULL; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; /// buffer.write(...) returns bytesWritten! + return i; + } + switch(value.constructor) { + + case ObjectID: + buffer[i++] = 7; /// = BSON.BSON_DATA_OID; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// i += buffer.write(value.id, i, 'binary'); /// OLD: writes a String to a Buffer; 'binary' deprecated!! + value.id.copy(buffer, i); /// NEW ObjectID version has this.id = Buffer at the ready! + return i += 12; + + case String: + buffer[i++] = 2; /// = BSON.BSON_DATA_STRING; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + + var size = Buffer.byteLength(value) + 1; /// includes the terminating '0'!? + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + i += buffer.write(value, i, 'utf8'); buffer[i++] = 0; + return i; + + case Number: + if ( ~~(value) === value) { /// double-Tilde is equiv. to Math.floor(value) + if ( value <= 2147483647 && value >= -2147483647){ /// = BSON.BSON_INT32_MAX / MIN asf. + buffer[i++] = 16; /// = BSON.BSON_DATA_INT; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + buffer[i++] = value & 0xff; buffer[i++] = (value >> 8) & 0xff; + buffer[i++] = (value >> 16) & 0xff; buffer[i++] = (value >> 24) & 0xff; + +// Else large-ish JS int!? to Long!? + } else { /// if (value <= BSON.JS_INT_MAX && value >= BSON.JS_INT_MIN){ /// 9007199254740992 asf. + buffer[i++] = 18; /// = BSON.BSON_DATA_LONG; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var lowBits = ( value % 4294967296 ) | 0, highBits = ( value / 4294967296 ) | 0; + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + } + } else { /// we have a float / Double + buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); + buffer.writeDoubleLE(value, i); i += 8; + } + return i; + + case Boolean: + buffer[i++] = 8; /// = BSON.BSON_DATA_BOOLEAN; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + buffer[i++] = value ? 1 : 0; + return i; + + case Array: + case Object: + buffer[i++] = value.constructor === Array ? 4 : 3; /// = BSON.BSON_DATA_ARRAY / _OBJECT; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + + var endIndex = serializeFast(value, checkKeys, buffer, i); /// + 4); no longer needed b/c serializeFast writes a temp 4 bytes for length + var size = endIndex - i; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + return endIndex; + + /// case Binary: /// is basically identical unless special/deprecated options! + case Buffer: /// solves ALL of our Binary needs without the BSON.Binary class!? + buffer[i++] = 5; /// = BSON.BSON_DATA_BINARY; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var size = value.length; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + buffer[i++] = 0; /// write BSON.BSON_BINARY_SUBTYPE_DEFAULT; + value.copy(buffer, i); ///, 0, size); << defaults to sourceStart=0, sourceEnd=sourceBuffer.length); + i += size; + return i; + + case RegExp: + buffer[i++] = 11; /// = BSON.BSON_DATA_REGEXP; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + i += buffer.write(value.source, i, 'utf8'); buffer[i++] = 0x00; + + if (value.global) buffer[i++] = 0x73; // s = 'g' for JS Regex! + if (value.ignoreCase) buffer[i++] = 0x69; // i + if (value.multiline) buffer[i++] = 0x6d; // m + buffer[i++] = 0x00; + return i; + + case Date: + buffer[i++] = 9; /// = BSON.BSON_DATA_DATE; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var millis = value.getTime(); + var lowBits = ( millis % 4294967296 ) | 0, highBits = ( millis / 4294967296 ) | 0; + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + return i; + + case Long: + case Timestamp: + buffer[i++] = value.constructor === Long ? 18 : 17; /// = BSON.BSON_DATA_LONG / _TIMESTAMP + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var lowBits = value.getLowBits(), highBits = value.getHighBits(); + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + return i; + + case Double: + buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); i += 8; + buffer.writeDoubleLE(value, i); i += 8; + return i + + case MinKey: /// = BSON.BSON_DATA_MINKEY; + buffer[i++] = 127; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + return i; + case MaxKey: /// = BSON.BSON_DATA_MAXKEY; + buffer[i++] = 255; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + return i; + + } /// end of switch + return i; /// ?! If no value to serialize +} + + +module.exports.deserializeFast = deserializeFast; + +function deserializeFast(buffer, i, isArray){ //// , options, isArray) { //// no more options! + if (buffer.length < 5) return new Error('Corrupt bson message < 5 bytes long'); /// from 'throw' + var elementType, tempindex = 0, name; + var string, low, high; /// = lowBits / highBits + /// using 'i' as the index to keep the lines shorter: + i || ( i = 0 ); /// for parseResponse it's 0; set to running index in deserialize(object/array) recursion + var object = isArray ? [] : {}; /// needed for type ARRAY recursion later! + var size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + if(size < 5 || size > buffer.length) return new Error('Corrupt BSON message'); +/// 'size' var was not used by anything after this, so we can reuse it + + while(true) { // While we have more left data left keep parsing + elementType = buffer[i++]; // Read the type + if (elementType === 0) break; // If we get a zero it's the last byte, exit + + tempindex = i; /// inlined readCStyleString & removed extra i= buffer.length) return new Error('Corrupt BSON document: illegal CString') + name = buffer.toString('utf8', i, tempindex); + i = tempindex + 1; /// Update index position to after the string + '0' termination + + switch(elementType) { + + case 7: /// = BSON.BSON_DATA_OID: + var buf = new Buffer(12); + buffer.copy(buf, 0, i, i += 12 ); /// copy 12 bytes from the current 'i' offset into fresh Buffer + object[name] = new ObjectID(buf); ///... & attach to the new ObjectID instance + break; + + case 2: /// = BSON.BSON_DATA_STRING: + size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; + object[name] = buffer.toString('utf8', i, i += size -1 ); + i++; break; /// need to get the '0' index "tick-forward" back! + + case 16: /// = BSON.BSON_DATA_INT: // Decode the 32bit value + object[name] = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; break; + + case 1: /// = BSON.BSON_DATA_NUMBER: // Decode the double value + object[name] = buffer.readDoubleLE(i); /// slightly faster depending on dec.points; a LOT cleaner + /// OLD: object[name] = readIEEE754(buffer, i, 'little', 52, 8); + i += 8; break; + + case 8: /// = BSON.BSON_DATA_BOOLEAN: + object[name] = buffer[i++] == 1; break; + + case 6: /// = BSON.BSON_DATA_UNDEFINED: /// deprecated + case 10: /// = BSON.BSON_DATA_NULL: + object[name] = null; break; + + case 4: /// = BSON.BSON_DATA_ARRAY + size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; /// NO 'i' increment since the size bytes are reread during the recursion! + object[name] = deserializeFast(buffer, i, true ); /// pass current index & set isArray = true + i += size; break; + case 3: /// = BSON.BSON_DATA_OBJECT: + size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; + object[name] = deserializeFast(buffer, i, false ); /// isArray = false => Object + i += size; break; + + case 5: /// = BSON.BSON_DATA_BINARY: // Decode the size of the binary blob + size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + buffer[i++]; /// Skip, as we assume always default subtype, i.e. 0! + object[name] = buffer.slice(i, i += size); /// creates a new Buffer "slice" view of the same memory! + break; + + case 9: /// = BSON.BSON_DATA_DATE: /// SEE notes below on the Date type vs. other options... + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + object[name] = new Date( high * 4294967296 + (low < 0 ? low + 4294967296 : low) ); break; + + case 18: /// = BSON.BSON_DATA_LONG: /// usage should be somewhat rare beyond parseResponse() -> cursorId, where it is handled inline, NOT as part of deserializeFast(returnedObjects); get lowBits, highBits: + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + + size = high * 4294967296 + (low < 0 ? low + 4294967296 : low); /// from long.toNumber() + if (size < JS_INT_MAX && size > JS_INT_MIN) object[name] = size; /// positive # more likely! + else object[name] = new Long(low, high); break; + + case 127: /// = BSON.BSON_DATA_MIN_KEY: /// do we EVER actually get these BACK from MongoDB server?! + object[name] = new MinKey(); break; + case 255: /// = BSON.BSON_DATA_MAX_KEY: + object[name] = new MaxKey(); break; + + case 17: /// = BSON.BSON_DATA_TIMESTAMP: /// somewhat obscure internal BSON type; MongoDB uses it for (pseudo) high-res time timestamp (past millisecs precision is just a counter!) in the Oplog ts: field, etc. + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + object[name] = new Timestamp(low, high); break; + +/// case 11: /// = RegExp is skipped; we should NEVER be getting any from the MongoDB server!? + } /// end of switch(elementType) + } /// end of while(1) + return object; // Return the finalized object +} + + +function MinKey() { this._bsontype = 'MinKey'; } /// these are merely placeholders/stubs to signify the type!? + +function MaxKey() { this._bsontype = 'MaxKey'; } + +function Long(low, high) { + this._bsontype = 'Long'; + this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. +} +Long.prototype.getLowBits = function(){ return this.low_; } +Long.prototype.getHighBits = function(){ return this.high_; } + +Long.prototype.toNumber = function(){ + return this.high_ * 4294967296 + (this.low_ < 0 ? this.low_ + 4294967296 : this.low_); +} +Long.fromNumber = function(num){ + return new Long(num % 4294967296, num / 4294967296); /// |0 is forced in the constructor! +} +function Double(value) { + this._bsontype = 'Double'; + this.value = value; +} +function Timestamp(low, high) { + this._bsontype = 'Timestamp'; + this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. +} +Timestamp.prototype.getLowBits = function(){ return this.low_; } +Timestamp.prototype.getHighBits = function(){ return this.high_; } + +/////////////////////////////// ObjectID ///////////////////////////////// +/// machine & proc IDs stored as 1 string, b/c Buffer shouldn't be held for long periods (could use SlowBuffer?!) + +var MACHINE = parseInt(Math.random() * 0xFFFFFF, 10); +var PROCESS = process.pid % 0xFFFF; +var MACHINE_AND_PROC = encodeIntBE(MACHINE, 3) + encodeIntBE(PROCESS, 2); /// keep as ONE string, ready to go. + +function encodeIntBE(data, bytes){ /// encode the bytes to a string + var result = ''; + if (bytes >= 4){ result += String.fromCharCode(Math.floor(data / 0x1000000)); data %= 0x1000000; } + if (bytes >= 3){ result += String.fromCharCode(Math.floor(data / 0x10000)); data %= 0x10000; } + if (bytes >= 2){ result += String.fromCharCode(Math.floor(data / 0x100)); data %= 0x100; } + result += String.fromCharCode(Math.floor(data)); + return result; +} +var _counter = ~~(Math.random() * 0xFFFFFF); /// double-tilde is equivalent to Math.floor() +var checkForHex = new RegExp('^[0-9a-fA-F]{24}$'); + +function ObjectID(id) { + this._bsontype = 'ObjectID'; + if (!id){ this.id = createFromScratch(); /// base case, DONE. + } else { + if (id.constructor === Buffer){ + this.id = id; /// case of + } else if (id.constructor === String) { + if ( id.length === 24 && checkForHex.test(id) ) { + this.id = new Buffer(id, 'hex'); + } else { + this.id = new Error('Illegal/faulty Hexadecimal string supplied!'); /// changed from 'throw' + } + } else if (id.constructor === Number) { + this.id = createFromTime(id); /// this is what should be the only interface for this!? + } + } +} +function createFromScratch() { + var buf = new Buffer(12), i = 0; + var ts = ~~(Date.now()/1000); /// 4 bytes timestamp in seconds, BigEndian notation! + buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; + buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; + + buf.write(MACHINE_AND_PROC, i, 5, 'utf8'); i += 5; /// write 3 bytes + 2 bytes MACHINE_ID and PROCESS_ID + _counter = ++_counter % 0xFFFFFF; /// 3 bytes internal _counter for subsecond resolution; BigEndian + buf[i++] = (_counter >> 16) & 0xFF; + buf[i++] = (_counter >> 8) & 0xFF; + buf[i++] = (_counter) & 0xFF; + return buf; +} +function createFromTime(ts) { + ts || ( ts = ~~(Date.now()/1000) ); /// 4 bytes timestamp in seconds only + var buf = new Buffer(12), i = 0; + buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; + buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; + + for (;i < 12; ++i) buf[i] = 0x00; /// indeces 4 through 11 (8 bytes) get filled up with nulls + return buf; +} +ObjectID.prototype.toHexString = function toHexString() { + return this.id.toString('hex'); +} +ObjectID.prototype.getTimestamp = function getTimestamp() { + return this.id.readUIntBE(0, 4); +} +ObjectID.prototype.getTimestampDate = function getTimestampDate() { + var ts = new Date(); + ts.setTime(this.id.readUIntBE(0, 4) * 1000); + return ts; +} +ObjectID.createPk = function createPk () { ///?override if a PrivateKey factory w/ unique factors is warranted?! + return new ObjectID(); +} +ObjectID.prototype.toJSON = function toJSON() { + return "ObjectID('" +this.id.toString('hex')+ "')"; +} + +/// module.exports.BSON = BSON; /// not needed anymore!? exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.Long = Long; /// ?! we really don't want to do the complicated Long math anywhere for now!? + +//module.exports.Double = Double; +//module.exports.Timestamp = Timestamp; diff --git a/5-3/node_modules/mongoose/node_modules/bson/bower.json b/5-3/node_modules/mongoose/node_modules/bson/bower.json new file mode 100644 index 0000000..b32140e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/bower.json @@ -0,0 +1,25 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "author": "Christian Amor Kvalheim ", + "main": "./browser_build/bson.js", + "license": "Apache-2.0", + "moduleType": [ + "globals", + "node" + ], + "ignore": [ + "**/.*", + "alternate_parsers", + "benchmarks", + "bower_components", + "node_modules", + "test", + "tools" + ] +} diff --git a/5-3/node_modules/mongoose/node_modules/bson/browser_build/bson.js b/5-3/node_modules/mongoose/node_modules/bson/browser_build/bson.js new file mode 100644 index 0000000..8e942dd --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/browser_build/bson.js @@ -0,0 +1,4843 @@ +var bson = (function(){ + + var pkgmap = {}, + global = {}, + nativeRequire = typeof require != 'undefined' && require, + lib, ties, main, async; + + function exports(){ return main(); }; + + exports.main = exports; + exports.module = module; + exports.packages = pkgmap; + exports.pkg = pkg; + exports.require = function require(uri){ + return pkgmap.main.index.require(uri); + }; + + + ties = {}; + + aliases = {}; + + + return exports; + +function join() { + return normalize(Array.prototype.join.call(arguments, "/")); +}; + +function normalize(path) { + var ret = [], parts = path.split('/'), cur, prev; + + var i = 0, l = parts.length-1; + for (; i <= l; i++) { + cur = parts[i]; + + if (cur === "." && prev !== undefined) continue; + + if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { + ret.pop(); + prev = ret.slice(-1)[0]; + } else { + if (prev === ".") ret.pop(); + ret.push(cur); + prev = cur; + } + } + + return ret.join("/"); +}; + +function dirname(path) { + return path && path.substr(0, path.lastIndexOf("/")) || "."; +}; + +function findModule(workingModule, uri){ + var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), + moduleIndexId = join(moduleId, 'index'), + pkg = workingModule.pkg, + module; + + var i = pkg.modules.length, + id; + + while(i-->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/5-3/node_modules/mongoose/node_modules/bson/browser_build/package.json b/5-3/node_modules/mongoose/node_modules/bson/browser_build/package.json new file mode 100644 index 0000000..3ebb587 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/browser_build/package.json @@ -0,0 +1,8 @@ +{ "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/5-3/node_modules/mongoose/node_modules/bson/deserializer_bak.js b/5-3/node_modules/mongoose/node_modules/bson/deserializer_bak.js new file mode 100644 index 0000000..c879ad5 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/deserializer_bak.js @@ -0,0 +1,357 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754, + readIEEE754 = require('../float_parser').readIEEE754, + f = require('util').format, + 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, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var BSON = {}; + +/** + * 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 = {}; + +/** + * 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; + +// 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. + +var deserialize = function(buffer, options, isArray) { + var index = 0; + // 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 || buffer.length < size) { + throw new Error("corrupt bson message"); + } + + // Illegal end value + if(buffer[size - 1] != 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, options, isArray); +} + +// // Reads in a C style string +// var readCStyleStringSpecial = function(buffer, index) { +// // 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 = buffer.toString('utf8', index, i); +// // Update index position +// index = i + 1; +// // Return string +// return {s: string, i: index}; +// } + +// Reads in a C style string +var readCStyleStringSpecial = function(buffer, index) { + // 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 + return buffer.toString('utf8', index, i); +} + +var DeserializationMethods = {} +DeserializationMethods[BSON.BSON_DATA_OID] = function(name, object, buffer, index) { + var string = buffer.toString('binary', index, index + 12); + object[name] = new ObjectID(string); + return index + 12; +} + +DeserializationMethods[BSON.BSON_DATA_NUMBER] = function(name, object, buffer, index) { + object[name] = buffer.readDoubleLE(index); + return index + 8; +} + +DeserializationMethods[BSON.BSON_DATA_INT] = function(name, object, buffer, index) { + object[name] = buffer.readInt32LE(index); + return index + 4; +} + +DeserializationMethods[BSON.BSON_DATA_TIMESTAMP] = function(name, object, buffer, index) { + 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; + object[name] = new Timestamp(lowBits, highBits); + return index; +} + +DeserializationMethods[BSON.BSON_DATA_STRING] = function(name, object, buffer, index) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + return index + stringSize; +} + +DeserializationMethods[BSON.BSON_DATA_BOOLEAN] = function(name, object, buffer, index) { + object[name] = buffer[index++] == 1; + return index; +} + +var deserializeObject = 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']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? {} : options['fieldsAsRaw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + + // 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; + + // 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"); + + // Create holding object + var object = isArray ? [] : {}; + + // 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; + var name = readCStyleStringSpecial(buffer, index); + index = index + name.length + 1; + + // console.log("----------- 0 " + elementType + " :: " + name) + index = DeserializationMethods[elementType](name, object, buffer, index); + // console.log('--------------- 1') + } + + // 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; +} + +/** + * 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; +} + +module.exports = deserialize diff --git a/5-3/node_modules/mongoose/node_modules/bson/lib/bson/binary.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/binary.js new file mode 100644 index 0000000..ef74b16 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/binary.js @@ -0,0 +1,344 @@ +/** + * 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, offset, 'binary'); + 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; diff --git a/5-3/node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js new file mode 100644 index 0000000..d2fc811 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js @@ -0,0 +1,385 @@ +/** + * 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/5-3/node_modules/mongoose/node_modules/bson/lib/bson/bson.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/bson.js new file mode 100644 index 0000000..36f0057 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/bson.js @@ -0,0 +1,323 @@ +// "use strict" + +var writeIEEE754 = require('./float_parser').writeIEEE754, + readIEEE754 = require('./float_parser').readIEEE754, + Map = require('./map'), + Long = require('./long').Long, + Double = require('./double').Double, + Timestamp = require('./timestamp').Timestamp, + ObjectID = require('./objectid').ObjectID, + BSONRegExp = require('./regexp').BSONRegExp, + 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; + +// Parts of the parser +var deserialize = require('./parser/deserializer'), + serializer = require('./parser/serializer'), + calculateObjectSize = require('./parser/calculate_size'); + +/** + * @ignore + * @api private + */ +// Max Size +var MAXSIZE = (1024*1024*17); +// Max Document Buffer size +var buffer = new Buffer(MAXSIZE); + +var BSON = function() { +} + +/** + * 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 serialize(object, checkKeys, asBuffer, serializeFunctions, index, ignoreUndefined) { + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, index || 0, 0, serializeFunctions, ignoreUndefined); + // Create the final buffer + var finishedBuffer = new Buffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +} + +/** + * 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, finalBuffer, startIndex, serializeFunctions, ignoreUndefined) { + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; +} + +/** + * 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.prototype.deserialize = function(data, options) { + return deserialize(data, options); +} + +/** + * 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, ignoreUndefined) { + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); +} + +/** + * 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.prototype.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] = this.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; +} + +/** + * @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 +module.exports = BSON; +module.exports.Code = Code; +module.exports.Map = Map; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.BSONRegExp = BSONRegExp; diff --git a/5-3/node_modules/mongoose/node_modules/bson/lib/bson/code.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/code.js new file mode 100644 index 0000000..83a42c9 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * 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/5-3/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js new file mode 100644 index 0000000..06789a6 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * 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/5-3/node_modules/mongoose/node_modules/bson/lib/bson/double.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/double.js new file mode 100644 index 0000000..09ed222 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * 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/5-3/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js new file mode 100644 index 0000000..6fca392 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js @@ -0,0 +1,121 @@ +// 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/5-3/node_modules/mongoose/node_modules/bson/lib/bson/index.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/index.js new file mode 100644 index 0000000..eca45cd --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/index.js @@ -0,0 +1,86 @@ +try { + exports.BSONPure = require('./bson'); + exports.BSONNative = require('./bson'); +} catch(err) { +} + +[ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './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 PURE JS BSON Parser +exports.pure = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './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; +} + +// Exports all the classes for the NATIVE JS BSON Parser +exports.native = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './symbol' + , './timestamp' + , './long' + ].forEach(function (path) { + var module = require(path); + for (var i in module) { + classes[i] = module[i]; + } + }); + + // Catch error and return no classes found + try { + classes['BSON'] = require('./bson'); + } catch(err) { + return exports.pure(); + } + + // Return classes list + return classes; +} diff --git a/5-3/node_modules/mongoose/node_modules/bson/lib/bson/long.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/long.js new file mode 100644 index 0000000..6f18885 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/long.js @@ -0,0 +1,856 @@ +// 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/5-3/node_modules/mongoose/node_modules/bson/lib/bson/map.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/map.js new file mode 100644 index 0000000..f53c8c1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/map.js @@ -0,0 +1,126 @@ +"use strict" + +// We have an ES6 Map available, return the native instance +if(typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; +} else { + // We will return a polyfill + var Map = function(array) { + this._keys = []; + this._values = {}; + + for(var i = 0; i < array.length; i++) { + if(array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = {v: value, i: this._keys.length - 1}; + } + } + + Map.prototype.clear = function() { + this._keys = []; + this._values = {}; + } + + Map.prototype.delete = function(key) { + var value = this._values[key]; + if(value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + } + + Map.prototype.entries = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + Map.prototype.forEach = function(callback, self) { + self = self || this; + + for(var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + } + + Map.prototype.get = function(key) { + return this._values[key] ? this._values[key].v : undefined; + } + + Map.prototype.has = function(key) { + return this._values[key] != null; + } + + Map.prototype.keys = function(key) { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + Map.prototype.set = function(key, value) { + if(this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = {v: value, i: this._keys.length - 1}; + return this; + } + + Map.prototype.values = function(key, value) { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable:true, + get: function() { return this._keys.length; } + }); + + module.exports = Map; + module.exports.Map = Map; +} \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js new file mode 100644 index 0000000..03ee9cd --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * 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/5-3/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js new file mode 100644 index 0000000..5e120fb --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * 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/5-3/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js new file mode 100644 index 0000000..4c2f7cf --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js @@ -0,0 +1,278 @@ +/** + * 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) { + var id; + + if(otherID != null && (otherID instanceof ObjectID || otherID.toHexString)) { + id = otherID.id; + } else if(typeof otherID == 'string' && ObjectID.isValid(otherID)) { + id = ObjectID.createFromHexString(otherID).id; + } else { + return false; + } + + 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(typeof id == 'number') + return true; + if(typeof id == 'string') { + return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id)); + } + return false; +}; + +/** +* @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; diff --git a/5-3/node_modules/mongoose/node_modules/bson/lib/bson/parser/calculate_size.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/parser/calculate_size.js new file mode 100644 index 0000000..03513f3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/parser/calculate_size.js @@ -0,0 +1,310 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754 + , readIEEE754 = require('../float_parser').readIEEE754 + , Long = require('../long').Long + , Double = require('../double').Double + , Timestamp = require('../timestamp').Timestamp + , ObjectID = require('../objectid').ObjectID + , Symbol = require('../symbol').Symbol + , BSONRegExp = require('../regexp').BSONRegExp + , Code = require('../code').Code + , MinKey = require('../min_key').MinKey + , MaxKey = require('../max_key').MaxKey + , DBRef = require('../db_ref').DBRef + , Binary = require('../binary').Binary; + +// 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]'; +} + +var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined) + } + } 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, false, ignoreUndefined) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + switch(typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + 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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } + case 'undefined': + if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); + return 0; + case 'boolean': + return (name != null ? (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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? (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 ? (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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + + Buffer.byteLength(value.options, 'utf8') + 1 + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 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 ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else if(serializeFunctions) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; + } + } + } + + return 0; +} + +var BSON = {}; + +/** + * 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 = {}; + +/** + * 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; + +// 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. + +module.exports = calculateObjectSize; diff --git a/5-3/node_modules/mongoose/node_modules/bson/lib/bson/parser/deserializer.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/parser/deserializer.js new file mode 100644 index 0000000..505ea59 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/parser/deserializer.js @@ -0,0 +1,525 @@ +"use strict" + +var readIEEE754 = require('../float_parser').readIEEE754, + f = require('util').format, + 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, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var deserialize = function(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // 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 || buffer.length < size) { + throw new Error("corrupt bson message"); + } + + // Illegal end value + if(buffer[size - 1] != 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index - 4, options, isArray); +} + +var deserializeObject = function(buffer, index, options, isArray) { + 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']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + var raw = options['raw'] == null ? false : options['raw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // 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"); + + // Create holding object + var object = isArray ? [] : {}; + + // 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; + + // 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") + var name = buffer.toString('utf8', index, i); + + index = i + 1; + + if(elementType == BSON.BSON_DATA_STRING) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_OID) { + var string = buffer.toString('binary', index, index + 12); + object[name] = new ObjectID(string); + index = index + 12; + } else if(elementType == BSON.BSON_DATA_INT) { + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } else if(elementType == BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if(elementType == BSON.BSON_DATA_DATE) { + 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; + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if(elementType == BSON.BSON_DATA_BOOLEAN) { + object[name] = buffer[index++] == 1; + } else if(elementType == BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + if(objectSize <= 0 || objectSize > (buffer.length - index)) throw new Error("bad embedded document length in bson"); + + // We have a raw value + if(raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if(elementType == BSON.BSON_DATA_ARRAY) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + var arrayOptions = options; + + // All elements of array to be returned as raw bson + if(fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for(var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + } else if(elementType == BSON.BSON_DATA_UNDEFINED || elementType == BSON.BSON_DATA_NULL) { + object[name] = null; + } else if(elementType == 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; + 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; + } + } else if(elementType == BSON.BSON_DATA_BINARY) { + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + 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; + } + if(promoteBuffers) { + object[name] = buffer.slice(index, index + binarySize); + } else { + 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]; + } + if(promoteBuffers) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + // Update the index + index = index + binarySize; + } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == false) { + // 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") + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // 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") + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // 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('')); + } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == true) { + // 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") + // Return the C string + var source = buffer.toString('utf8', index, i); + index = i + 1; + + // 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") + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if(elementType == BSON.BSON_DATA_SYMBOL) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_TIMESTAMP) { + 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; + object[name] = new Timestamp(lowBits, highBits); + } else if(elementType == BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if(elementType == BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if(elementType == BSON.BSON_DATA_CODE) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + 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 { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_CODE_W_SCOPE) { + 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; + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Javascript function + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + var _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 = deserializeObject(buffer, _index, 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 { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; +} + +/** + * 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; +} + +var BSON = {}; + +/** + * 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 = {}; + +/** + * 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; + +// 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. + +module.exports = deserialize diff --git a/5-3/node_modules/mongoose/node_modules/bson/lib/bson/parser/serializer.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/parser/serializer.js new file mode 100644 index 0000000..b991aec --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/parser/serializer.js @@ -0,0 +1,912 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754, + readIEEE754 = require('../float_parser').readIEEE754, + Long = require('../long').Long, + Map = require('../map'), + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + BSONRegExp = require('../regexp').BSONRegExp, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + DBRef = require('../db_ref').DBRef, + Binary = require('../binary').Binary; + +var regexp = /\x00/ + +// 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]'; +} + +var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} + +var serializeString = function(buffer, 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; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = (size + 1 >> 24) & 0xff; + buffer[index + 2] = (size + 1 >> 16) & 0xff; + buffer[index + 1] = (size + 1 >> 8) & 0xff; + buffer[index] = size + 1 & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeNumber = function(buffer, 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(buffer, 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(buffer, 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(buffer, 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(buffer, 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; + if (value.source && value.source.match(regexp) != null) { + throw Error("value " + value.source + " must not contain null bytes"); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // 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 serializeBSONRegExp = function(buffer, 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; + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options, index, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +var serializeMinMax = function(buffer, 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(buffer, 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; + + // Write the objectId into the shared buffer + buffer.write(value.id, index, 'binary') + + // Ajust index + return index + 12; +} + +var serializeBuffer = function(buffer, 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(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { + // 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(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + // Write size + var size = endIndex - index; + return endIndex; +} + +var serializeLong = function(buffer, key, value, index) { + // Write the type + buffer[index++] = value._bsontype == '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(buffer, 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 serializeFunction = function(buffer, key, value, index, checkKeys, depth) { + 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.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeCode = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { + 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(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // 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 end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined) + 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(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +} + +var serializeBinary = function(buffer, 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(buffer, 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; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} + +var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions) { + // 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(buffer, { + '$ref': value.namespace + , '$id' : value.oid + , '$db' : value.db + }, false, index, depth + 1, serializeFunctions); + } else { + endIndex = serializeInto(buffer, { + '$ref': value.namespace + , '$id' : value.oid + }, false, index, depth + 1, serializeFunctions); + } + + // 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 serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined) { + 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 value = object[i]; + + // Is there an override value + if(value && value.toBSON) { + if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + var type = typeof value; + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(type == 'undefined' || value == null) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else if(object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while(!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if(done) continue; + + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // 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 (checkKeys) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + // console.log("---------------------------------------------------") + // console.dir("key = " + key) + // console.dir("value = " + value) + + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(value === undefined && ignoreUndefined == true) { + } else if(value === null || value === undefined) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + 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"); + } + + // Iterate over all the keys + for(var key in object) { + var value = object[key]; + // Is there an override value + if(value && value.toBSON) { + if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // 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 (checkKeys) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(value === undefined && ignoreUndefined == true) { + } else if(value === null || value === undefined) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // 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; +} + +var BSON = {}; + +/** + * 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 = {}; + +/** + * 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; + +// 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. + +module.exports = serializeInto; diff --git a/5-3/node_modules/mongoose/node_modules/bson/lib/bson/regexp.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/regexp.js new file mode 100644 index 0000000..6b148b2 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/regexp.js @@ -0,0 +1,30 @@ +/** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ +function BSONRegExp(pattern, options) { + if(!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern; + this.options = options; + + // Validate options + for(var i = 0; i < options.length; i++) { + if(!(this.options[i] == 'i' + || this.options[i] == 'm' + || this.options[i] == 'x' + || this.options[i] == 'l' + || this.options[i] == 's' + || this.options[i] == 'u' + )) { + throw new Error('the regular expression options [' + this.options[i] + "] is not supported"); + } + } +} + +module.exports = BSONRegExp; +module.exports.BSONRegExp = BSONRegExp; \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js new file mode 100644 index 0000000..7681a4d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js @@ -0,0 +1,47 @@ +/** + * 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/5-3/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js new file mode 100644 index 0000000..7718caf --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js @@ -0,0 +1,856 @@ +// 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/5-3/node_modules/mongoose/node_modules/bson/package.json b/5-3/node_modules/mongoose/node_modules/bson/package.json new file mode 100644 index 0000000..bfe24b9 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/package.json @@ -0,0 +1,71 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "version": "0.4.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" + }, + "devDependencies": { + "nodeunit": "0.9.0", + "gleak": "0.2.3", + "one": "2.X.X", + "benchmark": "1.0.0", + "colors": "1.1.0" + }, + "config": { + "native": false + }, + "main": "./lib/bson/index", + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.6.19" + }, + "scripts": { + "test": "nodeunit ./test/node" + }, + "browser": "lib/bson/bson.js", + "license": "Apache-2.0", + "gitHead": "d88c87a7924f8d6a8b37366d7b3b39531cad521c", + "homepage": "https://github.com/mongodb/js-bson", + "_id": "bson@0.4.21", + "_shasum": "b8eae38c5aa94f7b8e64e8cfed0f42e58308ed95", + "_from": "bson@0.4.21", + "_npmVersion": "2.14.12", + "_nodeVersion": "4.2.4", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "octave", + "email": "chinsay@gmail.com" + }, + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "b8eae38c5aa94f7b8e64e8cfed0f42e58308ed95", + "tarball": "http://registry.npmjs.org/bson/-/bson-0.4.21.tgz" + }, + "_resolved": "https://registry.npmjs.org/bson/-/bson-0.4.21.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/bson/tools/gleak.js b/5-3/node_modules/mongoose/node_modules/bson/tools/gleak.js new file mode 100644 index 0000000..c707cfc --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/bson/tools/gleak.js @@ -0,0 +1,21 @@ + +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/5-3/node_modules/mongoose/node_modules/hooks-fixed/.npmignore b/5-3/node_modules/mongoose/node_modules/hooks-fixed/.npmignore new file mode 100644 index 0000000..96e29a8 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/hooks-fixed/.npmignore @@ -0,0 +1,2 @@ +**.swp +node_modules diff --git a/5-3/node_modules/mongoose/node_modules/hooks-fixed/Makefile b/5-3/node_modules/mongoose/node_modules/hooks-fixed/Makefile new file mode 100644 index 0000000..1db5d65 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/hooks-fixed/Makefile @@ -0,0 +1,9 @@ +test: + @NODE_ENV=test ./node_modules/expresso/bin/expresso \ + $(TESTFLAGS) \ + ./test.js + +test-cov: + @TESTFLAGS=--cov $(MAKE) test + +.PHONY: test test-cov diff --git a/5-3/node_modules/mongoose/node_modules/hooks-fixed/README.md b/5-3/node_modules/mongoose/node_modules/hooks-fixed/README.md new file mode 100644 index 0000000..98fe85b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/hooks-fixed/README.md @@ -0,0 +1,369 @@ +hooks +============ + +Add pre and post middleware hooks to your JavaScript methods. + +## Installation + npm install hooks + +## Motivation +Suppose you have a JavaScript object with a `save` method. + +It would be nice to be able to declare code that runs before `save` and after `save`. +For example, you might want to run validation code before every `save`, +and you might want to dispatch a job to a background job queue after `save`. + +One might have an urge to hard code this all into `save`, but that turns out to +couple all these pieces of functionality (validation, save, and job creation) more +tightly than is necessary. For example, what if someone does not want to do background +job creation after the logical save? + +It is nicer to tack on functionality using what we call `pre` and `post` hooks. These +are functions that you define and that you direct to execute before or after particular +methods. + +## Example +We can use `hooks` to add validation and background jobs in the following way: + +```javascript +var hooks = require('hooks') + , Document = require('./path/to/some/document/constructor'); + +// Add hooks' methods: `hook`, `pre`, and `post` +for (var k in hooks) { + Document[k] = hooks[k]; +} + +// Define a new method that is able to invoke pre and post middleware +Document.hook('save', Document.prototype.save); + +// Define a middleware function to be invoked before 'save' +Document.pre('save', function validate (next) { + // The `this` context inside of `pre` and `post` functions + // is the Document instance + if (this.isValid()) next(); // next() passes control to the next middleware + // or to the target method itself + else next(new Error("Invalid")); // next(error) invokes an error callback +}); + +// Define a middleware function to be invoked after 'save' +Document.post('save', function createJob (next) { + this.sendToBackgroundQueue(); + next(); +}); +``` + +If you already have defined `Document.prototype` methods for which you want pres and posts, +then you do not need to explicitly invoke `Document.hook(...)`. Invoking `Document.pre(methodName, fn)` +or `Document.post(methodName, fn)` will automatically and lazily change `Document.prototype[methodName]` +so that it plays well with `hooks`. An equivalent way to implement the previous example is: + +```javascript +var hooks = require('hooks') + , Document = require('./path/to/some/document/constructor'); + +// Add hooks' methods: `hook`, `pre`, and `post` +for (var k in hooks) { + Document[k] = hooks[k]; +} + +Document.prototype.save = function () { + // ... +}; + +// Define a middleware function to be invoked before 'save' +Document.pre('save', function validate (next) { + // The `this` context inside of `pre` and `post` functions + // is the Document instance + if (this.isValid()) next(); // next() passes control to the next middleware + // or to the target method itself + else next(new Error("Invalid")); // next(error) invokes an error callback +}); + +// Define a middleware function to be invoked after 'save' +Document.post('save', function createJob (next) { + this.sendToBackgroundQueue(); + next(); +}); +``` + +## Pres and Posts as Middleware +We structure pres and posts as middleware to give you maximum flexibility: + +1. You can define **multiple** pres (or posts) for a single method. +2. These pres (or posts) are then executed as a chain of methods. +3. Any functions in this middleware chain can choose to halt the chain's execution by `next`ing an Error from that middleware function. If this occurs, then none of the other middleware in the chain will execute, and the main method (e.g., `save`) will not execute. This is nice, for example, when we don't want a document to save if it is invalid. + +## Defining multiple pres (or posts) +`pre` and `post` are chainable, so you can define multiple via: +```javascript +Document.pre('save', function (next) { + console.log("hello"); + next(); +}).pre('save', function (next) { + console.log("world"); + next(); +}); + +Document.post('save', function (next) { + console.log("hello"); + next(); +}).post('save', function (next) { + console.log("world"); + next(); +}); +``` + +As soon as one pre finishes executing, the next one will be invoked, and so on. + +## Error Handling +You can define a default error handler by passing a 2nd function as the 3rd argument to `hook`: +```javascript +Document.hook('set', function (path, val) { + this[path] = val; +}, function (err) { + // Handler the error here + console.error(err); +}); +``` + +Then, we can pass errors to this handler from a pre or post middleware function: +```javascript +Document.pre('set', function (next, path, val) { + next(new Error()); +}); +``` + +If you do not set up a default handler, then `hooks` makes the default handler that just throws the `Error`. + +The default error handler can be over-rided on a per method invocation basis. + +If the main method that you are surrounding with pre and post middleware expects its last argument to be a function +with callback signature `function (error, ...)`, then that callback becomes the error handler, over-riding the default +error handler you may have set up. + +```javascript +Document.hook('save', function (callback) { + // Save logic goes here + ... +}); + +var doc = new Document(); +doc.save( function (err, saved) { + // We can pass err via `next` in any of our pre or post middleware functions + if (err) console.error(err); + + // Rest of callback logic follows ... +}); +``` + +## Mutating Arguments via Middleware +`pre` and `post` middleware can also accept the intended arguments for the method +they augment. This is useful if you want to mutate the arguments before passing +them along to the next middleware and eventually pass a mutated arguments list to +the main method itself. + +As a simple example, let's define a method `set` that just sets a key, value pair. +If we want to namespace the key, we can do so by adding a `pre` middleware hook +that runs before `set`, alters the arguments by namespacing the `key` argument, and passes them onto `set`: + +```javascript +Document.hook('set', function (key, val) { + this[key] = val; +}); +Document.pre('set', function (next, key, val) { + next('namespace-' + key, val); +}); +var doc = new Document(); +doc.set('hello', 'world'); +console.log(doc.hello); // undefined +console.log(doc['namespace-hello']); // 'world' +``` + +As you can see above, we pass arguments via `next`. + +If you are not mutating the arguments, then you can pass zero arguments +to `next`, and the next middleware function will still have access +to the arguments. + +```javascript +Document.hook('set', function (key, val) { + this[key] = val; +}); +Document.pre('set', function (next, key, val) { + // I have access to key and val here + next(); // We don't need to pass anything to next +}); +Document.pre('set', function (next, key, val) { + // And I still have access to the original key and val here + next(); +}); +``` + +Finally, you can add arguments that downstream middleware can also see: + +```javascript +// Note that in the definition of `set`, there is no 3rd argument, options +Document.hook('set', function (key, val) { + // But... + var options = arguments[2]; // ...I have access to an options argument + // because of pre function pre2 (defined below) + console.log(options); // '{debug: true}' + this[key] = val; +}); +Document.pre('set', function pre1 (next, key, val) { + // I only have access to key and val arguments + console.log(arguments.length); // 3 + next(key, val, {debug: true}); +}); +Document.pre('set', function pre2 (next, key, val, options) { + console.log(arguments.length); // 4 + console.log(options); // '{ debug: true}' + next(); +}); +Document.pre('set', function pre3 (next, key, val, options) { + // I still have access to key, val, AND the options argument introduced via the preceding middleware + console.log(arguments.length); // 4 + console.log(options); // '{ debug: true}' + next(); +}); + +var doc = new Document() +doc.set('hey', 'there'); +``` + +## Post middleware + +Post middleware intercepts the callback originally sent to the asynchronous function you have hooked to. + +This means that the following chain of execution will occur in a typical `save` operation: + +(1) doc.save -> (2) pre --(next)--> (3) save calls back -> (4) post --(next)--> (5) targetFn + +Illustrated below: + +``` +Document.pre('save', function (next) { + this.key = "value"; + next(); +}); +// Post handler occurs before `set` calls back. This is useful if we need to grab something +// async before `set` finishes. +Document.post('set', function (next) { + var me = this; + getSomethingAsync(function(value){ // let's assume it returns "Hello Async" + me.key2 = value; + next(); + }); +}); + +var doc = new Document(); +doc.save(function(err){ + console.log(this.key); // "value" - this value was saved + console.log(this.key2); // "Hello Async" - this value was *not* saved +} + +``` + +Post middleware must call `next()` or execution will stop. + +## Parallel `pre` middleware + +All middleware up to this point has been "serial" middleware -- i.e., middleware whose logic +is executed as a serial chain. + +Some scenarios call for parallel middleware -- i.e., middleware that can wait for several +asynchronous services at once to respond. + +For instance, you may only want to save a Document only after you have checked +that the Document is valid according to two different remote services. + +We accomplish asynchronous middleware by adding a second kind of flow control callback +(the only flow control callback so far has been `next`), called `done`. + +- `next` passes control to the next middleware in the chain +- `done` keeps track of how many parallel middleware have invoked `done` and passes + control to the target method when ALL parallel middleware have invoked `done`. If + you pass an `Error` to `done`, then the error is handled, and the main method that is + wrapped by pres and posts will not get invoked. + +We declare pre middleware that is parallel by passing a 3rd boolean argument to our `pre` +definition method. + +We illustrate via the parallel validation example mentioned above: + +```javascript +Document.hook('save', function targetFn (callback) { + // Save logic goes here + // ... + // This only gets run once the two `done`s are both invoked via preOne and preTwo. +}); + + // true marks this as parallel middleware +Document.pre('save', true, function preOne (next, doneOne, callback) { + remoteServiceOne.validate(this.serialize(), function (err, isValid) { + // The code in here will probably be run after the `next` below this block + // and could possibly be run after the console.log("Hola") in `preTwo + if (err) return doneOne(err); + if (isValid) doneOne(); + }); + next(); // Pass control to the next middleware +}); + +// We will suppose that we need 2 different remote services to validate our document +Document.pre('save', true, function preTwo (next, doneTwo, callback) { + remoteServiceTwo.validate(this.serialize(), function (err, isValid) { + if (err) return doneTwo(err); + if (isValid) doneTwo(); + }); + next(); +}); + +// While preOne and preTwo are parallel, preThree is a serial pre middleware +Document.pre('save', function preThree (next, callback) { + next(); +}); + +var doc = new Document(); +doc.save( function (err, doc) { + // Do stuff with the saved doc here... +}); +``` + +In the above example, flow control may happen in the following way: + +(1) doc.save -> (2) preOne --(next)--> (3) preTwo --(next)--> (4) preThree --(next)--> (wait for dones to invoke) -> (5) doneTwo -> (6) doneOne -> (7) targetFn + +So what's happening is that: + +1. You call `doc.save(...)` +2. First, your preOne middleware gets executed. It makes a remote call to the validation service and `next()`s to the preTwo middleware. +3. Now, your preTwo middleware gets executed. It makes a remote call to another validation service and `next()`s to the preThree middleware. +4. Your preThree middleware gets executed. It immediately `next()`s. But nothing else gets executing until both `doneOne` and `doneTwo` are invoked inside the callbacks handling the response from the two valiation services. +5. We will suppose that validation remoteServiceTwo returns a response to us first. In this case, we call `doneTwo` inside the callback to remoteServiceTwo. +6. Some fractions of a second later, remoteServiceOne returns a response to us. In this case, we call `doneOne` inside the callback to remoteServiceOne. +7. `hooks` implementation keeps track of how many parallel middleware has been defined per target function. It detects that both asynchronous pre middlewares (`preOne` and `preTwo`) have finally called their `done` functions (`doneOne` and `doneTwo`), so the implementation finally invokes our `targetFn` (i.e., our core `save` business logic). + +## Removing Pres + +You can remove a particular pre associated with a hook: + + Document.pre('set', someFn); + Document.removePre('set', someFn); + +And you can also remove all pres associated with a hook: + Document.removePre('set'); // Removes all declared `pre`s on the hook 'set' + +## Tests +To run the tests: + make test + +### Contributors +- [Brian Noguchi](https://github.com/bnoguchi) + +### License +MIT License + +--- +### Author +Brian Noguchi diff --git a/5-3/node_modules/mongoose/node_modules/hooks-fixed/hooks.alt.js b/5-3/node_modules/mongoose/node_modules/hooks-fixed/hooks.alt.js new file mode 100644 index 0000000..6ced357 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/hooks-fixed/hooks.alt.js @@ -0,0 +1,134 @@ +/** + * Hooks are useful if we want to add a method that automatically has `pre` and `post` hooks. + * For example, it would be convenient to have `pre` and `post` hooks for `save`. + * _.extend(Model, mixins.hooks); + * Model.hook('save', function () { + * console.log('saving'); + * }); + * Model.pre('save', function (next, done) { + * console.log('about to save'); + * next(); + * }); + * Model.post('save', function (next, done) { + * console.log('saved'); + * next(); + * }); + * + * var m = new Model(); + * m.save(); + * // about to save + * // saving + * // saved + */ + +// TODO Add in pre and post skipping options +module.exports = { + /** + * Declares a new hook to which you can add pres and posts + * @param {String} name of the function + * @param {Function} the method + * @param {Function} the error handler callback + */ + hook: function (name, fn, err) { + if (arguments.length === 1 && typeof name === 'object') { + for (var k in name) { // `name` is a hash of hookName->hookFn + this.hook(k, name[k]); + } + return; + } + + if (!err) err = fn; + + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {} + , posts = proto._posts = proto._posts || {}; + pres[name] = pres[name] || []; + posts[name] = posts[name] || []; + + function noop () {} + + proto[name] = function () { + var self = this + , pres = this._pres[name] + , posts = this._posts[name] + , numAsyncPres = 0 + , hookArgs = [].slice.call(arguments) + , preChain = pres.map( function (pre, i) { + var wrapper = function () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (numAsyncPres) { + // arguments[1] === asyncComplete + if (arguments.length) + hookArgs = [].slice.call(arguments, 2); + pre.apply(self, + [ preChain[i+1] || allPresInvoked, + asyncComplete + ].concat(hookArgs) + ); + } else { + if (arguments.length) + hookArgs = [].slice.call(arguments); + pre.apply(self, + [ preChain[i+1] || allPresDone ].concat(hookArgs)); + } + }; // end wrapper = function () {... + if (wrapper.isAsync = pre.isAsync) + numAsyncPres++; + return wrapper; + }); // end posts.map(...) + function allPresInvoked () { + if (arguments[0] instanceof Error) + err(arguments[0]); + } + + function allPresDone () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (arguments.length) + hookArgs = [].slice.call(arguments); + fn.apply(self, hookArgs); + var postChain = posts.map( function (post, i) { + var wrapper = function () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (arguments.length) + hookArgs = [].slice.call(arguments); + post.apply(self, + [ postChain[i+1] || noop].concat(hookArgs)); + }; // end wrapper = function () {... + return wrapper; + }); // end posts.map(...) + if (postChain.length) postChain[0](); + } + + if (numAsyncPres) { + complete = numAsyncPres; + function asyncComplete () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + --complete || allPresDone.call(this); + } + } + (preChain[0] || allPresDone)(); + }; + + return this; + }, + + pre: function (name, fn, isAsync) { + var proto = this.prototype + , pres = proto._pres = proto._pres || {}; + if (fn.isAsync = isAsync) { + this.prototype[name].numAsyncPres++; + } + (pres[name] = pres[name] || []).push(fn); + return this; + }, + post: function (name, fn, isAsync) { + var proto = this.prototype + , posts = proto._posts = proto._posts || {}; + (posts[name] = posts[name] || []).push(fn); + return this; + } +}; diff --git a/5-3/node_modules/mongoose/node_modules/hooks-fixed/hooks.js b/5-3/node_modules/mongoose/node_modules/hooks-fixed/hooks.js new file mode 100644 index 0000000..756c833 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/hooks-fixed/hooks.js @@ -0,0 +1,191 @@ +// TODO Add in pre and post skipping options +module.exports = { + /** + * Declares a new hook to which you can add pres and posts + * @param {String} name of the function + * @param {Function} the method + * @param {Function} the error handler callback + */ + hook: function (name, fn, errorCb) { + if (arguments.length === 1 && typeof name === 'object') { + for (var k in name) { // `name` is a hash of hookName->hookFn + this.hook(k, name[k]); + } + return; + } + + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {} + , posts = proto._posts = proto._posts || {}; + pres[name] = pres[name] || []; + posts[name] = posts[name] || []; + + proto[name] = function () { + var self = this + , hookArgs // arguments eventually passed to the hook - are mutable + , lastArg = arguments[arguments.length-1] + , pres = this._pres[name] + , posts = this._posts[name] + , _total = pres.length + , _current = -1 + , _asyncsLeft = proto[name].numAsyncPres + , _asyncsDone = function(err) { + if (err) { + return handleError(err); + } + --_asyncsLeft || _done.apply(self, hookArgs); + } + , handleError = function(err) { + if ('function' == typeof lastArg) + return lastArg(err); + if (errorCb) return errorCb.call(self, err); + throw err; + } + , _next = function () { + if (arguments[0] instanceof Error) { + return handleError(arguments[0]); + } + var _args = Array.prototype.slice.call(arguments) + , currPre + , preArgs; + if (_args.length && !(arguments[0] == null && typeof lastArg === 'function')) + hookArgs = _args; + if (++_current < _total) { + currPre = pres[_current] + if (currPre.isAsync && currPre.length < 2) + throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)"); + if (currPre.length < 1) + throw new Error("Your pre must have a next argument -- e.g., function (next, ...)"); + preArgs = (currPre.isAsync + ? [once(_next), once(_asyncsDone)] + : [once(_next)]).concat(hookArgs); + return currPre.apply(self, preArgs); + } else if (!_asyncsLeft) { + return _done.apply(self, hookArgs); + } + } + , _done = function () { + var args_ = Array.prototype.slice.call(arguments) + , ret, total_, current_, next_, done_, postArgs; + + if (_current === _total) { + + next_ = function () { + if (arguments[0] instanceof Error) { + return handleError(arguments[0]); + } + var args_ = Array.prototype.slice.call(arguments, 1) + , currPost + , postArgs; + if (args_.length) hookArgs = args_; + if (++current_ < total_) { + currPost = posts[current_] + if (currPost.length < 1) + throw new Error("Your post must have a next argument -- e.g., function (next, ...)"); + postArgs = [once(next_)].concat(hookArgs); + return currPost.apply(self, postArgs); + } else if (typeof lastArg === 'function'){ + // All post handlers are done, call original callback function + return lastArg.apply(self, arguments); + } + }; + + // We are assuming that if the last argument provided to the wrapped function is a function, it was expecting + // a callback. We trap that callback and wait to call it until all post handlers have finished. + if(typeof lastArg === 'function'){ + args_[args_.length - 1] = once(next_); + } + + total_ = posts.length; + current_ = -1; + ret = fn.apply(self, args_); // Execute wrapped function, post handlers come afterward + + if (total_ && typeof lastArg !== 'function') return next_(); // no callback provided, execute next_() manually + return ret; + } + }; + + return _next.apply(this, arguments); + }; + + proto[name].numAsyncPres = 0; + + return this; + }, + + pre: function (name, isAsync, fn, errorCb) { + if ('boolean' !== typeof arguments[1]) { + errorCb = fn; + fn = isAsync; + isAsync = false; + } + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {}; + + this._lazySetupHooks(proto, name, errorCb); + + if (fn.isAsync = isAsync) { + proto[name].numAsyncPres++; + } + + (pres[name] = pres[name] || []).push(fn); + return this; + }, + post: function (name, isAsync, fn) { + if (arguments.length === 2) { + fn = isAsync; + isAsync = false; + } + var proto = this.prototype || this + , posts = proto._posts = proto._posts || {}; + + this._lazySetupHooks(proto, name); + (posts[name] = posts[name] || []).push(fn); + return this; + }, + removePre: function (name, fnToRemove) { + var proto = this.prototype || this + , pres = proto._pres || (proto._pres || {}); + if (!pres[name]) return this; + if (arguments.length === 1) { + // Remove all pre callbacks for hook `name` + pres[name].length = 0; + } else { + pres[name] = pres[name].filter( function (currFn) { + return currFn !== fnToRemove; + }); + } + return this; + }, + removePost: function (name, fnToRemove) { + var proto = this.prototype || this + , posts = proto._posts || (proto._posts || {}); + if (!posts[name]) return this; + if (arguments.length === 1) { + // Remove all post callbacks for hook `name` + posts[name].length = 0; + } else { + posts[name] = posts[name].filter( function (currFn) { + return currFn !== fnToRemove; + }); + } + return this; + }, + + _lazySetupHooks: function (proto, methodName, errorCb) { + if ('undefined' === typeof proto[methodName].numAsyncPres) { + this.hook(methodName, proto[methodName], errorCb); + } + } +}; + +function once (fn, scope) { + return function fnWrapper () { + if (fnWrapper.hookCalled) return; + fnWrapper.hookCalled = true; + var ret = fn.apply(scope, arguments); + if (ret && ret.then) { + ret.then(function() {}, function() {}); + } + }; +} diff --git a/5-3/node_modules/mongoose/node_modules/hooks-fixed/package.json b/5-3/node_modules/mongoose/node_modules/hooks-fixed/package.json new file mode 100644 index 0000000..952e6ec --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/hooks-fixed/package.json @@ -0,0 +1,67 @@ +{ + "name": "hooks-fixed", + "description": "Adds pre and post hook functionality to your JavaScript methods.", + "version": "1.1.0", + "keywords": [ + "node", + "hooks", + "middleware", + "pre", + "post" + ], + "homepage": "https://github.com/vkarpov15/hooks-fixed/", + "repository": { + "type": "git", + "url": "git://github.com/vkarpov15/hooks-fixed.git" + }, + "author": { + "name": "Brian Noguchi", + "email": "brian.noguchi@gmail.com", + "url": "https://github.com/bnoguchi/" + }, + "main": "./hooks.js", + "directories": { + "lib": "." + }, + "scripts": { + "test": "make test" + }, + "dependencies": {}, + "devDependencies": { + "expresso": ">=0.7.6", + "should": ">=0.2.1", + "underscore": ">=1.1.4" + }, + "engines": { + "node": ">=0.4.0" + }, + "licenses": [ + "MIT" + ], + "optionalDependencies": {}, + "gitHead": "17ef258ae58d7aa6de7cec5b57f76233a4ba1c96", + "bugs": { + "url": "https://github.com/vkarpov15/hooks-fixed/issues" + }, + "_id": "hooks-fixed@1.1.0", + "_shasum": "0e8c15336708e6611185fe390b44687dd5230dbb", + "_from": "hooks-fixed@1.1.0", + "_npmVersion": "2.9.1", + "_nodeVersion": "0.12.3", + "_npmUser": { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + "dist": { + "shasum": "0e8c15336708e6611185fe390b44687dd5230dbb", + "tarball": "http://registry.npmjs.org/hooks-fixed/-/hooks-fixed-1.1.0.tgz" + }, + "maintainers": [ + { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + } + ], + "_resolved": "https://registry.npmjs.org/hooks-fixed/-/hooks-fixed-1.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/hooks-fixed/test.js b/5-3/node_modules/mongoose/node_modules/hooks-fixed/test.js new file mode 100644 index 0000000..81ad79e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/hooks-fixed/test.js @@ -0,0 +1,786 @@ +var hooks = require('./hooks') + , should = require('should') + , assert = require('assert') + , _ = require('underscore'); + +// TODO Add in test for making sure all pres get called if pre is defined directly on an instance. +// TODO Test for calling `done` twice or `next` twice in the same function counts only once +module.exports = { + 'should be able to assign multiple hooks at once': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook({ + hook1: function (a) {}, + hook2: function (b) {} + }); + var a = new A(); + assert.equal(typeof a.hook1, 'function'); + assert.equal(typeof a.hook2, 'function'); + }, + 'should run without pres and posts when not present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + }, + 'should run with pres when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValue.should.equal(2); + }, + 'should run with posts when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.value = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(2); + }, + 'should run pres and posts when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + A.post('save', function (next) { + this.value = 3; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(3); + a.preValue.should.equal(2); + }, + 'should run posts after pres': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.override = 100; + next(); + }); + A.post('save', function (next) { + this.override = 200; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.override.should.equal(200); + }, + 'should not run a hook if a pre fails': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function () { + this.value = 1; + }, function (err) { + counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + counter.should.equal(1); + assert.equal(typeof a.value, 'undefined'); + }, + 'should be able to run multiple pres': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.v1 = 1; + next(); + }).pre('save', function (next) { + this.v2 = 2; + next(); + }); + var a = new A(); + a.save(); + a.v1.should.equal(1); + a.v2.should.equal(2); + }, + 'should run multiple pres until a pre fails and not call the hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }, function (err) {}); + A.pre('save', function (next) { + this.v1 = 1; + next(); + }).pre('save', function (next) { + next(new Error()); + }).pre('save', function (next) { + this.v3 = 3; + next(); + }); + var a = new A(); + a.save(); + a.v1.should.equal(1); + assert.equal(typeof a.v3, 'undefined'); + assert.equal(typeof a.value, 'undefined'); + }, + 'should be able to run multiple posts': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.value = 2; + next(); + }).post('save', function (next) { + this.value = 3.14; + next(); + }).post('save', function (next) { + this.v3 = 3; + next(); + }); + var a = new A(); + a.save(); + assert.equal(a.value, 3.14); + assert.equal(a.v3, 3); + }, + 'should run only posts up until an error': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }, function (err) {}); + A.post('save', function (next) { + this.value = 2; + next(); + }).post('save', function (next) { + this.value = 3; + next(new Error()); + }).post('save', function (next) { + this.value = 4; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(3); + }, + "should fall back first to the hook method's last argument as the error handler if it is a function of arity 1 or 2": function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (callback) { + this.value = 1; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save( function (err) { + if (err instanceof Error) counter++; + }); + counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'should fall back second to the default error handler if specified': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (callback) { + this.value = 1; + }, function (err) { + if (err instanceof Error) counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'fallback default error handler should scope to the object': function () { + var A = function () { + this.counter = 0; + }; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (callback) { + this.value = 1; + }, function (err) { + if (err instanceof Error) this.counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + a.counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'should fall back last to throwing the error': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.hook('save', function (err) { + if (err instanceof Error) return counter++; + this.value = 1; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + var didCatch = false; + try { + a.save(); + } catch (e) { + didCatch = true; + e.should.be.an.instanceof(Error); + counter.should.equal(0); + assert.equal(typeof a.value, 'undefined'); + } + didCatch.should.be.true; + }, + "should proceed without mutating arguments if `next(null|undefined)` is called in a serial pre, and the last argument of the target method is a callback with node-like signature function (err, obj) {...} or function (err) {...}": function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.prototype.save = function (callback) { + this.value = 1; + callback(); + }; + A.pre('save', function (next) { + next(null); + }); + A.pre('save', function (next) { + next(undefined); + }); + var a = new A(); + a.save( function (err) { + if (err instanceof Error) counter++; + else counter--; + }); + counter.should.equal(-1); + a.value.should.eql(1); + }, + "should proceed with mutating arguments if `next(null|undefined)` is callback in a serial pre, and the last argument of the target method is not a function": function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.set = function (v) { + this.value = v; + }; + A.pre('set', function (next) { + next(undefined); + }); + A.pre('set', function (next) { + next(null); + }); + var a = new A(); + a.set(1); + should.strictEqual(null, a.value); + }, + 'should not run any posts if a pre fails': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 2; + }, function (err) {}); + A.pre('save', function (next) { + this.value = 1; + next(new Error()); + }).post('save', function (next) { + this.value = 3; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + }, + + "can pass the hook's arguments verbatim to pres": function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + }); + A.pre('set', function (next, path, val) { + path.should.equal('hello'); + val.should.equal('world'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + a.hello.should.equal('world'); + }, +// "can pass the hook's arguments as an array to pres": function () { +// // Great for dynamic arity - e.g., slice(...) +// var A = function () {}; +// _.extend(A, hooks); +// A.hook('set', function (path, val) { +// this[path] = val; +// }); +// A.pre('set', function (next, hello, world) { +// hello.should.equal('hello'); +// world.should.equal('world'); +// next(); +// }); +// var a = new A(); +// a.set('hello', 'world'); +// assert.equal(a.hello, 'world'); +// }, + "can pass the hook's arguments verbatim to posts": function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + }); + A.post('set', function (next, path, val) { + path.should.equal('hello'); + val.should.equal('world'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(a.hello, 'world'); + }, +// "can pass the hook's arguments as an array to posts": function () { +// var A = function () {}; +// _.extend(A, hooks); +// A.hook('set', function (path, val) { +// this[path] = val; +// }); +// A.post('set', function (next, halt, args) { +// assert.equal(args[0], 'hello'); +// assert.equal(args[1], 'world'); +// next(); +// }); +// var a = new A(); +// a.set('hello', 'world'); +// assert.equal(a.hello, 'world'); +// }, + "pres should be able to modify and pass on a modified version of the hook's arguments": function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + assert.equal(arguments[2], 'optional'); + }); + A.pre('set', function (next, path, val) { + next('foo', 'bar'); + }); + A.pre('set', function (next, path, val) { + assert.equal(path, 'foo'); + assert.equal(val, 'bar'); + next('rock', 'says', 'optional'); + }); + A.pre('set', function (next, path, val, opt) { + assert.equal(path, 'rock'); + assert.equal(val, 'says'); + assert.equal(opt, 'optional'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(typeof a.hello, 'undefined'); + a.rock.should.equal('says'); + }, + 'posts should see the modified version of arguments if the pres modified them': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + }); + A.pre('set', function (next, path, val) { + next('foo', 'bar'); + }); + A.post('set', function (next, path, val) { + path.should.equal('foo'); + val.should.equal('bar'); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(typeof a.hello, 'undefined'); + a.foo.should.equal('bar'); + }, + 'should pad missing arguments (relative to expected arguments of the hook) with null': function () { + // Otherwise, with hookFn = function (a, b, next, ), + // if we use hookFn(a), then because the pre functions are of the form + // preFn = function (a, b, next, ), then it actually gets executed with + // preFn(a, next, ), so when we call next() from within preFn, we are actually + // calling () + + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val, opts) { + this[path] = val; + }); + A.pre('set', function (next, path, val, opts) { + next('foo', 'bar'); + assert.equal(typeof opts, 'undefined'); + }); + var a = new A(); + a.set('hello', 'world'); + }, + + 'should not invoke the target method until all asynchronous middleware have invoked dones': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + counter++; + this[path] = val; + counter.should.equal(7); + }); + A.pre('set', function (next, path, val) { + counter++; + next(); + }); + A.pre('set', true, function (next, done, path, val) { + counter++; + setTimeout(function () { + counter++; + done(); + }, 1000); + next(); + }); + A.pre('set', function (next, path, val) { + counter++; + next(); + }); + A.pre('set', true, function (next, done, path, val) { + counter++; + setTimeout(function () { + counter++; + done(); + }, 500); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + }, + + 'invoking a method twice should run its async middleware twice': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val) { + this[path] = val; + if (path === 'hello') counter.should.equal(1); + if (path === 'foo') counter.should.equal(2); + }); + A.pre('set', true, function (next, done, path, val) { + setTimeout(function () { + counter++; + done(); + }, 1000); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + a.set('foo', 'bar'); + }, + + 'calling the same done multiple times should have the effect of only calling it once': function () { + var A = function () { + this.acked = false; + }; + _.extend(A, hooks); + A.hook('ack', function () { + console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); + this.acked = true; + }); + A.pre('ack', true, function (next, done) { + next(); + done(); + done(); + }); + A.pre('ack', true, function (next, done) { + next(); + // Notice that done() is not invoked here + }); + var a = new A(); + a.ack(); + setTimeout( function () { + a.acked.should.be.false; + }, 1000); + }, + + 'calling the same next multiple times should have the effect of only calling it once': function (beforeExit) { + var A = function () { + this.acked = false; + }; + _.extend(A, hooks); + A.hook('ack', function () { + console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); + this.acked = true; + }); + A.pre('ack', function (next) { + // force a throw to re-exec next() + try { + next(new Error('bam')); + } catch (err) { + next(); + } + }); + A.pre('ack', function (next) { + next(); + }); + var a = new A(); + a.ack(); + beforeExit( function () { + a.acked.should.be.false; + }); + }, + + 'asynchronous middleware should be able to pass an error via `done`, stopping the middleware chain': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.hook('set', function (path, val, fn) { + counter++; + this[path] = val; + fn(null); + }); + A.pre('set', true, function (next, done, path, val, fn) { + setTimeout(function () { + counter++; + done(new Error); + }, 1000); + next(); + }); + var a = new A(); + a.set('hello', 'world', function (err) { + err.should.be.an.instanceof(Error); + should.strictEqual(undefined, a['hello']); + counter.should.eql(1); + }); + }, + + 'should be able to remove a particular pre': function () { + var A = function () {} + , preTwo; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValueOne = 2; + next(); + }); + A.pre('save', preTwo = function (next) { + this.preValueTwo = 4; + next(); + }); + A.removePre('save', preTwo); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValueOne.should.equal(2); + should.strictEqual(undefined, a.preValueTwo); + }, + + 'should be able to remove all pres associated with a hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValueOne = 2; + next(); + }); + A.pre('save', function (next) { + this.preValueTwo = 4; + next(); + }); + A.removePre('save'); + var a = new A(); + a.save(); + a.value.should.equal(1); + should.strictEqual(undefined, a.preValueOne); + should.strictEqual(undefined, a.preValueTwo); + }, + + 'should be able to remove a particular post': function () { + var A = function () {} + , postTwo; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.postValueOne = 2; + next(); + }); + A.post('save', postTwo = function (next) { + this.postValueTwo = 4; + next(); + }); + A.removePost('save', postTwo); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.postValueOne.should.equal(2); + should.strictEqual(undefined, a.postValueTwo); + }, + + 'should be able to remove all posts associated with a hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.postValueOne = 2; + next(); + }); + A.post('save', function (next) { + this.postValueTwo = 4; + next(); + }); + A.removePost('save'); + var a = new A(); + a.save(); + a.value.should.equal(1); + should.strictEqual(undefined, a.postValueOne); + should.strictEqual(undefined, a.postValueTwo); + }, + + '#pre should lazily make a method hookable': function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValue.should.equal(2); + }, + + '#pre lazily making a method hookable should be able to provide a default errorHandler as the last argument': function () { + var A = function () {}; + var preValue = ""; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.pre('save', function (next) { + next(new Error); + }, function (err) { + preValue = 'ERROR'; + }); + var a = new A(); + a.save(); + should.strictEqual(undefined, a.value); + preValue.should.equal('ERROR'); + }, + + '#post should lazily make a method hookable': function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.post('save', function (next) { + this.value = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(2); + }, + + "a lazy hooks setup should handle errors via a method's last argument, if it's a callback": function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function (fn) {}; + A.pre('save', function (next) { + next(new Error("hi there")); + }); + var a = new A(); + a.save( function (err) { + err.should.be.an.instanceof(Error); + }); + }, + + 'should intercept method callbacks for post handlers': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function (val, callback) { + this.value = val; + callback(); + }); + A.post('save', function (next) { + assert.equal(a.value, 2); + this.value += 2; + setTimeout(next, 10); + }).post('save', function (next) { + assert.equal(a.value, 4); + this.value += 3; + setTimeout(next, 10); + }).post('save', function (next) { + assert.equal(a.value, 7); + this.value2 = 3; + setTimeout(next, 10); + }); + var a = new A(); + a.save(2, function(){ + assert.equal(a.value, 7); + assert.equal(a.value2, 3); + }); + }, + + 'should handle parallel followed by serial': function () { + var A = function () {}; + _.extend(A, hooks); + A.hook('save', function (val, callback) { + this.value = val; + callback(); + }); + A.pre('save', true, function(next, done) { + process.nextTick(function() { + done(); + }); + next(); + }).pre('save', function(done) { + process.nextTick(function() { + done(); + }); + }); + var a = new A(); + a.save(2, function(){ + assert.ok(true); + }); + } +}; diff --git a/5-3/node_modules/mongoose/node_modules/kareem/.npmignore b/5-3/node_modules/mongoose/node_modules/kareem/.npmignore new file mode 100644 index 0000000..59d842b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/.npmignore @@ -0,0 +1,28 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Commenting this out is preferred by some people, see +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- +node_modules + +# Users Environment Variables +.lock-wscript diff --git a/5-3/node_modules/mongoose/node_modules/kareem/.travis.yml b/5-3/node_modules/mongoose/node_modules/kareem/.travis.yml new file mode 100644 index 0000000..9aa8222 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "0.12" + - "0.10" + - "iojs" +script: "npm run-script test-travis" +after_script: "npm install coveralls@2.10.0 && cat ./coverage/lcov.info | coveralls" diff --git a/5-3/node_modules/mongoose/node_modules/kareem/LICENSE b/5-3/node_modules/mongoose/node_modules/kareem/LICENSE new file mode 100644 index 0000000..e06d208 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/LICENSE @@ -0,0 +1,202 @@ +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/5-3/node_modules/mongoose/node_modules/kareem/Makefile b/5-3/node_modules/mongoose/node_modules/kareem/Makefile new file mode 100644 index 0000000..f71ba90 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/Makefile @@ -0,0 +1,5 @@ +docs: + node ./docs.js + +coverage: + ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/* diff --git a/5-3/node_modules/mongoose/node_modules/kareem/README.md b/5-3/node_modules/mongoose/node_modules/kareem/README.md new file mode 100644 index 0000000..7d2dc84 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/README.md @@ -0,0 +1,379 @@ +# kareem + + [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem) + [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem) + +Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, meant to offer additional flexibility in allowing you to execute hooks whenever necessary, as opposed to simply wrapping a single function. + +Named for the NBA's all-time leading scorer Kareem Abdul-Jabbar, known for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook) + + + +# API + +## pre hooks + +Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define +pre and post hooks: pre hooks are called before a given function executes. +Unlike hooks, kareem stores hooks and other internal state in a separate +object, rather than relying on inheritance. Furthermore, kareem exposes +an `execPre()` function that allows you to execute your pre hooks when +appropriate, giving you more fine-grained control over your function hooks. + + +#### It runs without any hooks specified + +```javascript + + hooks.execPre('cook', null, function() { + done(); + }); + +``` + +#### It runs basic serial pre hooks + +pre hook functions take one parameter, a "done" function that you execute +when your pre hook is finished. + + +```javascript + + var count = 0; + + hooks.pre('cook', function(done) { + ++count; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count); + done(); + }); + +``` + +#### It can run multipe pre hooks + +```javascript + + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function(done) { + ++count1; + done(); + }); + + hooks.pre('cook', function(done) { + ++count2; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + +``` + +#### It can run fully synchronous pre hooks + +If your pre hook function takes no parameters, its assumed to be +fully synchronous. + + +```javascript + + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function() { + ++count1; + }); + + hooks.pre('cook', function() { + ++count2; + }); + + hooks.execPre('cook', null, function(error) { + assert.equal(null, error); + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + +``` + +#### It properly attaches context to pre hooks + +Pre save hook functions are bound to the second parameter to `execPre()` + + +```javascript + + hooks.pre('cook', function(done) { + this.bacon = 3; + done(); + }); + + hooks.pre('cook', function(done) { + this.eggs = 4; + done(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + // In the pre hooks, `this` will refer to `obj` + hooks.execPre('cook', obj, function(error) { + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + done(); + }); + +``` + +#### It can execute parallel (async) pre hooks + +Like the hooks module, you can declare "async" pre hooks - these take two +parameters, the functions `next()` and `done()`. `next()` passes control to +the next pre hook, but the underlying function won't be called until all +async pre hooks have called `done()`. + + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + done(); + }); + +``` + +## post hooks + +#### It runs without any hooks specified + +```javascript + + hooks.execPost('cook', null, [1], function(error, eggs) { + assert.ifError(error); + assert.equal(1, eggs); + done(); + }); + +``` + +#### It executes with parameters passed in + +```javascript + + hooks.post('cook', function(eggs, bacon, callback) { + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + +``` + +#### It can use synchronous post hooks + +```javascript + + var execed = {}; + + hooks.post('cook', function(eggs, bacon) { + execed.first = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + }); + + hooks.post('cook', function(eggs, bacon, callback) { + execed.second = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + +``` + +## wrap() + +#### It wraps pre and post calls into one call + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.ifError(error); + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj, + args); + +``` + +## createWrapper() + +#### It wraps wrap() into a callable function + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var cook = hooks.createWrapper( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj); + + cook(obj, function(error, result) { + assert.ifError(error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + +``` + +## clone() + +#### It clones a Kareem object + +```javascript + + var k1 = new Kareem(); + k1.pre('cook', function() {}); + k1.post('cook', function() {}); + + var k2 = k1.clone(); + assert.deepEqual(['cook'], Object.keys(k2._pres)); + assert.deepEqual(['cook'], Object.keys(k2._posts)); + +``` + diff --git a/5-3/node_modules/mongoose/node_modules/kareem/docs.js b/5-3/node_modules/mongoose/node_modules/kareem/docs.js new file mode 100644 index 0000000..4a8d4c8 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/docs.js @@ -0,0 +1,37 @@ +var acquit = require('acquit'); + +var content = require('fs').readFileSync('./test/examples.test.js').toString(); +var blocks = acquit.parse(content); + +var mdOutput = + '# kareem\n\n' + + ' [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem)\n' + + ' [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem)\n\n' + + 'Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, ' + + 'meant to offer additional flexibility in allowing you to execute hooks ' + + 'whenever necessary, as opposed to simply wrapping a single function.\n\n' + + 'Named for the NBA\'s all-time leading scorer Kareem Abdul-Jabbar, known ' + + 'for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook)\n\n' + + '\n\n' + + '# API\n\n'; + +for (var i = 0; i < blocks.length; ++i) { + var describe = blocks[i]; + mdOutput += '## ' + describe.contents + '\n\n'; + mdOutput += describe.comments[0] ? + acquit.trimEachLine(describe.comments[0]) + '\n\n' : + ''; + + for (var j = 0; j < describe.blocks.length; ++j) { + var it = describe.blocks[j]; + mdOutput += '#### It ' + it.contents + '\n\n'; + mdOutput += it.comments[0] ? + acquit.trimEachLine(it.comments[0]) + '\n\n' : + ''; + mdOutput += '```javascript\n'; + mdOutput += ' ' + it.code + '\n'; + mdOutput += '```\n\n'; + } +} + +require('fs').writeFileSync('README.md', mdOutput); diff --git a/5-3/node_modules/mongoose/node_modules/kareem/gulpfile.js b/5-3/node_modules/mongoose/node_modules/kareem/gulpfile.js new file mode 100644 index 0000000..635bfc7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/gulpfile.js @@ -0,0 +1,18 @@ +var gulp = require('gulp'); +var mocha = require('gulp-mocha'); +var config = require('./package.json'); +var jscs = require('gulp-jscs'); + +gulp.task('mocha', function() { + return gulp.src('./test/*'). + pipe(mocha({ reporter: 'dot' })); +}); + +gulp.task('jscs', function() { + return gulp.src('./index.js'). + pipe(jscs(config.jscsConfig)); +}); + +gulp.task('watch', function() { + gulp.watch('./index.js', ['jscs', 'mocha']); +}); diff --git a/5-3/node_modules/mongoose/node_modules/kareem/index.js b/5-3/node_modules/mongoose/node_modules/kareem/index.js new file mode 100644 index 0000000..b4b071b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/index.js @@ -0,0 +1,229 @@ +'use strict'; + +function Kareem() { + this._pres = {}; + this._posts = {}; +} + +Kareem.prototype.execPre = function(name, context, callback) { + var pres = this._pres[name] || []; + var numPres = pres.length; + var numAsyncPres = pres.numAsync || 0; + var currentPre = 0; + var asyncPresLeft = numAsyncPres; + var done = false; + + if (!numPres) { + return process.nextTick(function() { + callback(null); + }); + } + + var next = function() { + if (currentPre >= numPres) { + return; + } + var pre = pres[currentPre]; + + if (pre.isAsync) { + pre.fn.call( + context, + function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + ++currentPre; + next.apply(context, arguments); + }, + function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + if (--numAsyncPres === 0) { + return callback(null); + } + }); + } else if (pre.fn.length > 0) { + var args = [function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return callback(null); + } + } + + next.apply(context, arguments); + }]; + if (arguments.length >= 2) { + for (var i = 1; i < arguments.length; ++i) { + args.push(arguments[i]); + } + } + pre.fn.apply(context, args); + } else { + pre.fn.call(context); + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return process.nextTick(function() { + callback(null); + }); + } + } + next(); + } + }; + + next(); +}; + +Kareem.prototype.execPost = function(name, context, args, callback) { + var posts = this._posts[name] || []; + var numPosts = posts.length; + var currentPost = 0; + + if (!numPosts) { + return process.nextTick(function() { + callback.apply(null, [null].concat(args)); + }); + } + + var next = function() { + var post = posts[currentPost]; + + if (post.length > args.length) { + post.apply(context, args.concat(function(error) { + if (error) { + return callback(error); + } + + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + + next(); + })); + } else { + post.apply(context, args); + + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + + next(); + } + }; + + next(); +}; + +Kareem.prototype.wrap = function(name, fn, context, args, useLegacyPost) { + var lastArg = (args.length > 0 ? args[args.length - 1] : null); + var _this = this; + + this.execPre(name, context, function(error) { + if (error) { + if (typeof lastArg === 'function') { + return lastArg(error); + } + return; + } + + var end = (typeof lastArg === 'function' ? args.length - 1 : args.length); + + fn.apply(context, args.slice(0, end).concat(function() { + if (arguments[0]) { + // Assume error + return typeof lastArg === 'function' ? + lastArg(arguments[0]) : + undefined; + } + + if (useLegacyPost && typeof lastArg === 'function') { + lastArg.apply(context, arguments); + } + + var argsWithoutError = Array.prototype.slice.call(arguments, 1); + _this.execPost(name, context, argsWithoutError, function() { + if (arguments[0]) { + return typeof lastArg === 'function' ? + lastArg(arguments[0]) : + undefined; + } + + return typeof lastArg === 'function' && !useLegacyPost ? + lastArg.apply(context, arguments) : + undefined; + }); + })); + }); +}; + +Kareem.prototype.createWrapper = function(name, fn, context) { + var _this = this; + return function() { + var args = Array.prototype.slice.call(arguments); + _this.wrap(name, fn, context, args); + }; +}; + +Kareem.prototype.pre = function(name, isAsync, fn, error) { + if (typeof arguments[1] !== 'boolean') { + error = fn; + fn = isAsync; + isAsync = false; + } + + this._pres[name] = this._pres[name] || []; + var pres = this._pres[name]; + + if (isAsync) { + pres.numAsync = pres.numAsync || 0; + ++pres.numAsync; + } + + pres.push({ fn: fn, isAsync: isAsync }); + + return this; +}; + +Kareem.prototype.post = function(name, fn) { + (this._posts[name] = this._posts[name] || []).push(fn); + return this; +}; + +Kareem.prototype.clone = function() { + var n = new Kareem(); + for (var key in this._pres) { + n._pres[key] = this._pres[key].slice(); + } + for (var key in this._posts) { + n._posts[key] = this._posts[key].slice(); + } + + return n; +}; + +module.exports = Kareem; diff --git a/5-3/node_modules/mongoose/node_modules/kareem/package.json b/5-3/node_modules/mongoose/node_modules/kareem/package.json new file mode 100644 index 0000000..302be1b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/package.json @@ -0,0 +1,60 @@ +{ + "name": "kareem", + "version": "1.0.1", + "description": "Next-generation take on pre/post function hooks", + "main": "index.js", + "scripts": { + "test": "./node_modules/mocha/bin/mocha ./test/*", + "test-travis": "./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/*" + }, + "repository": { + "type": "git", + "url": "git://github.com/vkarpov15/kareem.git" + }, + "devDependencies": { + "acquit": "0.0.3", + "gulp": "3.8.10", + "gulp-mocha": "2.0.0", + "gulp-jscs": "1.4.0", + "istanbul": "0.3.5", + "jscs": "1.9.0", + "mocha": "2.0.0" + }, + "jscsConfig": { + "preset": "airbnb", + "requireMultipleVarDecl": null, + "disallowMultipleVarDecl": true + }, + "author": { + "name": "Valeri Karpov", + "email": "val@karpov.io" + }, + "license": "Apache 2.0", + "gitHead": "69710887f85dee09afac690df770dd2febde7268", + "bugs": { + "url": "https://github.com/vkarpov15/kareem/issues" + }, + "homepage": "https://github.com/vkarpov15/kareem", + "_id": "kareem@1.0.1", + "_shasum": "7805d215bb53214ec3af969a1d0b1f17e3e7b95c", + "_from": "kareem@1.0.1", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + }, + "maintainers": [ + { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + } + ], + "dist": { + "shasum": "7805d215bb53214ec3af969a1d0b1f17e3e7b95c", + "tarball": "http://registry.npmjs.org/kareem/-/kareem-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/kareem/-/kareem-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/kareem/test/examples.test.js b/5-3/node_modules/mongoose/node_modules/kareem/test/examples.test.js new file mode 100644 index 0000000..96d2fb8 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/test/examples.test.js @@ -0,0 +1,339 @@ +var assert = require('assert'); +var Kareem = require('../'); + +/* Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define + * pre and post hooks: pre hooks are called before a given function executes. + * Unlike hooks, kareem stores hooks and other internal state in a separate + * object, rather than relying on inheritance. Furthermore, kareem exposes + * an `execPre()` function that allows you to execute your pre hooks when + * appropriate, giving you more fine-grained control over your function hooks. + */ +describe('pre hooks', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('runs without any hooks specified', function(done) { + hooks.execPre('cook', null, function() { + done(); + }); + }); + + /* pre hook functions take one parameter, a "done" function that you execute + * when your pre hook is finished. + */ + it('runs basic serial pre hooks', function(done) { + var count = 0; + + hooks.pre('cook', function(done) { + ++count; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count); + done(); + }); + }); + + it('can run multipe pre hooks', function(done) { + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function(done) { + ++count1; + done(); + }); + + hooks.pre('cook', function(done) { + ++count2; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + }); + + /* If your pre hook function takes no parameters, its assumed to be + * fully synchronous. + */ + it('can run fully synchronous pre hooks', function(done) { + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function() { + ++count1; + }); + + hooks.pre('cook', function() { + ++count2; + }); + + hooks.execPre('cook', null, function(error) { + assert.equal(null, error); + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + }); + + /* Pre save hook functions are bound to the second parameter to `execPre()` + */ + it('properly attaches context to pre hooks', function(done) { + hooks.pre('cook', function(done) { + this.bacon = 3; + done(); + }); + + hooks.pre('cook', function(done) { + this.eggs = 4; + done(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + // In the pre hooks, `this` will refer to `obj` + hooks.execPre('cook', obj, function(error) { + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + done(); + }); + }); + + /* Like the hooks module, you can declare "async" pre hooks - these take two + * parameters, the functions `next()` and `done()`. `next()` passes control to + * the next pre hook, but the underlying function won't be called until all + * async pre hooks have called `done()`. + */ + it('can execute parallel (async) pre hooks', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + done(); + }); + }); +}); + +describe('post hooks', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('runs without any hooks specified', function(done) { + hooks.execPost('cook', null, [1], function(error, eggs) { + assert.ifError(error); + assert.equal(1, eggs); + done(); + }); + }); + + it('executes with parameters passed in', function(done) { + hooks.post('cook', function(eggs, bacon, callback) { + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + }); + + it('can use synchronous post hooks', function(done) { + var execed = {}; + + hooks.post('cook', function(eggs, bacon) { + execed.first = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + }); + + hooks.post('cook', function(eggs, bacon, callback) { + execed.second = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + }); +}); + +describe('wrap()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('wraps pre and post calls into one call', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.ifError(error); + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj, + args); + }); +}); + +describe('createWrapper()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('wraps wrap() into a callable function', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var cook = hooks.createWrapper( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj); + + cook(obj, function(error, result) { + assert.ifError(error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + }); +}); + +describe('clone()', function() { + it('clones a Kareem object', function() { + var k1 = new Kareem(); + k1.pre('cook', function() {}); + k1.post('cook', function() {}); + + var k2 = k1.clone(); + assert.deepEqual(['cook'], Object.keys(k2._pres)); + assert.deepEqual(['cook'], Object.keys(k2._posts)); + }); +}); diff --git a/5-3/node_modules/mongoose/node_modules/kareem/test/post.test.js b/5-3/node_modules/mongoose/node_modules/kareem/test/post.test.js new file mode 100644 index 0000000..3df0ec5 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/test/post.test.js @@ -0,0 +1,46 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('execPost', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles errors', function(done) { + hooks.post('cook', function(eggs, callback) { + callback('error!'); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.equal('error!', error); + assert.ok(!eggs); + done(); + }); + }); + + it('multiple posts', function(done) { + hooks.post('cook', function(eggs, callback) { + setTimeout( + function() { + callback(); + }, + 5); + }); + + hooks.post('cook', function(eggs, callback) { + setTimeout( + function() { + callback(); + }, + 5); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.ifError(error); + assert.equal(4, eggs); + done(); + }); + }); +}); \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/kareem/test/pre.test.js b/5-3/node_modules/mongoose/node_modules/kareem/test/pre.test.js new file mode 100644 index 0000000..4c1a212 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/test/pre.test.js @@ -0,0 +1,226 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('execPre', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles errors with multiple pres', function(done) { + var execed = {}; + + hooks.pre('cook', function(done) { + execed.first = true; + done(); + }); + + hooks.pre('cook', function(done) { + execed.second = true; + done('error!'); + }); + + hooks.pre('cook', function(done) { + execed.third = true; + done(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + done('other error!'); + }, + 10); + + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors in next()', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 15); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + next('error!'); + done('another error!'); + }, + 5); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors in next() when already done', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + next('error!'); + done('another error!'); + }, + 25); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('other error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('returns correct error when async pre errors', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', function(next) { + execed.second = true; + setTimeout( + function() { + next('error!'); + }, + 15); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('other error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('lets async pres run when fully sync pres are done', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done(); + }, + 5); + + next(); + }); + + hooks.pre('cook', function() { + execed.second = true; + }); + + hooks.execPre('cook', null, function(err) { + assert.ifError(err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('allows passing arguments to the next pre', function(done) { + var execed = {}; + + hooks.pre('cook', function(next) { + execed.first = true; + next(null, 'test'); + }); + + hooks.pre('cook', function(next, p) { + execed.second = true; + assert.equal(p, 'test'); + next(); + }); + + hooks.pre('cook', function(next, p) { + execed.third = true; + assert.ok(!p); + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.ifError(err); + assert.equal(3, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.ok(execed.third); + done(); + }); + }); +}); diff --git a/5-3/node_modules/mongoose/node_modules/kareem/test/wrap.test.js b/5-3/node_modules/mongoose/node_modules/kareem/test/wrap.test.js new file mode 100644 index 0000000..3303961 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/kareem/test/wrap.test.js @@ -0,0 +1,277 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('wrap()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles pre errors', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal(undefined, obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + // Should never get called + assert.ok(false); + callback(null, o); + }, + obj, + args); + }); + + it('handles pre errors when no callback defined', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + + hooks.wrap( + 'cook', + function(o, callback) { + // Should never get called + assert.ok(false); + callback(null, o); + }, + obj, + args); + + setTimeout( + function() { + done(); + }, + 25); + }); + + it('handles errors in wrapped function', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal(undefined, obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + callback('error!'); + }, + obj, + args); + }); + + it('handles errors in post', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(obj, callback) { + obj.tofu = 'no'; + callback('error!'); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal('no', obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + callback(null, o); + }, + obj, + args); + }); + + it('works with no args', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(null); + }, + obj, + args); + + setTimeout( + function() { + assert.equal('no', obj.tofu); + done(); + }, + 25); + }); + + it('handles pre errors with no args', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(null); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(undefined, obj.tofu); + done(); + }, + 25); + }); + + it('handles wrapped function errors with no args', function(done) { + hooks.pre('cook', function(done) { + obj.waffles = false; + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback('error!'); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + done(); + }, + 25); + }); + + it('handles post errors with no args', function(done) { + hooks.pre('cook', function(done) { + obj.waffles = false; + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback('error!'); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + done(); + }, + 25); + }); + + it('can use legacy post behavior', function(done) { + var called = 0; + hooks.post('cook', function(callback) { + ++called; + callback(); + }); + + var args = [function(error) { + assert.equal(called, 0); + + setTimeout(function() { + assert.equal(called, 1); + done(); + }, 0); + }]; + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + null, + args, + true); + }); +}); \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/.coveralls.yml b/5-3/node_modules/mongoose/node_modules/mongodb/.coveralls.yml new file mode 100644 index 0000000..ad1e93c --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/.coveralls.yml @@ -0,0 +1 @@ +repo_token: GZFmqKPy7XEX0uOl9TDZFUoOQ5AHADMkU diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/HISTORY.md b/5-3/node_modules/mongoose/node_modules/mongodb/HISTORY.md new file mode 100644 index 0000000..763464d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/HISTORY.md @@ -0,0 +1,1328 @@ +2.1.5 2016-02-05 +---------------- +* Updated mongodb-core to 1.3.1. + +2.1.5 2016-02-04 +---------------- +* Updated mongodb-core to 1.3.0. +* Added raw support for the command function on topologies. +* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +* NODE-638, Cannot authenticate database user with utf-8 password. +* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +* Switched to using Array.push instead of concat for use cases of a lot of documents. +* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +* Added peer optional dependencies support using require_optional module. +* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) +* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) + +2.1.4 2016-01-12 +---------------- +* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). +* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). +* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). + +2.1.3 2016-01-04 +---------------- +* Updated mongodb-core to 1.2.31. +* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +2.1.2 2015-12-23 +---------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.1.1 2015-12-13 +---------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.1.0 2015-12-06 +---------------- +* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. +* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. +* Full MongoDB 3.2 support. +* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Updated mongodb-core to 1.2.26. +* Return destination in GridStore pipe function. +* NODE-606 better error handling on destroyed topology for db.js methods. +* Added isDestroyed method to server, replset and mongos topologies. +* Upgraded test suite to run using mongodb-topology-manager. + +2.0.53 2015-12-23 +----------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.0.52 2015-12-14 +----------------- +* removed remove from Gridstore.close. + +2.0.51 2015-12-13 +----------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.0.50 2015-12-06 +----------------- +* Updated mongodb-core to 1.2.26. + +2.0.49 2015-11-20 +----------------- +* Updated mongodb-core to 1.2.24 with several fixes. + * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). + * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + * ismaster runs against admin.$cmd instead of system.$cmd. + * Fixes to handle getMore command errors for MongoDB 3.2 + * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +2.0.48 2015-11-07 +----------------- +* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. +* Updated mongodb-core to 1.2.21. +* Hardened the checking for replicaset equality checks. +* OpReplay flag correctly set on Wire protocol query. +* Mongos load balancing added, introduced localThresholdMS to control the feature. +* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +2.0.47 2015-10-28 +----------------- +* Updated mongodb-core to 1.2.20. +* Fixed bug in arbiter connection capping code. +* NODE-599 correctly handle arrays of server tags in order of priority. +* Fix for 2.6 wire protocol handler related to readPreference handling. +* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +2.0.46 2015-10-15 +----------------- +* Updated mongodb-core to 1.2.19. +* NODE-578 Order of sort fields is lost for numeric field names. +* Expose BSON Map (ES6 Map or polyfill). +* Minor fixes for APM support to pass extended APM test suite. + +2.0.45 2015-09-30 +----------------- +* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. + +2.0.44 2015-09-28 +----------------- +* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. +* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. +* Updated mongodb-core to 1.2.14. +* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. +* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) +* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. +* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. +* NODE-572 Remove examples that use the second parameter to `find()`. + +2.0.43 2015-09-14 +----------------- +* Propagate timeout event correctly to db instances. +* Application Monitoring API (APM) implemented. +* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. +* Updated mongodb-core to 1.2.12. +* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. +* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) +* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) +* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) + +2.0.42 2015-08-18 +----------------- +* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. + +2.0.41 2015-08-14 +----------------- +* Added missing Mongos.prototype.parserType function. +* Updated mongodb-core to 1.2.10. + +2.0.40 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. +* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +* NODE-518 connectTimeoutMS is doubled in 2.0.39. +* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). +* NODE-526 Unique index not throwing duplicate key error. +* NODE-528 Ignore undefined fields in Collection.find(). +* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. + +2.0.39 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.6 for NODE-505. + +2.0.38 2015-07-14 +----------------- +* NODE-505 Query fails to find records that have a 'result' property with an array value. + +2.0.37 2015-07-14 +----------------- +* NODE-504 Collection * Default options when using promiseLibrary. +* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. +* Updated mongodb-core to 1.2.5 to fix NODE-492. + +2.0.36 2015-07-07 +----------------- +* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). +* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. + +2.0.35 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. + +2.0.34 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. +* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. +* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +2.0.33 2015-05-20 +----------------- +* Bumped mongodb-core to 1.1.32. + +2.0.32 2015-05-19 +----------------- +* NODE-463 db.close immediately executes its callback. +* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). +* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. + +2.0.31 2015-05-08 +----------------- +* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +2.0.30 2015-05-07 +----------------- +* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. + +2.0.29 2015-05-07 +----------------- +* NODE-444 Possible memory leak, too many listeners added. +* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. +* Bumped mongodb-core to 1.1.26. + +2.0.28 2015-04-24 +----------------- +* Bumped mongodb-core to 1.1.25 +* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. +* NODE-430 Cursor.count() opts argument masked by var opts = {} +* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. +* NODE-438 replaceOne is not returning the result.ops property as described in the docs. +* NODE-433 _read, pipe and write all open gridstore automatically if not open. +* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. +* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. +* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). +* Minor fix in GridStore.exists for dealing with regular expressions searches. + +2.0.27 2015-04-07 +----------------- +* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. + +2.0.26 2015-04-07 +----------------- +* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. +* NODE-408 Expose GridStore.currentChunk.chunkNumber. + +2.0.25 2015-03-26 +----------------- +* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. + +2.0.24 2015-03-24 +----------------- +* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. +* Upgraded mongodb-core to 1.1.20. + +2.0.23 2015-03-21 +----------------- +* NODE-380 Correctly return MongoError from toError method. +* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. +* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. +* Upgraded mongodb-core to 1.1.19. + +2.0.22 2015-03-16 +----------------- +* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. +* Upgraded mongodb-core to 1.1.17. + +2.0.21 2015-03-06 +----------------- +* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. + +2.0.20 2015-03-04 +----------------- +* Updated mongodb-core 1.1.15 to relax pickserver method. + +2.0.19 2015-03-03 +----------------- +* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) +* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) +* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) + +2.0.18 2015-02-27 +----------------- +* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. + +2.0.17 2015-02-27 +----------------- +* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. +* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. + +2.0.16 2015-02-16 +----------------- +* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. +* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. +* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) + +2.0.15 2015-02-02 +----------------- +* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. +* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. +* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. +* Added ~1.0 mongodb-tools module for test running. +* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +2.0.14 2015-01-21 +----------------- +* Fixed some MongoClient.connect options pass through issues and added test coverage. +* Bumped mongodb-core to 1.1.9 including fixes for io.js + +2.0.13 2015-01-09 +----------------- +* Bumped mongodb-core to 1.1.8. +* Optimized query path for performance, moving Object.defineProperty outside of constructors. + +2.0.12 2014-12-22 +----------------- +* Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +2.0.11 2014-12-19 +----------------- +* listCollections filters out index namespaces on < 2.8 correctly +* Bumped mongo-client to 1.1.7 + +2.0.10 2014-12-18 +----------------- +* NODE-328 fixed db.open return when no callback available issue and added test. +* NODE-327 Refactored listCollections to return cursor to support 2.8. +* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. +* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. +* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) +* Bumped mongo-client to 1.1.6 + +2.0.9 2014-12-01 +---------------- +* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. +* All classes are now strict (Issue #1233) +* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. +* Fixed recursion issues in debug logging due to JSON.stringify() +* Documentation fixes (Issue #1232, https://github.com/wsmoak) +* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) + +2.0.8 2014-11-28 +---------------- +* NODE-322 Finished up prototype refactoring of Db class. +* NODE-322 Exposed Cursor in index.js for New Relic. + +2.0.7 2014-11-20 +---------------- +* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. +* NODE-318 collection.update error while setting a function with serializeFunctions option. +* Documentation fixes. + +2.0.6 2014-11-14 +---------------- +* Refactored code to be prototype based instead of privileged methods. +* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. +* Implemented missing aspects of the CRUD specification. +* Fixed documentation issues. +* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) +* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +2.0.5 2014-10-29 +---------------- +* Minor fixes to documentation and generation of documentation. +* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. + +2.0.4 2014-10-23 +---------------- +* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) +* Made each rewind on each call allowing for re-using the cursor. +* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. +* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. + +2.0.3 2014-10-14 +---------------- +* NODE-297 Aggregate Broken for case of pipeline with no options. + +2.0.2 2014-10-08 +---------------- +* Bumped mongodb-core to 1.0.2. +* Fixed bson module dependency issue by relying on the mongodb-core one. +* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) + +2.0.1 2014-10-07 +---------------- +* Dependency fix + +2.0.0 2014-10-07 +---------------- +* First release of 2.0 driver + +2.0.0-alpha2 2014-10-02 +----------------------- +* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) +* Cluster Management Spec compatible. + +2.0.0-alpha1 2014-09-08 +----------------------- +* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode +* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package +* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node +* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) + * Might break some application +* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove +* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) +* Removed Grid class +* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data + + seek will fail if attempt to use with w or w+ + + write will fail if attempted with w+ or r + + w+ only works for updating metadata on a file +* Cursor toArray and each resets and re-runs the cursor +* FindAndModify returns whole result document instead of just value +* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find +* Removed db.dereference method +* Removed db.cursorInfo method +* Removed db.stats method +* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections +* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. +* Added db.listCollections to replace several methods above + +1.4.10 2014-09-04 +----------------- +* Fixed BSON and Kerberos compilation issues +* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +* Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +* NODE-240 Operations on SSL connection hang on node 0.11.x +* NODE-235 writeResult is not being passed on when error occurs in insert +* NODE-229 Allow count to work with query hints +* NODE-233 collection.save() does not support fullResult +* NODE-244 Should parseError also emit a `disconnected` event? +* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +* NODE-248 Crash with X509 auth +* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +* Bumped BSON parser to 0.2.12 + + +1.4.8 2014-08-01 +---------------- +* NODE-205 correctly emit authenticate event +* NODE-210 ensure no undefined connection error when checking server state +* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +* NODE-220 don't throw error if ensureIndex errors out in Gridstore +* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +* Fixed test running filters +* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +* Fixed parsing issue for w:0 in url parser when in connection string +* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +* Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +* Removed leaking global variable (Issue #1174, https://github.com/dainis) +* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) +* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +* Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +* Correctly emit joined event when primary change +* Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +* All node exceptions will no longer be caught if on('error') is defined +* Added X509 auth support +* Fix for MongoClient connection timeout issue (NODE-97) +* Pass through error messages from parseError instead of just text (Issue #1125) +* Close db connection on error (Issue #1128, https://github.com/benighted) +* Fixed documentation generation +* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +* Insert/Update/Remove using new write commands when available +* Added support for new roles based API's in 2.6 for addUser/removeUser +* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +* Support for OP_LOG_REPLAY flag (NODE-94) +* Fixes for SSL HA ping and discovery. +* Uses createIndexes if available for ensureIndex/createIndex +* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +* Made CommandCursor behave as Readable stream. +* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +* Refactored commands to all go through command function ensuring consistent command execution. +* Fixed issues where readPreferences where not correctly passed to mongos. +* Catch error == null and make err detection more prominent (NODE-130) +* Allow reads from arbiter for single server connection (NODE-117) +* Handle error coming back with no documents (NODE-130) +* Correctly use close parameter in Gridstore.write() (NODE-125) +* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +* Ignore return commands that have no registered callback +* Made collection.count not use the db.command function +* Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +* Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +* Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +* BSON size checking now done pre serialization (Issue #1037) +* Added isConnected returns false when no connection Pool exists (Issue #1043) +* Unified command handling to ensure same handling (Issue #1041, #1042) +* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +* Fixed issue with Kerberos authentication on Windows for re-authentication. +* Fixed Mongos failover behavior to correctly throw out old servers. +* Ensure stored queries/write ops are executed correctly after connection timeout +* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +* Fixed bug with callback third parameter on some commands (Issue #1033) +* Fixed possible issue where killcursor command might leave hanging functions +* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +* Throw error if dbName or collection name contains null character (at command level and at collection level) +* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +* Add driver version to export (Issue #1021, https://github.com/aheckmann) +* Add text to readpreference obedient commands (Issue #1019) +* Drivers should check the query failure bit even on getmore response (Issue #1018) +* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +* Support SASL PLAIN authentication (Issue #1009) +* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +* Introduced write and read concerns for GridFS (Issue #996) +* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +* Fixed issue with pool size on replicaset connections (Issue #1000) +* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +* Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +* Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +* Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +* Applied auth before server instance is set as connected when single server connection +* Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +* Refactored test suite to speed up running of replicaset tests +* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +* Corrected a slaveOk setting issue (Issue #906, #905) +* Fixed HA issue where ping's would not go to correct server on HA server connection failure. +* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +* Fixed race condition in Cursor stream (NODE-31) +* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +* Added support for maxMessageSizeBytes if available (DRIVERS-1) +* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +* Fixed missing MongoErrors on some cursor methods (Issue #882) +* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +* Added limit/skip options to Collection.count (Issue #870) +* Added applySkipLimit option to Cursor.count (Issue #870) +* Enabled ping strategy as default for Replicaset if none specified (Issue #876) +* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +* Added fixes for handling type 2 binary due to PHP driver (Issue #864) +* Moved callBackStore to Base class to have single unified store (Issue #866) +* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +* Only open a new HA socket when previous one dead (Issue #859, #857) +* Minor fixes + +1.2.9 2013-01-15 +---------------- +* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +* Connection string with no db specified should default to admin db (Issue #848) +* Support port passed as string to Server class (Issue #844) +* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +* Included toError wrapper code moved to utils.js file (Issue #839, #840) +* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +* Rolled back batches as they hang in certain situations +* Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +* Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +* Fixed ssl regression, added more test coverage (Issue #800) +* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +* Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +* Fix for journal write concern not correctly being passed under some circumstances. +* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +* Fix for double callback on insert with w:0 specified (Issue #783) +* Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +* Force correct setting of read_secondary based on the read preference (Issue #741) +* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +* Mongos connection with auth not working (Issue #737) +* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + * open/close/db/connect methods implemented +* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +* Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +* Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +* fix Admin.serverStatus (Issue #723, https://github.com/Contra) +* logging on connection open/close(Issue #721, https://github.com/asiletto) +* more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +* Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +* Cleanup of non-closing connections (Issue #706) +* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +* Set keepalive on as default, override if not needed +* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +* Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +* Proper stopping of strategy on replicaset stop +* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +* Fix for eval on replicaset Issue #684 +* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +* Added exhaust option for find for feature completion (not recommended for normal use) +* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +* Fix gridfs readstream (Issue #607, https://github.com/tedeh). +* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +* Cleanup map reduce (Issue #614, https://github.com/aheckmann). +* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +* Date identification handled correctly in bson js parser when running in vm context. +* Documentation updates +* GridStore filename not set on read (Issue #621) +* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +* Added support for awaitdata for tailable cursors (Issue #624) +* Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +* Fixed auth to work better when multiple connections are involved. +* Default connection pool size increased to 5 connections. +* Fixes for the ReadStream class to work properly with 0.8 of Node.js +* Added explain function support to aggregation helper +* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +* Fixed Always emit db events (Issue #657) +* Close event not correctly resets DB openCalled variable to allow reconnect +* Added open event on connection established for replicaset, mongos and server +* Much faster BSON C++ parser thanks to Lucasfilm Singapore. +* Refactoring of replicaset connection logic to simplify the code. +* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +* Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +* Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +* Passing back getLastError object as 3rd parameter on findAndModify command. +* Fixed a bunch of performance regressions in objectId and cursor. +* Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +* Fixes to handling of failover on server error +* Only emits error messages if there are error listeners to avoid uncaught events +* Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +* _id=0 is being turned into an ObjectID (Issue #551) +* fix for error in GridStore write method (Issue #559) +* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +* Connection pools handles closing themselves down and clearing the state +* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +* Returning update status document at the end of the callback for updates, (Issue #569) +* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +* Stats not returned from map reduce with inline results (Issue #542) +* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +* Streaming large files from GridFS causes truncation (Issue #540) +* Make callback type checks agnostic to V8 context boundaries (Issue #545) +* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +* Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +* BSON parser is externalized in it's own repository, currently using git master +* Fixes for Replicaset connectivity issue (Issue #537) +* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +* Removed SimpleEmitter and replaced with standard EventEmitter +* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +* Fixed memory leak in C++ bson parser (Issue #526) +* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +* Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/LICENSE b/5-3/node_modules/mongoose/node_modules/mongodb/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/LICENSE @@ -0,0 +1,201 @@ +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. \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/Makefile b/5-3/node_modules/mongoose/node_modules/mongodb/Makefile new file mode 100644 index 0000000..36e1202 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/Makefile @@ -0,0 +1,11 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + hugo -s docs/reference -d ../../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/README.md b/5-3/node_modules/mongoose/node_modules/mongodb/README.md new file mode 100644 index 0000000..8ebc810 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/README.md @@ -0,0 +1,415 @@ +[![NPM](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![NPM](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) + +[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.png)](http://travis-ci.org/mongodb/node-mongodb-native) +[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) +[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +# Description + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. + +## MongoDB Node.JS Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| api-doc | http://mongodb.github.io/node-mongodb-native/2.1/api/ | +| 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) + +### 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 + +# Installation + +The recommended way to get started using the Node.js 2.0 driver is by using the `NPM` (Node Package Manager) to install the dependency in your project. + +## MongoDB Driver + +Given that you have created your own project using `npm init` we install the mongodb driver and it's dependencies by executing the following `NPM` command. + +``` +npm install mongodb --save +``` + +This will download the MongoDB driver and add a dependency entry in your `package.json` file. + +## Troubleshooting + +The MongoDB driver depends on several other packages. These are. + +* mongodb-core +* bson +* kerberos +* node-gyp + +The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build node.js itself to be able to compile and install the `kerberos` module. Furthermore the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager what libraries to install. + +{{% note class="important" %}} +Windows already contains the SSPI API used for Kerberos authentication. However you will need to install a full compiler tool chain using visual studio C++ to correctly install the kerberos extension. +{{% /note %}} + +### Diagnosing on UNIX + +If you don’t have the build essentials it won’t build. In the case of linux you will need gcc and g++, node.js with all the headers and python. The easiest way to figure out what’s missing is by trying to build the kerberos project. You can do this by performing the following steps. + +``` +git clone https://github.com/christkv/kerberos.git +cd kerberos +npm install +``` + +If all the steps complete you have the right toolchain installed. If you get node-gyp not found you need to install it globally by doing. + +``` +npm install -g node-gyp +``` + +If correctly compiles and runs the tests you are golden. We can now try to install the mongod driver by performing the following command. + +``` +cd yourproject +npm install mongodb --save +``` + +If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. + +``` +npm --loglevel verbose install mongodb +``` + +This will print out all the steps npm is performing while trying to install the module. + +### Diagnosing on Windows + +A known compiler tool chain known to work for compiling `kerberos` on windows is the following. + +* Visual Studio c++ 2010 (do not use higher versions) +* Windows 7 64bit SDK +* Python 2.7 or higher + +Open visual studio command prompt. Ensure node.exe is in your path and install node-gyp. + +``` +npm install -g node-gyp +``` + +Next you will have to build the project manually to test it. Use any tool you use with git and grab the repo. + +``` +git clone https://github.com/christkv/kerberos.git +cd kerberos +npm install +node-gyp rebuild +``` + +This should rebuild the driver successfully if you have everything set up correctly. + +### Other possible issues + +Your python installation might be hosed making gyp break. I always recommend that you test your deployment environment first by trying to build node itself on the server in question as this should unearth any issues with broken packages (and there are a lot of broken packages out there). + +Another thing is to ensure your user has write permission to wherever the node modules are being installed. + +QuickStart +========== +The quick start guide will show you how to setup a simple application using node.js and MongoDB. Its scope is only how to set up the driver and perform the simple crud operations. For more in depth coverage we encourage reading the tutorials. + +Create the package.json file +---------------------------- +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Enter the following command and answer the questions to create the initial structure for your new project + +``` +npm init +``` + +Next we need to edit the generated package.json file to add the dependency for the MongoDB driver. The package.json file below is just an example and your will look different depending on how you answered the questions after entering `npm init` + +``` +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb": "~2.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +Connecting to MongoDB +--------------------- +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server and the database **myproject**. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + db.close(); +}); +``` + +Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console. + +Let's Add some code to show the different CRUD operations available. + +Inserting a Document +-------------------- +Let's create a function that will insert some documents for us. + +```js +var insertDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.insertMany([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the document collection"); + callback(result); + }); +} +``` + +The insert command will return a results object that contains several fields that might be useful. + +* **result** Contains the result document from MongoDB +* **ops** Contains the documents inserted with added **_id** fields +* **connection** Contains the connection used to perform the insert + +Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + db.close(); + }); +}); +``` + +We can now run the update **app.js** file. + +``` +node app.js +``` + +You should see the following output after running the **app.js** file. + +``` +Connected correctly to server +Inserted 3 documents into the document collection +``` + +Updating a document +------------------- +Let's look at how to do a simple document update by adding a new field **b** to the document that has the field **a** set to **2**. + +```js +var updateDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.updateOne({ a : 2 } + , { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(result); + }); +} +``` + +The method will update the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Let's update the callback function from **MongoClient.connect** to include the update method. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + db.close(); + }); + }); +}); +``` + +Delete a document +----------------- +Next lets delete the document where the field **a** equals to **3**. + +```js +var deleteDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.deleteOne({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(result); + }); +} +``` + +This will delete the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient +.connect** callback function. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + deleteDocument(db, function() { + db.close(); + }); + }); + }); +}); +``` + +Finally let's retrieve all the documents using a simple find. + +Find All Documents +------------------ +We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query. + +```js +var findDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Find some documents + collection.find({}).toArray(function(err, docs) { + assert.equal(err, null); + assert.equal(2, docs.length); + console.log("Found the following records"); + console.dir(docs); + callback(docs); + }); +} +``` + +This query will return all the documents in the **documents** collection. Since we deleted a document the total +documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + deleteDocument(db, function() { + findDocuments(db, function() { + db.close(); + }); + }); + }); + }); +}); +``` + +This concludes the QuickStart of connecting and performing some Basic operations using the MongoDB Node.js driver. For more detailed information you can look at the tutorials covering more specific topics of interest. + +## Next Steps + + * [MongoDB Documentation](http://mongodb.org/) + * [Read about Schemas](http://learnmongodbthehardway.com/) + * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/conf.json b/5-3/node_modules/mongoose/node_modules/mongodb/conf.json new file mode 100644 index 0000000..aba0b7a --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/conf.json @@ -0,0 +1,73 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/functional/operation_example_tests.js", + "test/functional/operation_promises_example_tests.js", + "test/functional/operation_generators_example_tests.js", + "test/functional/authentication_tests.js", + "test/functional/gridfs_stream_tests.js", + "lib/admin.js", + "lib/collection.js", + "lib/cursor.js", + "lib/aggregation_cursor.js", + "lib/command_cursor.js", + "lib/db.js", + "lib/mongo_client.js", + "lib/mongos.js", + "lib/read_preference.js", + "lib/replset.js", + "lib/server.js", + "lib/bulk/common.js", + "lib/bulk/ordered.js", + "lib/bulk/unordered.js", + "lib/gridfs/grid_store.js", + "node_modules/mongodb-core/lib/error.js", + "lib/gridfs-stream/index.js", + "lib/gridfs-stream/download.js", + "lib/gridfs-stream/upload.js", + "node_modules/mongodb-core/lib/connection/logger.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/index.js b/5-3/node_modules/mongoose/node_modules/mongodb/index.js new file mode 100644 index 0000000..1ebe943 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/index.js @@ -0,0 +1,50 @@ +// Core module +var core = require('mongodb-core'), + Instrumentation = require('./lib/apm'); + +// Set up the connect function +var connect = require('./lib/mongo_client').connect; + +// Expose error class +connect.MongoError = core.MongoError; + +// Actual driver classes exported +connect.Admin = require('./lib/admin'); +connect.MongoClient = require('./lib/mongo_client'); +connect.Db = require('./lib/db'); +connect.Collection = require('./lib/collection'); +connect.Server = require('./lib/server'); +connect.ReplSet = require('./lib/replset'); +connect.Mongos = require('./lib/mongos'); +connect.ReadPreference = require('./lib/read_preference'); +connect.GridStore = require('./lib/gridfs/grid_store'); +connect.Chunk = require('./lib/gridfs/chunk'); +connect.Logger = core.Logger; +connect.Cursor = require('./lib/cursor'); +connect.GridFSBucket = require('./lib/gridfs-stream'); + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.Map = core.BSON.Map; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; + +// Add connect method +connect.connect = connect; + +// Set up the instrumentation method +connect.instrument = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + return new Instrumentation(core, options, callback); +} + +// Set our exports to be the connect function +module.exports = connect; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/admin.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/admin.js new file mode 100644 index 0000000..1f89512 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/admin.js @@ -0,0 +1,581 @@ +"use strict"; + +var toError = require('./utils').toError, + Define = require('./metadata'), + shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Use the admin database for the operation + * var adminDb = db.admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +var Admin = function(db, topology, promiseLibrary) { + if(!(this instanceof Admin)) return new Admin(db, topology); + var self = this; + + // Internal state + this.s = { + db: db + , topology: topology + , promiseLibrary: promiseLibrary + } +} + +var define = Admin.define = new Define('Admin', Admin, false); + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.command = function(command, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand(command, options, function(err, doc) { + return callback != null ? callback(err, doc) : null; + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand(command, options, function(err, doc) { + if(err) return reject(err); + resolve(doc); + }); + }); +} + +define.classMethod('command', {callback: true, promise:true}); + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.buildInfo = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.serverInfo(callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.serverInfo(function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('buildInfo', {callback: true, promise:true}); + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverInfo = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err != null) return callback(err, null); + callback(null, doc); + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err) return reject(err); + resolve(doc); + }); + }); +} + +define.classMethod('serverInfo', {callback: true, promise:true}); + +/** + * Retrieve this db's server status. + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverStatus = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return serverStatus(self, callback) + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + serverStatus(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var serverStatus = function(self, callback) { + self.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { + if(err == null && doc.ok === 1) { + callback(null, doc); + } else { + if(err) return callback(err, false); + return callback(toError(doc), false); + } + }); +} + +define.classMethod('serverStatus', {callback: true, promise:true}); + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.profilingLevel = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return profilingLevel(self, callback) + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + profilingLevel(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var profilingLevel = function(self, callback) { + self.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) { + doc = doc; + + 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); + } + }); +} + +define.classMethod('profilingLevel', {callback: true, promise:true}); + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.ping = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({ping: 1}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({ping: 1}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('ping', {callback: true, promise:true}); + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.authenticate = function(username, password, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options); + options.authdb = 'admin'; + + // Execute using callback + if(typeof callback == 'function') return this.s.db.authenticate(username, password, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.authenticate(username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('authenticate', {callback: true, promise:true}); + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.logout = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.s.db.logout({authdb: 'admin'}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.logout({authdb: 'admin'}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('logout', {callback: true, promise:true}); + +// Get write concern +var writeConcern = function(options, db) { + options = shallowClone(options); + + // If options already contain write concerns return it + if(options.w || options.wtimeout || options.j || options.fsync) { + return options; + } + + // Set db write concern if available + if(db.writeConcern) { + if(options.w) options.w = db.writeConcern.w; + if(options.wtimeout) options.wtimeout = db.writeConcern.wtimeout; + if(options.j) options.j = db.writeConcern.j; + if(options.fsync) options.fsync = db.writeConcern.fsync; + } + + // Return modified options + return options; +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.addUser = function(username, password, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + // Get the options + options = writeConcern(options, self.s.db) + // Set the db name to admin + options.dbName = 'admin'; + + // Execute using callback + if(typeof callback == 'function') + return self.s.db.addUser(username, password, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.addUser(username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('addUser', {callback: true, promise:true}); + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.removeUser = function(username, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + // Get the options + options = writeConcern(options, self.s.db) + // Set the db name + options.dbName = 'admin'; + + // Execute using callback + if(typeof callback == 'function') + return self.s.db.removeUser(username, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.removeUser(username, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('removeUser', {callback: true, promise:true}); + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.setProfilingLevel = function(level, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return setProfilingLevel(self, level, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + setProfilingLevel(self, level, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var setProfilingLevel = function(self, level, callback) { + 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; + + self.s.db.executeDbAdminCommand(command, function(err, doc) { + doc = doc; + + if(err == null && doc.ok === 1) + return callback(null, level); + return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + }); +} + +define.classMethod('setProfilingLevel', {callback: true, promise:true}); + +/** + * Retrive the current profiling information for MongoDB + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.profilingInfo = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return profilingInfo(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + profilingInfo(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var profilingInfo = function(self, callback) { + try { + self.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback); + } catch (err) { + return callback(err, null); + } +} + +define.classMethod('profilingLevel', {callback: true, promise:true}); + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options=null] Optional settings. + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') + return validateCollection(self, collectionName, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + validateCollection(self, collectionName, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var validateCollection = function(self, collectionName, options, callback) { + 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]]; + } + } + + self.s.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); + }); +} + +define.classMethod('validateCollection', {callback: true, promise:true}); + +/** + * List the available databases + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.listDatabases = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return self.s.db.executeDbAdminCommand({listDatabases:1}, {}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('listDatabases', {callback: true, promise:true}); + +/** + * Get ReplicaSet status + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.replSetGetStatus = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return replSetGetStatus(self, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + replSetGetStatus(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var replSetGetStatus = function(self, callback) { + self.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { + if(err == null && doc.ok === 1) + return callback(null, doc); + if(err) return callback(err, false); + callback(toError(doc), false); + }); +} + +define.classMethod('replSetGetStatus', {callback: true, promise:true}); + +module.exports = Admin; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js new file mode 100644 index 0000000..3663229 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js @@ -0,0 +1,432 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('./cursor') + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = AggregationCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + } +} + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(AggregationCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' + , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' + , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified']; + +// Extend the Cursor +for(var name in CoreCursor.prototype) { + AggregationCursor.prototype[name] = CoreCursor.prototype[name]; +} + +var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {AggregationCursor} + */ +AggregationCursor.prototype.batchSize = function(value) { + if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true }); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", drvier:true }); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.geoNear = function(document) { + this.s.cmd.pipeline.push({$geoNear: document}); + return this; +} + +define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.group = function(document) { + this.s.cmd.pipeline.push({$group: document}); + return this; +} + +define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.limit = function(value) { + this.s.cmd.pipeline.push({$limit: value}); + return this; +} + +define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.match = function(document) { + this.s.cmd.pipeline.push({$match: document}); + return this; +} + +define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.out = function(destination) { + this.s.cmd.pipeline.push({$out: destination}); + return this; +} + +define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.project = function(document) { + this.s.cmd.pipeline.push({$project: document}); + return this; +} + +define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.redact = function(document) { + this.s.cmd.pipeline.push({$redact: document}); + return this; +} + +define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.skip = function(value) { + this.s.cmd.pipeline.push({$skip: value}); + return this; +} + +define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.sort = function(document) { + this.s.cmd.pipeline.push({$sort: document}); + return this; +} + +define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.unwind = function(field) { + this.s.cmd.pipeline.push({$unwind: field}); + return this; +} + +define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]}); + +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +// Inherited methods +define.classMethod('toArray', {callback: true, promise:true}); +define.classMethod('each', {callback: true, promise:false}); +define.classMethod('forEach', {callback: true, promise:false}); +define.classMethod('next', {callback: true, promise:true}); +define.classMethod('close', {callback: true, promise:true}); +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); +define.classMethod('rewind', {callback: false, promise:false}); +define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); +define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * 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. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * 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. + * @method AggregationCursor.prototype.each + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +AggregationCursor.INIT = 0; +AggregationCursor.OPEN = 1; +AggregationCursor.CLOSED = 2; + +module.exports = AggregationCursor; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/apm.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/apm.js new file mode 100644 index 0000000..7b08012 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/apm.js @@ -0,0 +1,608 @@ +var EventEmitter = require('events').EventEmitter, + inherits = require('util').inherits; + +// Get prototypes +var AggregationCursor = require('./aggregation_cursor'), + CommandCursor = require('./command_cursor'), + OrderedBulkOperation = require('./bulk/ordered').OrderedBulkOperation, + UnorderedBulkOperation = require('./bulk/unordered').UnorderedBulkOperation, + GridStore = require('./gridfs/grid_store'), + Server = require('./server'), + ReplSet = require('./replset'), + Mongos = require('./mongos'), + Cursor = require('./cursor'), + Collection = require('./collection'), + Db = require('./db'), + Admin = require('./admin'); + +var basicOperationIdGenerator = { + operationId: 1, + + next: function() { + return this.operationId++; + } +} + +var basicTimestampGenerator = { + current: function() { + return new Date().getTime(); + }, + + duration: function(start, end) { + return end - start; + } +} + +var senstiveCommands = ['authenticate', 'saslStart', 'saslContinue', 'getnonce', + 'createUser', 'updateUser', 'copydbgetnonce', 'copydbsaslstart', 'copydb']; + +var Instrumentation = function(core, options, callback) { + options = options || {}; + + // Optional id generators + var operationIdGenerator = options.operationIdGenerator || basicOperationIdGenerator; + // Optional timestamp generator + var timestampGenerator = options.timestampGenerator || basicTimestampGenerator; + // Extend with event emitter functionality + EventEmitter.call(this); + + // Contains all the instrumentation overloads + this.overloads = []; + + // --------------------------------------------------------- + // + // Instrument prototype + // + // --------------------------------------------------------- + + var instrumentPrototype = function(callback) { + var instrumentations = [] + + // Classes to support + var classes = [GridStore, OrderedBulkOperation, UnorderedBulkOperation, + CommandCursor, AggregationCursor, Cursor, Collection, Db]; + + // Add instrumentations to the available list + for(var i = 0; i < classes.length; i++) { + if(classes[i].define) { + instrumentations.push(classes[i].define.generate()); + } + } + + // Return the list of instrumentation points + callback(null, instrumentations); + } + + // Did the user want to instrument the prototype + if(typeof callback == 'function') { + instrumentPrototype(callback); + } + + // --------------------------------------------------------- + // + // Server + // + // --------------------------------------------------------- + + // Reference + var self = this; + // Names of methods we need to wrap + var methods = ['command', 'insert', 'update', 'remove']; + // Prototype + var proto = core.Server.prototype; + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var requestId = core.Query.nextRequestId(); + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + var ns = args[0]; + var commandObj = args[1]; + var options = args[2] || {}; + var keys = Object.keys(commandObj); + var commandName = keys[0]; + var db = ns.split('.')[0]; + + // Do we have a legacy insert/update/remove command + if(x == 'insert' && !this.lastIsMaster().maxWireVersion) { + commandName = 'insert'; + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + insert: col, documents: commandObj + } + + if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { + commandObj.writeConcern = options.writeConcern; + } + + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'update' && !this.lastIsMaster().maxWireVersion) { + commandName = 'update'; + + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + update: col, updates: commandObj + } + + if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { + commandObj.writeConcern = options.writeConcern; + } + + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'remove' && !this.lastIsMaster().maxWireVersion) { + commandName = 'delete'; + + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + delete: col, deletes: commandObj + } + + if(options.writeConcern && Object.keys(options.writeConcern).length > 0) { + commandObj.writeConcern = options.writeConcern; + } + + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'insert' || x == 'update' || x == 'remove' && this.lastIsMaster().maxWireVersion >= 2) { + // Skip the insert/update/remove commands as they are executed as actual write commands in 2.6 or higher + return func.apply(this, args); + } + + // Get the callback + var callback = args.pop(); + // Set current callback operation id from the current context or create + // a new one + var ourOpId = callback.operationId || operationIdGenerator.next(); + + // Get a connection reference for this server instance + var connection = this.s.pool.get() + + // Emit the start event for the command + var command = { + // Returns the command. + command: commandObj, + // Returns the database name. + databaseName: db, + // Returns the command name. + commandName: commandName, + // Returns the driver generated request id. + requestId: requestId, + // Returns the driver generated operation id. + // This is used to link events together such as bulk write operations. OPTIONAL. + operationId: ourOpId, + // Returns the connection id for the command. For languages that do not have this, + // this MUST return the driver equivalent which MUST include the server address and port. + // The name of this field is flexible to match the object that is returned from the driver. + connectionId: connection + }; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.commandObj = {}; + command.commandObj[commandName] = true; + } + + // Emit the started event + self.emit('started', command) + + // Start time + var startTime = timestampGenerator.current(); + + // Push our handler callback + args.push(function(err, r) { + var endTime = timestampGenerator.current(); + var command = { + duration: timestampGenerator.duration(startTime, endTime), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: connection + }; + + // If we have an error + if(err || (r && r.result && r.result.ok == 0)) { + command.failure = err || r.result.writeErrors || r.result; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.failure = {}; + } + + self.emit('failed', command); + } else if(commandObj && commandObj.writeConcern + && commandObj.writeConcern.w == 0) { + // If we have write concern 0 + command.reply = {ok:1}; + self.emit('succeeded', command); + } else { + command.reply = r && r.result ? r.result : r; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase()) != -1) { + command.reply = {}; + } + + self.emit('succeeded', command); + } + + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } + }); + + // --------------------------------------------------------- + // + // Bulk Operations + // + // --------------------------------------------------------- + + // Inject ourselves into the Bulk methods + var methods = ['execute']; + var prototypes = [ + require('./bulk/ordered').Bulk.prototype, + require('./bulk/unordered').Bulk.prototype + ] + + prototypes.forEach(function(proto) { + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var bulk = this; + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + // Set an operation Id on the bulk object + this.operationId = operationIdGenerator.next(); + + // Get the callback + var callback = args.pop(); + // If we have a callback use this + if(typeof callback == 'function') { + args.push(function(err, r) { + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } else { + return func.apply(this, args); + } + } + }); + }); + + // --------------------------------------------------------- + // + // Cursor + // + // --------------------------------------------------------- + + // Inject ourselves into the Cursor methods + var methods = ['_find', '_getmore', '_killcursor']; + var prototypes = [ + require('./cursor').prototype, + require('./command_cursor').prototype, + require('./aggregation_cursor').prototype + ] + + // Command name translation + var commandTranslation = { + '_find': 'find', '_getmore': 'getMore', '_killcursor': 'killCursors', '_explain': 'explain' + } + + prototypes.forEach(function(proto) { + + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var cursor = this; + var requestId = core.Query.nextRequestId(); + var ourOpId = operationIdGenerator.next(); + var parts = this.ns.split('.'); + var db = parts[0]; + + // Get the collection + parts.shift(); + var collection = parts.join('.'); + + // Set the command + var command = this.query; + var cmd = this.s.cmd; + + // If we have a find method, set the operationId on the cursor + if(x == '_find') { + cursor.operationId = ourOpId; + } + + // Do we have a find command rewrite it + if(x == '_getmore') { + command = { + getMore: this.cursorState.cursorId, + collection: collection, + batchSize: cmd.batchSize + } + + if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; + } else if(x == '_killcursors') { + command = { + killCursors: collection, + cursors: [this.cursorState.cursorId] + } + } else if(cmd.find) { + command = { + find: collection, filter: cmd.query + } + + if(cmd.sort) command.sort = cmd.sort; + if(cmd.fields) command.projection = cmd.fields; + if(cmd.limit && cmd.limit < 0) { + command.limit = Math.abs(cmd.limit); + command.singleBatch = true; + } else if(cmd.limit) { + command.limit = Math.abs(cmd.limit); + } + + // Options + if(cmd.skip) command.skip = cmd.skip; + if(cmd.hint) command.hint = cmd.hint; + if(cmd.batchSize) command.batchSize = cmd.batchSize; + if(typeof cmd.returnKey == 'boolean') command.returnKey = cmd.returnKey; + if(cmd.comment) command.comment = cmd.comment; + if(cmd.min) command.min = cmd.min; + if(cmd.max) command.max = cmd.max; + if(cmd.maxScan) command.maxScan = cmd.maxScan; + if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; + + // Flags + if(typeof cmd.awaitData == 'boolean') command.awaitData = cmd.awaitData; + if(typeof cmd.snapshot == 'boolean') command.snapshot = cmd.snapshot; + if(typeof cmd.tailable == 'boolean') command.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') command.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') command.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.partial == 'boolean') command.partial = cmd.partial; + if(typeof cmd.showDiskLoc == 'boolean') command.showRecordId = cmd.showDiskLoc; + + // Read Concern + if(cmd.readConcern) command.readConcern = cmd.readConcern; + + // Override method + if(cmd.explain) command.explain = cmd.explain; + if(cmd.exhaust) command.exhaust = cmd.exhaust; + + // If we have a explain flag + if(cmd.explain) { + // Create fake explain command + command = { + explain: command, + verbosity: 'allPlansExecution' + } + + // Set readConcern on the command if available + if(cmd.readConcern) command.readConcern = cmd.readConcern + + // Set up the _explain name for the command + x = '_explain'; + } + } else { + command = cmd; + } + + // Set up the connection + var connectionId = null; + + // Set local connection + if(this.connection) connectionId = this.connection; + if(!connectionId && this.server && this.server.getConnection) connectionId = this.server.getConnection(); + + // Get the command Name + var commandName = x == '_find' ? Object.keys(command)[0] : commandTranslation[x]; + + // Emit the start event for the command + var command = { + // Returns the command. + command: command, + // Returns the database name. + databaseName: db, + // Returns the command name. + commandName: commandName, + // Returns the driver generated request id. + requestId: requestId, + // Returns the driver generated operation id. + // This is used to link events together such as bulk write operations. OPTIONAL. + operationId: this.operationId, + // Returns the connection id for the command. For languages that do not have this, + // this MUST return the driver equivalent which MUST include the server address and port. + // The name of this field is flexible to match the object that is returned from the driver. + connectionId: connectionId + }; + + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + + // Get the callback + var callback = args.pop(); + + // We do not have a callback but a Promise + if(typeof callback == 'function' || command.commandName == 'killCursors') { + var startTime = timestampGenerator.current(); + // Emit the started event + self.emit('started', command) + + // Emit succeeded event with killcursor if we have a legacy protocol + if(command.commandName == 'killCursors' + && this.server.lastIsMaster() + && this.server.lastIsMaster().maxWireVersion < 4) { + // Emit the succeeded command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: [{ok:1}] + }; + + // Emit the command + return self.emit('succeeded', command) + } + + // Add our callback handler + args.push(function(err, r) { + if(err) { + // Command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: cursor.server.getConnection(), + failure: err }; + + // Emit the command + self.emit('failed', command) + } else { + + // Do we have a getMore + if(commandName.toLowerCase() == 'getmore' && r == null) { + r = { + cursor: { + id: cursor.cursorState.cursorId, + ns: cursor.ns, + nextBatch: cursor.cursorState.documents + }, ok:1 + } + } else if(commandName.toLowerCase() == 'find' && r == null) { + r = { + cursor: { + id: cursor.cursorState.cursorId, + ns: cursor.ns, + firstBatch: cursor.cursorState.documents + }, ok:1 + } + } else if(commandName.toLowerCase() == 'killcursors' && r == null) { + r = { + cursorsUnknown:[cursor.cursorState.lastCursorId], + ok:1 + } + } + + // cursor id is zero, we can issue success command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: r && r.result ? r.result : r + }; + + // Emit the command + self.emit('succeeded', command) + } + + // Return + if(!callback) return; + + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } else { + // Assume promise, push back the missing value + args.push(callback); + // Get the promise + var promise = func.apply(this, args); + // Return a new promise + return new cursor.s.promiseLibrary(function(resolve, reject) { + var startTime = timestampGenerator.current(); + // Emit the started event + self.emit('started', command) + // Execute the function + promise.then(function(r) { + // cursor id is zero, we can issue success command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: cursor.cursorState.documents + }; + + // Emit the command + self.emit('succeeded', command) + }).catch(function(err) { + // Command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: cursor.server.getConnection(), + failure: err }; + + // Emit the command + self.emit('failed', command) + // reject the promise + reject(err); + }); + }); + } + } + }); + }); +} + +inherits(Instrumentation, EventEmitter); + +Instrumentation.prototype.uninstrument = function() { + for(var i = 0; i < this.overloads.length; i++) { + var obj = this.overloads[i]; + obj.proto[obj.name] = obj.func; + } + + // Remove all listeners + this.removeAllListeners('started'); + this.removeAllListeners('succeeded'); + this.removeAllListeners('failed'); +} + +module.exports = Instrumentation; \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 0000000..d5c5f93 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,431 @@ +"use strict"; + +var utils = require('../utils'), + Long = require('mongodb-core').BSON.Long, + Timestamp = require('mongodb-core').BSON.Timestamp; + +// 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 + + +// Get write concern +var writeConcern = function(target, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + target.writeConcern = options; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } + + return target +} + +/** + * Helper function to define properties + * @ignore + */ +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 + * @ignore + */ +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 + * @ignore + */ +var LegacyOp = function(batchType, operation, index) { + this.batchType = batchType; + this.index = index; + this.operation = operation; +} + +/** + * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {boolean} ok Did bulk operation correctly execute + * @property {number} nInserted number of inserted documents + * @property {number} nUpdated number of documents updated logically + * @property {number} nUpserted Number of upserted documents + * @property {number} nModified Number of documents updated physically on disk + * @property {number} nRemoved Number of removed documents + * @return {BulkWriteResult} a BulkWriteResult instance + */ +var BulkWriteResult = 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 inserted ids + * + * @return {object[]} + */ + this.getInsertedIds = function() { + return bulkResult.insertedIds; + } + + /** + * Return an array of upserted ids + * + * @return {object[]} + */ + 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 {object} + */ + this.getUpsertedIdAt = function(index) { + return bulkResult.upserted[index]; + } + + /** + * Return raw internal result + * + * @return {object} + */ + this.getRawResponse = function() { + return bulkResult; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + this.hasWriteErrors = function() { + return bulkResult.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + this.getWriteErrorCount = function() { + return bulkResult.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @return {WriteError} + */ + this.getWriteErrorAt = function(index) { + if(index < bulkResult.writeErrors.length) { + return bulkResult.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {object[]} + */ + this.getWriteErrors = function() { + return bulkResult.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + this.getLastOp = function() { + return bulkResult.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + 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 "BulkWriteResult(" + this.toJSON(bulkResult) + ")"; + } + + this.isOk = function() { + return bulkResult.ok == 1; + } +} + +/** + * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +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 + ")"; + } +} + +/** + * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {number} index Write concern error original bulk operation index. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +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 + * @ignore + */ +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; + } else if(result && result.result) { + result = result.result; + } else if(result == null) { + return; + } + + // 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); + var writeError = { + index: 0 + , code: result.code || 0 + , errmsg: result.message + , op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if(result.ok == 0 && bulkResult.ok == 0) { + return; + } + + // Deal with opTime if available + if(result.opTime || result.lastOp) { + var opTime = result.lastOp || result.opTime; + var lastOpTS = null; + var lastOpT = null; + + // We have a time stamp + if(opTime instanceof Timestamp) { + if(bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if(opTime.greaterThan(bulkResult.lastOp)) { + bulkResult.lastOp = opTime; + } + } else { + // Existing TS + if(bulkResult.lastOp) { + lastOpTS = typeof bulkResult.lastOp.ts == 'number' + ? Long.fromNumber(bulkResult.lastOp.ts) : bulkResult.lastOp.ts; + lastOpT = typeof bulkResult.lastOp.t == 'number' + ? Long.fromNumber(bulkResult.lastOp.t) : bulkResult.lastOp.t; + } + + // Current OpTime TS + var opTimeTS = typeof opTime.ts == 'number' + ? Long.fromNumber(opTime.ts) : opTime.ts; + var opTimeT = typeof opTime.t == 'number' + ? Long.fromNumber(opTime.t) : opTime.t; + + // Compare the opTime's + if(bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if(opTimeTS.greaterThan(lastOpTS)) { + bulkResult.lastOp = opTime; + } else if(opTimeTS.equals(lastOpTS)) { + if(opTimeT.greaterThan(lastOpT)) { + bulkResult.lastOp = opTime; + } + } + } + } + + // 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)); + } +} + +// +// 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.BulkWriteResult = BulkWriteResult; +exports.WriteError = WriteError; +exports.Batch = Batch; +exports.LegacyOp = LegacyOp; +exports.mergeBatchResults = mergeBatchResults; +exports.cloneOptions = cloneOptions; +exports.writeConcern = writeConcern; +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; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 0000000..b93ec71 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,530 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , f = require('util').format + , handleCallback = require('../utils').handleCallback + , shallowClone = utils.shallowClone + , WriteError = common.WriteError + , BulkWriteResult = common.BulkWriteResult + , LegacyOp = common.LegacyOp + , ObjectID = require('mongodb-core').BSON.ObjectID + , Define = require('../metadata') + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +/** + * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance. + */ +var FindOperatorsOrdered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +FindOperatorsOrdered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.deleteOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne; + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.delete = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete; + +// Add to internal list of documents +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = _self.s.bson.calculateObjectSize(document, false); + + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatchSize + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Reset the current size trackers + _self.s.currentBatchSize = 0; + _self.s.currentBatchSizeBytes = 0; + } else { + // Update current batch size + _self.s.currentBatchSize = _self.s.currentBatchSize + 1; + _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; + } + + if(docType == common.INSERT) { + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentBatch.operations.push(document) + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Return self + return _self; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ +function OrderedBulkOperation(topology, 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 bson = topology.bson; + + // Namespace for the operation + var namespace = collection.collectionName; + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize + ? topology.isMasterDoc.maxBsonObjectSize : (1024*1025*16); + var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize + ? topology.isMasterDoc.maxWriteBatchSize : 1000; + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Current batch + var currentBatch = null; + var currentIndex = 0; + var currentBatchSize = 0; + var currentBatchSizeBytes = 0; + var batches = []; + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentBatch: null + , currentIndex: 0 + , currentBatchSize: 0 + , currentBatchSizeBytes: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + // Promise Library + , promiseLibrary: promiseLibrary + // Fundamental error + , err: null + // Bypass validation + , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false + } +} + +var define = OrderedBulkOperation.define = new Define('OrderedBulkOperation', OrderedBulkOperation, false); + +OrderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Set up the force server object id + var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' + ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + operation.upsert = op[key].upsert ? true: false; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + var operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +OrderedBulkOperation.prototype.insert = function(document) { + if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +OrderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsOrdered(this); +} + +Object.defineProperty(OrderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// +// Execute next write command in a chain +var executeCommands = function(self, callback) { + if(self.s.batches.length == 0) { + return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult)); + } + + // Ordered execution of the command + var batch = self.s.batches.shift(); + + var resultHandler = function(err, result) { + // Error is a driver related error not a bulk op error, terminate + if(err && err.driver || err && err.message) { + return handleCallback(callback, err); + } + + // If we have and error + if(err) err.ok = 0; + // Merge the results together + var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result); + if(mergeResult != null) { + return handleCallback(callback, null, new BulkWriteResult(self.s.bulkResult)); + } + + // If we are ordered and have errors and they are + // not all replication errors terminate the operation + if(self.s.bulkResult.writeErrors.length > 0) { + return handleCallback(callback, toError(self.s.bulkResult.writeErrors[0]), new BulkWriteResult(self.s.bulkResult)); + } + + // Execute the next command in line + executeCommands(self, callback); + } + + var finalOptions = {ordered: true} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + // Set an operationIf if provided + if(self.operationId) { + resultHandler.operationId = self.operationId; + } + + // Serialize functions + if(self.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true + } + + // Serialize functions + if(self.s.options.ignoreUndefined) { + finalOptions.ignoreUndefined = true + } + + // Is the bypassDocumentValidation options specific + if(self.s.bypassDocumentValidation == true) { + finalOptions.bypassDocumentValidation = true; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +/** + * The callback format for results + * @callback OrderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {OrderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +OrderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + var self = this; + if(this.s.executed) throw new toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute using callback + if(typeof callback == 'function') { + return executeCommands(this, callback); + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeCommands(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('execute', {callback: true, promise:false}); + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeOrderedBulkOp = function(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; +module.exports = initializeOrderedBulkOp; +module.exports.Bulk = OrderedBulkOperation; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 0000000..70602b9 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,539 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , f = require('util').format + , handleCallback = require('../utils').handleCallback + , shallowClone = utils.shallowClone + , WriteError = common.WriteError + , BulkWriteResult = common.BulkWriteResult + , LegacyOp = common.LegacyOp + , ObjectID = require('mongodb-core').BSON.ObjectID + , Define = require('../metadata') + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +/** + * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance. + */ +var FindOperatorsUnordered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.removeOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.remove = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// +// Add to the operations list +// +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = _self.s.bson.calculateObjectSize(document, false); + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Holds the current batch + _self.s.currentBatch = null; + // Get the right type of batch + if(docType == common.INSERT) { + _self.s.currentBatch = _self.s.currentInsertBatch; + } else if(docType == common.UPDATE) { + _self.s.currentBatch = _self.s.currentUpdateBatch; + } else if(docType == common.REMOVE) { + _self.s.currentBatch = _self.s.currentRemoveBatch; + } + + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatch.size + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatch.sizeBytes + bsonSize) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.operations.push(document); + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Save back the current Batch to the right type + if(docType == common.INSERT) { + _self.s.currentInsertBatch = _self.s.currentBatch; + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } else if(docType == common.UPDATE) { + _self.s.currentUpdateBatch = _self.s.currentBatch; + } else if(docType == common.REMOVE) { + _self.s.currentRemoveBatch = _self.s.currentBatch; + } + + // Update current batch size + _self.s.currentBatch.size = _self.s.currentBatch.size + 1; + _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize; + + // Return self + return _self; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +var UnorderedBulkOperation = function(topology, 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 currentBatch = null; + 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 bson = topology.bson; + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc && topology.isMasterDoc.maxBsonObjectSize + ? topology.isMasterDoc.maxBsonObjectSize : (1024*1025*16); + var maxWriteBatchSize = topology.isMasterDoc && topology.isMasterDoc.maxWriteBatchSize + ? topology.isMasterDoc.maxWriteBatchSize : 1000; + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentInsertBatch: null + , currentUpdateBatch: null + , currentRemoveBatch: null + , currentBatch: null + , currentIndex: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + // Promise Library + , promiseLibrary: promiseLibrary + // Bypass validation + , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false + } +} + +var define = UnorderedBulkOperation.define = new Define('UnorderedBulkOperation', UnorderedBulkOperation, false); + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +UnorderedBulkOperation.prototype.insert = function(document) { + if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsUnordered} + */ +UnorderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsUnordered(this); +} + +Object.defineProperty(UnorderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +UnorderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Set up the force server object id + var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' + ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + if(op[key].upsert) operation.upsert = true; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + var operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +// +// Execute the command +var executeBatch = function(self, batch, callback) { + var finalOptions = {ordered: false} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + var resultHandler = function(err, result) { + // Error is a driver related error not a bulk op error, terminate + if(err && err.driver || err && err.message) { + return handleCallback(callback, err); + } + + // If we have and error + if(err) err.ok = 0; + handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, result)); + } + + // Set an operationIf if provided + if(self.operationId) { + resultHandler.operationId = self.operationId; + } + + // Serialize functions + if(self.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true + } + + // Is the bypassDocumentValidation options specific + if(self.s.bypassDocumentValidation == true) { + finalOptions.bypassDocumentValidation = true; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback(callback, null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +// +// Execute all the commands +var executeBatches = function(self, callback) { + var numberOfCommandsToExecute = self.s.batches.length; + var error = null; + // Execute over all the batches + for(var i = 0; i < self.s.batches.length; i++) { + executeBatch(self, self.s.batches[i], function(err, result) { + // Driver layer error capture it + if(err) error = err; + // Count down the number of commands left to execute + numberOfCommandsToExecute = numberOfCommandsToExecute - 1; + + // Execute + if(numberOfCommandsToExecute == 0) { + // Driver level error + if(error) return handleCallback(callback, error); + // Treat write errors + var error = self.s.bulkResult.writeErrors.length > 0 ? toError(self.s.bulkResult.writeErrors[0]) : null; + handleCallback(callback, error, new BulkWriteResult(self.s.bulkResult)); + } + }); + } +} + +/** + * The callback format for results + * @callback UnorderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +UnorderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + var self = this; + if(this.s.executed) throw toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if(this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if(this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute using callback + if(typeof callback == 'function') return executeBatches(this, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeBatches(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('execute', {callback: true, promise:false}); + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeUnorderedBulkOp = function(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; +module.exports = initializeUnorderedBulkOp; +module.exports.Bulk = UnorderedBulkOperation; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/collection.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/collection.js new file mode 100644 index 0000000..048c9c5 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/collection.js @@ -0,0 +1,3179 @@ +"use strict"; + +var checkCollectionName = require('./utils').checkCollectionName + , ObjectID = require('mongodb-core').BSON.ObjectID + , Long = require('mongodb-core').BSON.Long + , Code = require('mongodb-core').BSON.Code + , f = require('util').format + , AggregationCursor = require('./aggregation_cursor') + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone + , isObject = require('./utils').isObject + , toError = require('./utils').toError + , normalizeHintField = require('./utils').normalizeHintField + , handleCallback = require('./utils').handleCallback + , decorateCommand = require('./utils').decorateCommand + , formattedOrderClause = require('./utils').formattedOrderClause + , ReadPreference = require('./read_preference') + , CoreReadPreference = require('mongodb-core').ReadPreference + , CommandCursor = require('./command_cursor') + , Define = require('./metadata') + , Cursor = require('./cursor') + , unordered = require('./bulk/unordered') + , ordered = require('./bulk/ordered'); + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {string} collectionName Get the collection name. + * @property {string} namespace Get the full collection namespace. + * @property {object} writeConcern The current write concern values. + * @property {object} readConcern The current read concern values. + * @property {object} hint Get current index hint for collection. + * @return {Collection} a Collection instance. + */ +var Collection = function(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + var self = this; + // Unpack variables + var internalHint = null; + var opts = options != null && ('object' === typeof options) ? options : {}; + var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + var serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; + var raw = options == null || options.raw == null ? db.raw : options.raw; + var readPreference = null; + var collectionHint = null; + var namespace = f("%s.%s", dbName, name); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Assign the right collection level readPreference + if(options && options.readPreference) { + readPreference = options.readPreference; + } else if(db.options.readPreference) { + readPreference = db.options.readPreference; + } + + // Set custom primary key factory if provided + pkFactory = pkFactory == null + ? ObjectID + : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory + // Db + , db: db + // Topology + , topology: topology + // dbName + , dbName: dbName + // Options + , options: options + // Namespace + , namespace: namespace + // Read preference + , readPreference: readPreference + // Raw + , raw: raw + // SlaveOK + , slaveOk: slaveOk + // Serialize functions + , serializeFunctions: serializeFunctions + // internalHint + , internalHint: internalHint + // collectionHint + , collectionHint: collectionHint + // Name + , name: name + // Promise library + , promiseLibrary: promiseLibrary + // Read Concern + , readConcern: options.readConcern + } +} + +var define = Collection.define = new Define('Collection', Collection, false); + +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, get: function() { return this.s.name; } +}); + +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, get: function() { return this.s.namespace; } +}); + +Object.defineProperty(Collection.prototype, 'readConcern', { + enumerable: true, get: function() { return this.s.readConcern || {level: 'local'}; } +}); + +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(this.s.options.w != null) ops.w = this.s.options.w; + if(this.s.options.j != null) ops.j = this.s.options.j; + if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * @ignore + */ +Object.defineProperty(Collection.prototype, "hint", { + enumerable: true + , get: function () { return this.s.collectionHint; } + , set: function (v) { this.s.collectionHint = normalizeHintField(v); } +}); + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} query The cursor query object. + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = function() { + 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 && fields !== undefined && !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]; + } + + // Unpack options + 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.s.raw; + newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + 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.s.db.slaveOk; + + // Add read preference if needed + newOptions = getReadPreference(this, newOptions, this.s.db, this); + // Set slave ok to true if read preference different from primary + if(newOptions.readPreference != null + && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if(selector != null && typeof selector != 'object') { + throw MongoError.create({message: "query selector must be an object", driver:true }); + } + + // Build the find command + var findCommand = { + find: this.s.namespace + , limit: newOptions.limit + , skip: newOptions.skip + , query: selector + } + + // Ensure we use the right await data option + if(typeof newOptions.awaitdata == 'boolean') { + newOptions.awaitData = newOptions.awaitdata + }; + + // Translate to new command option noCursorTimeout + if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + // Merge in options to command + for(var name in newOptions) { + if(newOptions[name] != null) findCommand[name] = newOptions[name]; + } + + // Format the fields + var formatFields = function(fields) { + var object = {}; + if(Array.isArray(fields)) { + for(var i = 0; i < fields.length; i++) { + if(Array.isArray(fields[i])) { + object[fields[i][0]] = fields[i][1]; + } else { + object[fields[i][0]] = 1; + } + } + } else { + object = fields; + } + + return object; + } + + // Special treatment for the fields selector + if(fields) findCommand.fields = formatFields(fields); + + // Add db object to the new options + newOptions.db = this.s.db; + + // Add the promise library + newOptions.promiseLibrary = this.s.promiseLibrary; + + // Set raw if available at collection level + if(newOptions.raw == null && this.s.raw) newOptions.raw = this.s.raw; + + // Sort options + if(findCommand.sort) + findCommand.sort = formattedOrderClause(findCommand.sort); + + // Set the readConcern + if(this.s.readConcern) { + findCommand.readConcern = this.s.readConcern; + } + + // Create the cursor + if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions)); + return this.s.topology.cursor(this.s.namespace, findCommand, newOptions); +} + +define.classMethod('find', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object} doc Document to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertOne = function(doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + if(Array.isArray(doc)) return callback(MongoError.create({message: 'doc parameter must be an object', driver:true })); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return insertOne(self, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + insertOne(self, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var insertOne = function(self, doc, options, callback) { + insertDocuments(self, [doc], options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + // Workaround for pre 2.6 servers + if(r == null) return callback(null, {result: {ok:1}}); + // Add values to top level to ensure crud spec compatibility + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if(callback) callback(null, r); + }); +} + +var mapInserManyResults = function(docs, r) { + var ids = r.getInsertedIds(); + var keys = Object.keys(ids); + var finalIds = new Array(keys); + + for(var i = 0; i < keys.length; i++) { + if(ids[keys[i]]._id) { + finalIds[ids[keys[i]].index] = ids[keys[i]]._id; + } + } + + var finalResult = { + result: {ok: 1, n: r.insertedCount}, + ops: docs, + insertedCount: r.insertedCount, + insertedIds: finalIds + }; + + if(r.getLastOp()) { + finalResult.result.opTime = r.getLastOp(); + } + + return finalResult; +} + +define.classMethod('insertOne', {callback: true, promise:true}); + +/** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertMany = function(docs, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:true}; + if(!Array.isArray(docs)) return callback(MongoError.create({message: 'docs parameter must be an array of documents', driver:true })); + + // Get the write concern options + if(typeof options.checkKeys != 'boolean') { + options.checkKeys = true; + } + + // If keep going set unordered + options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Set up the force server object id + var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' + ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; + + // Do we want to force the server to assign the _id key + if(forceServerObjectId !== true) { + // Add _id if not specified + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + } + + // Generate the bulk write operations + var operations = [{ + insertMany: docs + }]; + + // Execute using callback + if(typeof callback == 'function') return bulkWrite(self, operations, options, function(err, r) { + if(err) return callback(err, r); + callback(null, mapInserManyResults(docs, r)); + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + bulkWrite(self, operations, options, function(err, r) { + if(err) return reject(err); + resolve(mapInserManyResults(docs, r)); + }); + }); +} + +define.classMethod('insertMany', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:true}; + + if(!Array.isArray(operations)) { + throw MongoError.create({message: "operations must be an array of documents", driver:true }); + } + + // Execute using callback + if(typeof callback == 'function') return bulkWrite(self, operations, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + bulkWrite(self, operations, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var bulkWrite = function(self, operations, options, callback) { + // Add ignoreUndfined + if(self.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = self.s.options.ignoreUndefined; + } + + // Create the bulk operation + var bulk = options.ordered == true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options); + + // for each op go through and add to the bulk + for(var i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + + // Final options for write concern + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + + // Execute the bulk + bulk.execute(writeCon, function(err, r) { + // We have connection level error + if(!r && err) return callback(err, null); + // We have single error + if(r && r.hasWriteErrors() && r.getWriteErrorCount() == 1) { + return callback(toError(r.getWriteErrorAt(0)), r); + } + + // if(err) return callback(err); + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Update the n + r.n = r.insertedCount; + + // Inserted documents + var inserted = r.getInsertedIds(); + // Map inserted ids + for(var i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + var upserted = r.getUpsertedIds(); + // Map upserted ids + for(var i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Check if we have write errors + if(r.hasWriteErrors()) { + // Get all the errors + var errors = r.getWriteErrors(); + // Return the MongoError object + return callback(toError({ + message: 'write operation failed', code: errors[0].code, writeErrors: errors + }), r); + } + + // Check if we have a writeConcern error + if(r.getWriteConcernError()) { + // Return the MongoError object + return callback(toError(r.getWriteConcernError()), r); + } + + // Return the results + callback(null, r); + }); +} + +var insertDocuments = function(self, docs, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true; + + // If keep going set unordered + if(finalOptions.keepGoing == true) finalOptions.ordered = false; + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Set up the force server object id + var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' + ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; + + // Add _id if not specified + if(forceServerObjectId !== true){ + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + } + + // File inserts + self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +define.classMethod('bulkWrite', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * @typedef {Object} Collection~insertWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId[]} insertedIds All the generated _id's for the inserted documents. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * @typedef {Object} Collection~insertOneWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * The callback format for inserts + * @callback Collection~insertWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * The callback format for inserts + * @callback Collection~insertOneWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = function(docs, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:false}; + docs = !Array.isArray(docs) ? [docs] : docs; + + if(options.keepGoing == true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); +} + +define.classMethod('insert', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~updateWriteOpResult + * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents scanned. + * @property {Number} result.nModified The total count of documents modified. + * @property {Object} connection The connection object used for the operation. + * @property {Number} matchedCount The number of documents that matched the filter. + * @property {Number} modifiedCount The number of documents that were modified. + * @property {Number} upsertedCount The number of documents upserted. + * @property {Object} upsertedId The upserted id. + * @property {ObjectId} upsertedId._id The upserted _id returned from the server. + */ + +/** + * The callback format for inserts + * @callback Collection~updateWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Update a single document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateOne(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateOne(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var updateOne = function(self, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + if(callback) callback(null, r); + }); +} + +define.classMethod('updateOne', {callback: true, promise:true}); + +/** + * Replace a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} doc The Document that replaces the matching document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.replaceOne = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return replaceOne(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + replaceOne(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var replaceOne = function(self, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.ops = [update]; + if(callback) callback(null, r); + }); +} + +define.classMethod('replaceOne', {callback: true, promise:true}); + +/** + * Update multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateMany(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateMany(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var updateMany = function(self, filter, update, options, callback) { + // Set single document update + options.multi = true; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + if(callback) callback(null, r); + }); +} + +define.classMethod('updateMany', {callback: true, promise:true}); + +var updateDocuments = function(self, selector, document, options, callback) { + if('function' === typeof options) callback = options, options = null; + if(options == null) options = {}; + if(!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object")); + if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object")); + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Execute the operation + var op = {q: selector, u: document}; + op.upsert = typeof options.upsert == 'boolean' ? options.upsert : false; + op.multi = typeof options.multi == 'boolean' ? options.multi : false; + + // Update options + self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} document The update document. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = function(selector, document, options, callback) { + var self = this; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateDocuments(self, selector, document, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateDocuments(self, selector, document, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('update', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~deleteWriteOpResult + * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents deleted. + * @property {Object} connection The connection object used for the operation. + * @property {Number} deletedCount The number of documents deleted. + */ + +/** + * The callback format for inserts + * @callback Collection~deleteWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Delete a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + var options = shallowClone(options); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return deleteOne(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + deleteOne(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var deleteOne = function(self, filter, options, callback) { + options.single = true; + removeDocuments(self, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +define.classMethod('deleteOne', {callback: true, promise:true}); + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +define.classMethod('removeOne', {callback: true, promise:true}); + +/** + * Delete multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + var options = shallowClone(options); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return deleteMany(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + deleteMany(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var deleteMany = function(self, filter, options, callback) { + options.single = false; + removeDocuments(self, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +var removeDocuments = function(self, selector, options, callback) { + if(typeof options == 'function') { + callback = options, options = {}; + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // If selector is null set empty + if(selector == null) selector = {}; + + // Build the op + var op = {q: selector, limit: 0}; + if(options.single) op.limit = 1; + + // Execute the remove + self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +define.classMethod('deleteMany', {callback: true, promise:true}); + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +define.classMethod('removeMany', {callback: true, promise:true}); + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = function(selector, options, callback) { + var self = this; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return removeDocuments(self, selector, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + removeDocuments(self, selector, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('remove', {callback: true, promise:true}); + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +Collection.prototype.save = function(doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return save(self, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + save(self, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var save = function(self, doc, options, callback) { + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + // Establish if we need to perform an insert or update + if(doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(self, {_id: doc._id}, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(self, [doc], options, function(err, r) { + if(callback == null) return; + if(doc == null) return handleCallback(callback, null, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, r); + }); +} + +define.classMethod('save', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options=null] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan=null] Limit the number of items to scan. + * @param {number} [options.min=null] Set index bounds. + * @param {number} [options.max=null] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use find().limit(1).next(function(err, doc){}) + */ +Collection.prototype.findOne = function() { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + var callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + + // Execute using callback + if(typeof callback == 'function') return findOne(self, args, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + findOne(self, args, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOne = function(self, args, callback) { + var cursor = self.find.apply(self, args).limit(-1).batchSize(1); + // Return the item + cursor.next(function(err, item) { + if(err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); +} + +define.classMethod('findOne', {callback: true, promise:true}); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Collection~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.rename = function(newName, opt, callback) { + var self = this; + if(typeof opt == 'function') callback = opt, opt = {}; + opt = opt || {}; + + // Execute using callback + if(typeof callback == 'function') return rename(self, newName, opt, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + rename(self, newName, opt, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var rename = function(self, newName, opt, callback) { + // Check the collection name + checkCollectionName(newName); + // Build the command + var renameCollection = f("%s.%s", self.s.dbName, self.s.name); + var toCollection = f("%s.%s", self.s.dbName, newName); + var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false; + var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}; + + // Execute against admin + self.s.db.admin().command(cmd, opt, function(err, doc) { + if(err) return handleCallback(callback, err, null); + // We have an error + if(doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options)); + } catch(err) { + return handleCallback(callback, toError(err), null); + } + }); +} + +define.classMethod('rename', {callback: true, promise:true}); + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.drop = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return self.s.db.dropCollection(self.s.name, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.dropCollection(self.s.name, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('drop', {callback: true, promise:true}); + +/** + * Returns the options of the collection. + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.options = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return options(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var options = function(self, callback) { + self.s.db.listCollections({name: self.s.name}).toArray(function(err, collections) { + if(err) return handleCallback(callback, err); + if(collections.length == 0) { + return handleCallback(callback, MongoError.create({message: f("collection %s not found", self.s.namespace), driver:true })); + } + + handleCallback(callback, err, collections[0].options || null); + }); +} + +define.classMethod('options', {callback: true, promise:true}); + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.isCapped = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return isCapped(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + isCapped(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var isCapped = function(self, callback) { + self.options(function(err, document) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, document && document.capped); + }); +} + +define.classMethod('isCapped', {callback: true, promise:true}); + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + + // Execute using callback + if(typeof callback == 'function') return createIndex(self, fieldOrSpec, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndex(self, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var createIndex = function(self, fieldOrSpec, options, callback) { + self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback); +} + +define.classMethod('createIndex', {callback: true, promise:true}); + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * @method + * @param {array} indexSpecs An array of index specifications to be created + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndexes = function(indexSpecs, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return createIndexes(self, indexSpecs, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndexes(self, indexSpecs, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var createIndexes = function(self, indexSpecs, callback) { + // Ensure we generate the correct name if the parameter is not set + for(var i = 0; i < indexSpecs.length; i++) { + if(indexSpecs[i].name == null) { + var keys = []; + + for(var name in indexSpecs[i].key) { + keys.push(f('%s_%s', name, indexSpecs[i].key[name])); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + // Execute the index + self.s.db.command({ + createIndexes: self.s.name, indexes: indexSpecs + }, callback); +} + +define.classMethod('createIndexes', {callback: true, promise:true}); + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + // Execute using callback + if(typeof callback == 'function') return dropIndex(self, indexName, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + dropIndex(self, indexName, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var dropIndex = function(self, indexName, options, callback) { + // Delete index command + var cmd = {'deleteIndexes':self.s.name, 'index':indexName}; + + // Execute command + self.s.db.command(cmd, options, function(err, result) { + if(typeof callback != 'function') return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +define.classMethod('dropIndex', {callback: true, promise:true}); + +/** + * Drops all indexes from this collection. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndexes = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return dropIndexes(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + dropIndexes(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var dropIndexes = function(self, callback) { + self.dropIndex('*', function (err, result) { + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); +} + +define.classMethod('dropIndexes', {callback: true, promise:true}); + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {Promise} returns Promise if no [callback] passed + */ +Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes; + +define.classMethod('dropAllIndexes', {callback: true, promise:true}); + +/** + * 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. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.reIndex = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return reIndex(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + reIndex(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var reIndex = function(self, options, callback) { + // Reindex + var cmd = {'reIndex':self.s.name}; + + // Execute the command + self.s.db.command(cmd, options, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +define.classMethod('reIndex', {callback: true, promise:true}); + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + options = options || {}; + // Clone the options + options = shallowClone(options); + // Set the CommandCursor constructor + options.cursorFactory = CommandCursor; + // Set the promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + if(!this.s.topology.capabilities()) { + throw new MongoError('cannot connect to server'); + } + + // We have a list collections command + if(this.s.topology.capabilities().hasListIndexesCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listIndexes: this.s.name, cursor: cursor }; + // Execute the cursor + var cursor = this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options); + // Do we have a readPreference, apply it + if(options.readPreference) cursor.setReadPreference(options.readPreference); + // Return the cursor + return cursor; + } + + // Get the namespace + var ns = f('%s.system.indexes', this.s.dbName); + // Get the query + var cursor = this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options); + // Do we have a readPreference, apply it + if(options.readPreference) cursor.setReadPreference(options.readPreference); + // Set the passed in batch size if one was provided + if(options.batchSize) cursor = cursor.batchSize(options.batchSize); + // Return the cursor + return cursor; +}; + +define.classMethod('listIndexes', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return ensureIndex(self, fieldOrSpec, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + ensureIndex(self, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var ensureIndex = function(self, fieldOrSpec, options, callback) { + self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback); +} + +define.classMethod('ensureIndex', {callback: true, promise:true}); + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexExists = function(indexes, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return indexExists(self, indexes, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexExists(self, indexes, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexExists = function(self, indexes, callback) { + self.indexInformation(function(err, indexInformation) { + // If we have an error return + if(err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for(var i = 0; i < indexes.length; i++) { + if(indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +define.classMethod('indexExists', {callback: true, promise:true}); + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexInformation = function(options, callback) { + var self = this; + // Unpack calls + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return indexInformation(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexInformation(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexInformation = function(self, options, callback) { + self.s.db.indexInformation(self.s.name, options, callback); +} + +define.classMethod('indexInformation', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * Count number of matching documents in the db to a query. + * @method + * @param {object} query The query for the count. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.limit=null] The limit of documents to count. + * @param {boolean} [options.skip=null] The number of documents to skip for the count. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~countCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.count = function(query, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + var queryOption = args.length ? args.shift() || {} : {}; + var optionsOption = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return count(self, queryOption, optionsOption, callback); + + // Check if query is empty + query = query || {}; + options = options || {}; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + count(self, query, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var count = function(self, query, options, callback) { + var skip = options.skip; + var limit = options.limit; + var hint = options.hint; + var maxTimeMS = options.maxTimeMS; + + // Final query + var cmd = { + 'count': self.s.name, 'query': query + }; + + // Add limit and skip if defined + if(typeof skip == 'number') cmd.skip = skip; + if(typeof limit == 'number') cmd.limit = limit; + if(hint) options.hint = hint; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + cmd.readConcern = self.s.readConcern; + } + + // Execute command + self.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.n); + }); +} + +define.classMethod('count', {callback: true, promise:true}); + +/** + * The distinct command returns returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.distinct = function(key, query, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + var queryOption = args.length ? args.shift() || {} : {}; + var optionsOption = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return distinct(self, key, queryOption, optionsOption, callback); + + // Ensure the query and options are set + query = query || {}; + options = options || {}; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + distinct(self, key, query, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var distinct = function(self, key, query, options, callback) { + // maxTimeMS option + var maxTimeMS = options.maxTimeMS; + + // Distinct command + var cmd = { + 'distinct': self.s.name, 'key': key, 'query': query + }; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + cmd.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.values); + }); +} + +define.classMethod('distinct', {callback: true, promise:true}); + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexes = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return indexes(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexes(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexes = function(self, callback) { + self.s.db.indexInformation(self.s.name, {full:true}, callback); +} + +define.classMethod('indexes', {callback: true, promise:true}); + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Collection~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.stats = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return stats(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + stats(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var stats = function(self, options, callback) { + // Build command object + var commandObject = { + collStats:self.s.name + } + + // Check if we have the scale value + if(options['scale'] != null) commandObject['scale'] = options['scale']; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Execute the command + self.s.db.command(commandObject, options, callback); +} + +define.classMethod('stats', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~findAndModifyWriteOpResult + * @property {object} value Document returned from findAndModify command. + * @property {object} lastErrorObject The raw lastErrorObject returned from the command. + * @property {Number} ok Is 1 if the command executed correctly. + */ + +/** + * The callback format for inserts + * @callback Collection~findAndModifyCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndDelete(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndDelete(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndDelete = function(self, filter, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['remove'] = true; + // Execute find and Modify + self.findAndModify( + filter + , options.sort + , null + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndDelete', {callback: true, promise:true}); + +/** + * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} replacement Document replacing the matching document. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndReplace(self, filter, replacement, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndReplace(self, filter, replacement, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndReplace = function(self, filter, replacement, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['update'] = true; + finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; + finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; + + // Execute findAndModify + self.findAndModify( + filter + , options.sort + , replacement + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndReplace', {callback: true, promise:true}); + +/** + * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} update Update operations to be performed on the document + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndUpdate(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndUpdate(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndUpdate = function(self, filter, update, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['update'] = true; + finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; + finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; + + // Execute findAndModify + self.findAndModify( + filter + , options.sort + , update + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndUpdate', {callback: true, promise:true}); + +/** + * Find and update a document. + * @method + * @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=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = function(query, sort, doc, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + var options = shallowClone(options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + // Execute using callback + if(typeof callback == 'function') return findAndModify(self, query, sort, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findAndModify(self, query, sort, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findAndModify = function(self, query, sort, doc, options, callback) { + // Create findAndModify command object + var queryObject = { + 'findandmodify': self.s.name + , 'query': query + }; + + sort = formattedOrderClause(sort); + if(sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + if(options.fields) { + queryObject.fields = options.fields; + } + + if(doc && !options.remove) { + queryObject.update = doc; + } + + // 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'] = self.s.serializeFunctions; + } + + // No check on the documents + options.checkKeys = false; + + // Get the write concern settings + var finalOptions = writeConcern(options, self.s.db, self, options); + + // Decorate the findAndModify command with the write Concern + if(finalOptions.writeConcern) { + queryObject.writeConcern = finalOptions.writeConcern; + } + + // Have we specified bypassDocumentValidation + if(typeof finalOptions.bypassDocumentValidation == 'boolean') { + queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; + } + + // Execute the command + self.s.db.command(queryObject + , options, function(err, result) { + if(err) return handleCallback(callback, err, null); + return handleCallback(callback, null, result); + }); +} + +define.classMethod('findAndModify', {callback: true, promise:true}); + +/** + * Find and remove a document. + * @method + * @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=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = function(query, sort, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return findAndRemove(self, query, sort, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + findAndRemove(self, query, sort, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findAndRemove = function(self, query, sort, options, callback) { + // Add the remove option + options['remove'] = true; + // Execute the callback + self.findAndModify(query, sort, null, options, callback); +} + +define.classMethod('findAndRemove', {callback: true, promise:true}); + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} pipeline Array containing all the aggregation framework commands for the execution. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~resultCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + var self = this; + if(Array.isArray(pipeline)) { + // Set up callback if one is provided + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if(options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + var args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + var opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = opts && (opts.readPreference + || opts.explain || opts.cursor || opts.out + || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + // Ignore readConcern option + var ignoreReadConcern = false; + + // If out was specified + if(typeof options.out == 'string') { + pipeline.push({$out: options.out}); + ignoreReadConcern = true; + } else if(pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { + ignoreReadConcern = true; + } + + // Build the command + var command = { aggregate : this.s.name, pipeline : pipeline}; + + // If we have bypassDocumentValidation set + if(typeof options.bypassDocumentValidation == 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Do we have a readConcern specified + if(!ignoreReadConcern && this.s.readConcern) { + command.readConcern = this.s.readConcern; + } + + // If we have allowDiskUse defined + if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // If explain has been specified add it + if(options.explain) command.explain = options.explain; + + // Validate that cursor options is valid + if(options.cursor != null && typeof options.cursor != 'object') { + throw toError('cursor options must be an object'); + } + + // promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Set the AggregationCursor constructor + options.cursorFactory = AggregationCursor; + if(typeof callback != 'function') { + if(!this.s.topology.capabilities()) { + throw new MongoError('cannot connect to server'); + } + + if(this.s.topology.capabilities().hasAggregationCursor) { + options.cursor = options.cursor || { batchSize : 1000 }; + command.cursor = options.cursor; + } + + // Allow disk usage command + if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Execute the cursor + return this.s.topology.cursor(this.s.namespace, command, options); + } + + var cursor = null; + // We do not allow cursor + if(options.cursor) { + return this.s.topology.cursor(this.s.namespace, command, options); + } + + // Execute the command + this.s.db.command(command, options, function(err, result) { + if(err) { + handleCallback(callback, err); + } else if(result['err'] || result['errmsg']) { + handleCallback(callback, toError(result)); + } else if(typeof result == 'object' && result['serverPipeline']) { + handleCallback(callback, null, result['serverPipeline']); + } else if(typeof result == 'object' && result['stages']) { + handleCallback(callback, null, result['stages']); + } else { + handleCallback(callback, null, result.result); + } + }); +} + +define.classMethod('aggregate', {callback: true, promise:false}); + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.parallelCollectionScan = function(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; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Add a promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Execute using callback + if(typeof callback == 'function') return parallelCollectionScan(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + parallelCollectionScan(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var parallelCollectionScan = function(self, options, callback) { + // Create command object + var commandObject = { + parallelCollectionScan: self.s.name + , numCursors: options.numCursors + } + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Store the raw value + var raw = options.raw; + delete options['raw']; + + // Execute the command + self.s.db.command(commandObject, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null); + + var cursors = []; + // Add the raw back to the option + if(raw) options.raw = raw; + // 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 cmd = { + batchSize: options.batchSize + , cursorId: cursorId + , items: result.cursors[i].cursor.firstBatch + } + + // Add a command cursor + cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +define.classMethod('parallelCollectionScan', {callback: true, promise:true}); + +/** + * Execute the geoNear command to search for items in the collection + * + * @method + * @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 {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.num=null] Max number of results to return. + * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher) + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions. + * @param {object} [options.query=null] Filter the results by a query. + * @param {boolean} [options.spherical=false] Perform query using a spherical model. + * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X. + * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoNear = function(x, y, options, callback) { + var self = this; + var point = typeof(x) == 'object' && x + , args = Array.prototype.slice.call(arguments, point?1:2); + + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return geoNear(self, x, y, point, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + geoNear(self, x, y, point, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var geoNear = function(self, x, y, point, options, callback) { + // Build command object + var commandObject = { + geoNear:self.s.name, + near: point || [x, y] + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Exclude readPreference and existing options to prevent user from + // shooting themselves in the foot + var exclude = { + readPreference: true, + geoNear: true, + near: true + }; + + // Filter out any excluded objects + commandObject = decorateCommand(commandObject, options, exclude); + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) return handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +define.classMethod('geoNear', {callback: true, promise:true}); + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @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 {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {object} [options.search=null] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return geoHaystackSearch(self, x, y, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + geoHaystackSearch(self, x, y, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var geoHaystackSearch = function(self, x, y, options, callback) { + // Build command object + var commandObject = { + geoSearch: self.s.name, + near: [x, y] + } + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, {readPreference: true}); + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) handleCallback(callback, utils.toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +define.classMethod('geoHaystackSearch', {callback: true, promise:true}); + +/** + * 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(); + +/** + * Run a group command across a collection + * + * @method + * @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=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 3); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // 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 callback + if(typeof callback == 'function') return group(self, keys, condition, initial, reduce, finalize, command, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + group(self, keys, condition, initial, reduce, finalize, command, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) { + // Execute using the command + if(command) { + var reduceFunction = reduce instanceof Code + ? reduce + : new Code(reduce); + + var selector = { + group: { + 'ns': self.s.name + , '$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; + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + selector.readConcern = self.s.readConcern; + } + + // Execute command + self.s.db.command(selector, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + var scope = reduce != null && reduce instanceof Code + ? reduce.scope + : {}; + + scope.ns = self.s.name; + 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() + ';'); + + self.s.db.eval(new Code(groupfn, scope), function (err, results) { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +define.classMethod('group', {callback: true, promise:true}); + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope (scope) { + if(!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; +} + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query=null] Query filter object. + * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit=null] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize=null] Finalize function. + * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~resultCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + var self = this; + 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(); + } + + // Execute using callback + if(typeof callback == 'function') return mapReduce(self, map, reduce, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + mapReduce(self, map, reduce, options, function(err, r, r1) { + if(err) return reject(err); + if(r instanceof Collection) return resolve(r); + resolve({results: r, stats: r1}); + }); + }); +} + +var mapReduce = function(self, map, reduce, options, callback) { + var mapCommandHash = { + mapreduce: self.s.name + , map: map + , reduce: reduce + }; + + // Add any other options passed in + for(var n in options) { + if('scope' == n) { + mapCommandHash[n] = processScope(options[n]); + } else { + mapCommandHash[n] = options[n]; + } + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // If we have a read preference and inline is not set as output fail hard + if((options.readPreference != false && options.readPreference != 'primary') + && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { + options.readPreference = 'primary'; + } else if(self.s.readConcern) { + mapCommandHash.readConcern = self.s.readConcern; + } + + // Is bypassDocumentValidation specified + if(typeof options.bypassDocumentValidation == 'boolean') { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Execute command + self.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) { + if(err) return handleCallback(callback, err); + // Check if we have an error + if(1 != result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + var stats = {}; + if(result.timeMillis) stats['processtime'] = result.timeMillis; + if(result.counts) stats['counts'] = result.counts; + if(result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if(result.results) { + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, result.results, stats); + } + + // The returned collection + var collection = null; + + // If we have an object it's a different db + if(result.result != null && typeof result.result == 'object') { + var doc = result.result; + collection = self.s.db.db(doc.db).collection(doc.collection); + } else { + // Create a collection object that wraps the result collection + collection = self.s.db.collection(result.result) + } + + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, collection, stats); + }); +} + +define.classMethod('mapReduce', {callback: true, promise:true}); + +/** + * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @return {UnorderedBulkOperation} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return unordered(this.s.topology, this, options); +} + +define.classMethod('initializeUnorderedBulkOp', {callback: false, promise:false, returns: [ordered.UnorderedBulkOperation]}); + +/** + * 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. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return ordered(this.s.topology, this, options); +} + +define.classMethod('initializeOrderedBulkOp', {callback: false, promise:false, returns: [ordered.OrderedBulkOperation]}); + +// Get write concern +var writeConcern = function(target, db, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w != null) opts.w = options.w; + if(options.wtimeout != null) opts.wtimeout = options.wtimeout; + if(options.j != null) opts.j = options.j; + if(options.fsync != null) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Figure out the read preference +var getReadPreference = function(self, options, db, coll) { + var r = null + if(options.readPreference) { + r = options.readPreference + } else if(self.s.readPreference) { + r = self.s.readPreference + } else if(db.readPreference) { + r = db.readPreference; + } + + if(r instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else if(typeof r == 'string') { + options.readPreference = new CoreReadPreference(r); + } else if(r && !(r instanceof ReadPreference) && typeof r == 'object') { + var mode = r.mode || r.preference; + if (mode && typeof mode == 'string') { + options.readPreference = new CoreReadPreference(mode, r.tags); + } + } + + return options; +} + +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, 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 +} + +module.exports = Collection; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js new file mode 100644 index 0000000..94c5234 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js @@ -0,0 +1,320 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('./cursor') + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = CommandCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + } +} + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(CommandCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' + , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' + , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled']; + +// Only inherit the types we need +for(var i = 0; i < methodsToInherit.length; i++) { + CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; +} + +var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true); + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +CommandCursor.prototype.setReadPreference = function(r) { + if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(this.s.state != CommandCursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); + + if(r instanceof ReadPreference) { + this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else if(typeof r == 'string') { + this.s.options.readPreference = new CoreReadPreference(r); + } else if(r instanceof CoreReadPreference) { + this.s.options.readPreference = r; + } + + return this; +} + +define.classMethod('setReadPreference', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {CommandCursor} + */ +CommandCursor.prototype.batchSize = function(value) { + if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ +CommandCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]}); + +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +define.classMethod('get', {callback: true, promise:false}); + +// Inherited methods +define.classMethod('toArray', {callback: true, promise:true}); +define.classMethod('each', {callback: true, promise:false}); +define.classMethod('forEach', {callback: true, promise:false}); +define.classMethod('next', {callback: true, promise:true}); +define.classMethod('close', {callback: true, promise:true}); +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); +define.classMethod('rewind', {callback: false, promise:false}); +define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); +define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * 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. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * 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. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +CommandCursor.INIT = 0; +CommandCursor.OPEN = 1; +CommandCursor.CLOSED = 2; + +module.exports = CommandCursor; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/cursor.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/cursor.js new file mode 100644 index 0000000..c2d0deb --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/cursor.js @@ -0,0 +1,1199 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('mongodb-core').Cursor + , Map = require('mongodb-core').BSON.Map + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the mongodb-core and node.js + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +var fields = ['numberOfRetries', 'tailableRetryInterval']; +var push = Array.prototype.push; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Cursor cursor options. + * + * collection.find({}).project({a:1}) // Create a projection of field a + * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 + * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 + * collection.find({}).filter({a:1}) // Set query on the cursor + * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries + * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable + * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay + * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout + * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData + * collection.find({}).addCursorFlag('exhaust', true) // Set cursor as exhaust + * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial + * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} + * collection.find({}).max(10) // Set the cursor maxScan + * collection.find({}).maxScan(10) // Set the cursor maxScan + * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS + * collection.find({}).min(100) // Set the cursor min + * collection.find({}).returnKey(10) // Set the cursor returnKey + * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference + * collection.find({}).showRecordId(true) // Set the cursor showRecordId + * collection.find({}).snapshot(true) // Set the cursor snapshot + * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query + * collection.find({}).hint('a_1') // Set the cursor hint + * + * All options are chainable, so one can do the following. + * + * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = Cursor.INIT; + var streamOptions = {}; + + // Tailable cursor options + var numberOfRetries = options.numberOfRetries || 5; + var tailableRetryInterval = options.tailableRetryInterval || 500; + var currentNumberOfRetries = numberOfRetries; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries + , tailableRetryInterval: tailableRetryInterval + , currentNumberOfRetries: currentNumberOfRetries + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespace + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + // Current doc + , currentDoc: null + } + + // Legacy fields + this.timeout = self.s.options.noCursorTimeout == true; + this.sortValue = self.s.cmd.sort; +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(Cursor, Readable); + +// Map core cursor _next method so we can apply mapping +CoreCursor.prototype._next = CoreCursor.prototype.next; + +for(var name in CoreCursor.prototype) { + Cursor.prototype[name] = CoreCursor.prototype[name]; +} + +var define = Cursor.define = new Define('Cursor', Cursor, true); + +/** + * Check if there is any document still available in the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.hasNext = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') { + if(self.s.currentDoc){ + return callback(null, true); + } else { + return nextObject(self, function(err, doc) { + if(!doc) return callback(null, false); + self.s.currentDoc = doc; + callback(null, true); + }); + } + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + if(self.s.currentDoc){ + resolve(true); + } else { + nextObject(self, function(err, doc) { + if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false); + if(err) return reject(err); + if(!doc) return resolve(false); + self.s.currentDoc = doc; + resolve(true); + }); + } + }); +} + +define.classMethod('hasNext', {callback: true, promise:true}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.next = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') { + // Return the currentDoc if someone called hasNext first + if(self.s.currentDoc) { + var doc = self.s.currentDoc; + self.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + return nextObject(self, callback) + }; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + // Return the currentDoc if someone called hasNext first + if(self.s.currentDoc) { + var doc = self.s.currentDoc; + self.s.currentDoc = null; + return resolve(doc); + } + + nextObject(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('next', {callback: true, promise:true}); + +/** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ +Cursor.prototype.filter = function(filter) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.query = filter; + return this; +} + +define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor maxScan + * @method + * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query + * @return {Cursor} + */ +Cursor.prototype.maxScan = function(maxScan) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxScan = maxScan; + return this; +} + +define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor hint + * @method + * @param {object} hint If specified, then the query system will only consider plans using the hinted index. + * @return {Cursor} + */ +Cursor.prototype.hint = function(hint) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.hint = hint; + return this; +} + +define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor min + * @method + * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.min = function(min) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.min = min; + return this; +} + +define.classMethod('min', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor max + * @method + * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.max = function(max) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.max = max; + return this; +} + +define.classMethod('max', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor returnKey + * @method + * @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms: + * @return {Cursor} + */ +Cursor.prototype.returnKey = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.returnKey = value; + return this; +} + +define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor showRecordId + * @method + * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + * @return {Cursor} + */ +Cursor.prototype.showRecordId = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.showDiskLoc = value; + return this; +} + +define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor snapshot + * @method + * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. + * @return {Cursor} + */ +Cursor.prototype.snapshot = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.snapshot = value; + return this; +} + +define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setCursorOption = function(field, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true }); + this.s[field] = value; + if(field == 'numberOfRetries') + this.s.currentNumberOfRetries = value; + return this; +} + +define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addCursorFlag = function(flag, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true }); + if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true}); + this.s.cmd[flag] = value; + return this; +} + +define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addQueryModifier = function(name, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true}); + // Strip of the $ + var field = name.substr(1); + // Set on the command + this.s.cmd[field] = value; + // Deal with the special case for sort + if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field]; + return this; +} + +define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.comment = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.comment = value; + return this; +} + +define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * @method + * @param {number} value Number of milliseconds to wait before aborting the tailed query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxAwaitTimeMS = function(value) { + if(typeof value != 'number') throw MongoError.create({message: "maxAwaitTimeMS must be a number", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxAwaitTimeMS = value; + return this; +} + +define.classMethod('maxAwaitTimeMS', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxTimeMS = function(value) { + if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxTimeMS = value; + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]}); + +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.project = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.fields = value; + return this; +} + +define.classMethod('project', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.sort = function(keyOrList, direction) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + var order = keyOrList; + + // We have an array of arrays, we need to preserve the order of the sort + // so we will us a Map + if(Array.isArray(order) && Array.isArray(order[0])) { + order = new Map(order.map(function(x) { + var value = [x[0], null]; + if(x[1] == 'asc') { + value[1] = 1; + } else if(x[1] == 'desc') { + value[1] = -1; + } else if(x[1] == 1 || x[1] == -1) { + value[1] = x[1]; + } else { + throw new MongoError("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); + } + + return value; + })); + } + + if(direction != null) { + order = [[keyOrList, direction]]; + } + + this.s.cmd.sort = order; + this.sortValue = order; + return this; +} + +define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.batchSize = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true}); + if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); + this.s.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.limit = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true}); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true}); + this.s.cmd.limit = value; + // this.cursorLimit = value; + this.setCursorLimit(value); + return this; +} + +define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.skip = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true}); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true}); + this.s.cmd.skip = value; + this.setCursorSkip(value); + return this; +} + +define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]}); + +/** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null|boolean)} result The result object if the command was executed successfully. + */ + +/** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + +/** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @deprecated + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.nextObject = Cursor.prototype.next; + +var nextObject = function(self, callback) { + if(self.s.state == Cursor.CLOSED || self.isDead && self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); + if(self.s.state == Cursor.INIT && self.s.cmd.sort) { + try { + self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort); + } catch(err) { + return handleCallback(callback, err); + } + } + + // Get the next object + self._next(function(err, doc) { + if(err && err.tailable && self.s.currentNumberOfRetries == 0) return callback(err); + if(err && err.tailable && self.s.currentNumberOfRetries > 0) { + self.s.currentNumberOfRetries = self.s.currentNumberOfRetries - 1; + + return setTimeout(function() { + // Rewind the cursor only when it has not actually read any documents yet + if(self.cursorState.currentLimit == 0) self.rewind(); + // Read the next document, forcing a re-issue of query if no cursorId exists + self.nextObject(callback); + }, self.s.tailableRetryInterval); + } + + self.s.state = Cursor.OPEN; + if(err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +define.classMethod('nextObject', {callback: true, promise:true}); + +// 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.bufferedCount() == 0) return; + // Get the next document + self._next(callback); + // Loop + return loop; +} + +Cursor.prototype.next = Cursor.prototype.nextObject; + +define.classMethod('next', {callback: true, promise:true}); + +/** + * 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. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.each = function(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = Cursor.INIT; + // Run the query + _each(this, callback); +}; + +define.classMethod('each', {callback: true, promise:false}); + +// Run the each loop +var _each = function(self, callback) { + if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true}); + if(self.isNotified()) return; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); + } + + if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN; + + // Define function to avoid global scope escape + var fn = null; + // Trampoline all the entries + if(self.bufferedCount() > 0) { + while(fn = loop(self, callback)) fn(self, callback); + _each(self, callback); + } else { + self.next(function(err, item) { + if(err) return handleCallback(callback, err); + if(item == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, null); + } + + if(handleCallback(callback, null, item) == false) return; + _each(self, callback); + }) + } +} + +/** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.forEach = function(iterator, callback) { + this.each(function(err, doc){ + if(err) { callback(err); return false; } + if(doc != null) { iterator(doc); return true; } + if(doc == null && callback) { + var internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); +} + +define.classMethod('forEach', {callback: true, promise:false}); + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setReadPreference = function(r) { + if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); + if(r instanceof ReadPreference) { + this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else if(typeof r == 'string'){ + this.s.options.readPreference = new CoreReadPreference(r); + } else if(r instanceof CoreReadPreference) { + this.s.options.readPreference = r; + } + + return this; +} + +define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]}); + +/** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * 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. + * @method + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.toArray = function(callback) { + var self = this; + if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true}); + + // Execute using callback + if(typeof callback == 'function') return toArray(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + toArray(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var toArray = function(self, callback) { + var items = []; + + // Reset cursor + self.rewind(); + self.s.state = Cursor.INIT; + + // Fetch all the documents + var fetchDocs = function() { + self._next(function(err, doc) { + if(err) return handleCallback(callback, err); + if(doc == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, items); + } + + // Add doc to items + items.push(doc) + + // Get all buffered objects + if(self.bufferedCount() > 0) { + var docs = self.readBufferedDocuments(self.bufferedCount()) + + // Transform the doc if transform method added + if(self.s.transforms && typeof self.s.transforms.doc == 'function') { + docs = docs.map(self.s.transforms.doc); + } + + push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }) + } + + fetchDocs(); +} + +define.classMethod('toArray', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + +/** + * Get the count of documents for this cursor + * @method + * @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options=null] Optional settings. + * @param {number} [options.skip=null] The number of documents to skip. + * @param {number} [options.limit=null] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.count = function(applySkipLimit, opts, callback) { + var self = this; + if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true}); + if(typeof opts == 'function') callback = opts, opts = {}; + opts = opts || {}; + + // Execute using callback + if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + count(self, applySkipLimit, opts, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var count = function(self, applySkipLimit, opts, callback) { + if(typeof applySkipLimit == 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if(applySkipLimit) { + if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip(); + if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit(); + } + + // Command + var delimiter = self.s.ns.indexOf('.'); + + var command = { + 'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query + } + + if(typeof opts.maxTimeMS == 'number') { + command.maxTimeMS = opts.maxTimeMS; + } else if(self.s.cmd && typeof self.s.cmd.maxTimeMS == 'number') { + command.maxTimeMS = self.s.cmd.maxTimeMS; + } + + // Get a server + var server = self.s.topology.getServer(opts); + // Get a connection + var connection = self.s.topology.getConnection(opts); + // Get the callbacks + var callbacks = server.getCallbacks(); + + // Merge in any options + if(opts.skip) command.skip = opts.skip; + if(opts.limit) command.limit = opts.limit; + if(self.s.options.hint) command.hint = self.s.options.hint; + + // Build Query object + var query = new Query(self.s.bson, f("%s.$cmd", self.s.ns.substr(0, delimiter)), command, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false + }); + + // Set up callback + callbacks.register(query.requestId, function(err, result) { + if(err) return handleCallback(callback, err); + if(result.documents.length == 1 + && (result.documents[0].errmsg + || result.documents[0].err + || result.documents[0]['$err'])) { + return handleCallback(callback, MongoError.create(result.documents[0])); + } + handleCallback(callback, null, result.documents[0].n); + }); + + // Write the initial command out + connection.write(query.toBin()); +} + +define.classMethod('count', {callback: true, promise:true}); + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.close = function(callback) { + this.s.state = Cursor.CLOSED; + // Kill the cursor + this.kill(); + // Emit the close event for the cursor + this.emit('close'); + // Callback if provided + if(typeof callback == 'function') return handleCallback(callback, null, this); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + resolve(); + }); +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {null} + */ +Cursor.prototype.map = function(transform) { + this.cursorState.transforms = { doc: transform }; + return this; +} + +define.classMethod('map', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Is the cursor closed + * @method + * @return {boolean} + */ +Cursor.prototype.isClosed = function() { + return this.isDead(); +} + +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); + +Cursor.prototype.destroy = function(err) { + if(err) this.emit('error', err); + this.pause(); + this.close(); +} + +define.classMethod('destroy', {callback: false, promise:false}); + +/** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options=null] Optional settings. + * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ +Cursor.prototype.stream = function(options) { + this.s.streamOptions = options || {}; + return this; +} + +define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.explain = function(callback) { + var self = this; + this.s.cmd.explain = true; + + // Do we have a readConcern + if(this.s.cmd.readConcern) { + delete this.s.cmd['readConcern']; + } + + // Execute using callback + if(typeof callback == 'function') return this._next(callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self._next(function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('explain', {callback: true, promise:true}); + +Cursor.prototype._read = function(n) { + var self = this; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return self.push(null); + } + + // Get the next item + self.nextObject(function(err, result) { + if(err) { + if(self.listeners('error') && self.listeners('error').length > 0) { + self.emit('error', err); + } + if(!self.isDead()) self.close(); + + // Emit end event + self.emit('end'); + return self.emit('finish'); + } + + // If we provided a transformation method + if(typeof self.s.streamOptions.transform == 'function' && result != null) { + return self.push(self.s.streamOptions.transform(result)); + } + + // If we provided a map function + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) { + return self.push(self.cursorState.transforms.doc(result)); + } + + // Return the result + self.push(result); + }); +} + +Object.defineProperty(Cursor.prototype, 'readPreference', { + enumerable:true, + get: function() { + if (!this || !this.s) { + return null; + } + + return this.s.options.readPreference; + } +}); + +Object.defineProperty(Cursor.prototype, 'namespace', { + enumerable: true, + get: function() { + if (!this || !this.s) { + return null; + } + + // TODO: refactor this logic into core + var ns = this.s.ns || ''; + var firstDot = ns.indexOf('.'); + if (firstDot < 0) { + return { + database: this.s.ns, + collection: '' + }; + } + return { + database: ns.substr(0, firstDot), + collection: ns.substr(firstDot + 1) + }; + } +}); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +Cursor.INIT = 0; +Cursor.OPEN = 1; +Cursor.CLOSED = 2; +Cursor.GET_MORE = 3; + +module.exports = Cursor; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/db.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/db.js new file mode 100644 index 0000000..c253231 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/db.js @@ -0,0 +1,1807 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , getSingleProperty = require('./utils').getSingleProperty + , shallowClone = require('./utils').shallowClone + , parseIndexOptions = require('./utils').parseIndexOptions + , debugOptions = require('./utils').debugOptions + , CommandCursor = require('./command_cursor') + , handleCallback = require('./utils').handleCallback + , toError = require('./utils').toError + , ReadPreference = require('./read_preference') + , f = require('util').format + , Admin = require('./admin') + , Code = require('mongodb-core').BSON.Code + , CoreReadPreference = require('mongodb-core').ReadPreference + , MongoError = require('mongodb-core').MongoError + , ObjectID = require('mongodb-core').ObjectID + , Define = require('./metadata') + , Logger = require('mongodb-core').Logger + , Collection = require('./collection') + , crypto = require('crypto'); + +var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId' + , 'serializeFunctions', 'raw', 'promoteLongs', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds' + , 'readPreference', 'pkFactory']; + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * var testDb = db.db('test'); + * db.close(); + * }); + */ + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.native_parser=true] Select C++ bson parser instead of JavaScript parser. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {number} [options.bufferMaxEntries=-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. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @fires Db#close + * @fires Db#authenticated + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +var Db = function(databaseName, topology, options) { + options = options || {}; + if(!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + var self = this; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Ensure we put the promiseLib in the options + options.promiseLibrary = promiseLibrary; + + // var self = this; // Internal state of the db object + this.s = { + // Database name + databaseName: databaseName + // DbCache + , dbCache: {} + // Children db's + , children: [] + // Topology + , topology: topology + // Options + , options: options + // Logger instance + , logger: Logger('Db', options) + // Get the bson parser + , bson: topology ? topology.bson : null + // Authsource if any + , authSource: options.authSource + // Unpack read preference + , readPreference: options.readPreference + // Set buffermaxEntries + , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1 + // Parent db (if chained) + , parentDb: options.parentDb || null + // Set up the primary key factory or fallback to ObjectID + , pkFactory: options.pkFactory || ObjectID + // Get native parser + , nativeParser: options.nativeParser || options.native_parser + // Promise library + , promiseLibrary: promiseLibrary + // No listener + , noListener: typeof options.noListener == 'boolean' ? options.noListener : false + // ReadConcern + , readConcern: options.readConcern + } + + // Ensure we have a valid db name + validateDatabaseName(self.s.databaseName); + + // If we have specified the type of parser + if(typeof self.s.nativeParser == 'boolean') { + if(self.s.nativeParser) { + topology.setBSONParserType("c++"); + } else { + topology.setBSONParserType("js"); + } + } + + // Add a read Only property + getSingleProperty(this, 'serverConfig', self.s.topology); + getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', self.s.databaseName); + + // Last ismaster + Object.defineProperty(this, 'options', { + enumerable:true, + get: function() { return self.s.options; } + }); + + // Last ismaster + Object.defineProperty(this, 'native_parser', { + enumerable:true, + get: function() { return self.s.topology.parserType() == 'c++'; } + }); + + // Last ismaster + Object.defineProperty(this, 'slaveOk', { + enumerable:true, + get: function() { + if(self.s.options.readPreference != null + && (self.s.options.readPreference != 'primary' || self.s.options.readPreference.mode != 'primary')) { + return true; + } + return false; + } + }); + + Object.defineProperty(this, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(self.s.options.w != null) ops.w = self.s.options.w; + if(self.s.options.j != null) ops.j = self.s.options.j; + if(self.s.options.fsync != null) ops.fsync = self.s.options.fsync; + if(self.s.options.wtimeout != null) ops.wtimeout = self.s.options.wtimeout; + return ops; + } + }); + + // This is a child db, do not register any listeners + if(options.parentDb) return; + if(this.s.noListener) return; + + // Add listeners + topology.on('error', createListener(self, 'error', self)); + topology.on('timeout', createListener(self, 'timeout', self)); + topology.on('close', createListener(self, 'close', self)); + topology.on('parseError', createListener(self, 'parseError', self)); + topology.once('open', createListener(self, 'open', self)); + topology.once('fullsetup', createListener(self, 'fullsetup', self)); + topology.once('all', createListener(self, 'all', self)); + topology.on('reconnect', createListener(self, 'reconnect', self)); +} + +inherits(Db, EventEmitter); + +var define = Db.define = new Define('Db', Db, false); + +/** + * The callback format for the Db.open method + * @callback Db~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The Db instance if the open method was successful. + */ + +// Internal method +var open = function(self, callback) { + self.s.topology.connect(self, self.s.options, function(err, topology) { + if(callback == null) return; + var internalCallback = callback; + callback == null; + + if(err) { + self.close(); + return internalCallback(err); + } + + internalCallback(null, self); + }); +} + +/** + * Open the database + * @method + * @param {Db~openCallback} [callback] Callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.open = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return open(self, callback); + // Return promise + return new self.s.promiseLibrary(function(resolve, reject) { + open(self, function(err, db) { + if(err) return reject(err); + resolve(db); + }) + }); +} + +define.classMethod('open', {callback: true, promise:true}); + +/** + * Converts provided read preference to CoreReadPreference + * @param {(ReadPreference|string|object)} readPreference the user provided read preference + * @return {CoreReadPreference} + */ +var convertReadPreference = function(readPreference) { + if(readPreference && typeof readPreference == 'string') { + return new CoreReadPreference(readPreference); + } else if(readPreference instanceof ReadPreference) { + return new CoreReadPreference(readPreference.mode, readPreference.tags); + } else if(readPreference && typeof readPreference == 'object') { + var mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode == 'string') { + readPreference = new CoreReadPreference(mode, readPreference.tags); + } + } + return readPreference; +} + +/** + * The callback format for results + * @callback Db~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +var executeCommand = function(self, command, options, callback) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // Get the db name we are executing against + var dbName = options.dbName || options.authdb || self.s.databaseName; + // If we have a readPreference set + if(options.readPreference == null && self.s.readPreference) { + options.readPreference = self.s.readPreference; + } + + // Convert the readPreference + if(options.readPreference) { + options.readPreference = convertReadPreference(options.readPreference); + } + + // Debug information + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]' + , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options)))); + + // Execute command + self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) { + if(err) return handleCallback(callback, err); + if(options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); +} + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.command = function(command, options, callback) { + var self = this; + // Change the callback + if(typeof options == 'function') callback = options, options = {}; + // Clone the options + options = shallowClone(options); + + // Do we have a callback + if(typeof callback == 'function') return executeCommand(self, command, options, callback); + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeCommand(self, command, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('command', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Db~noResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {null} result Is not set to a value + */ + +/** + * Close the db and it's underlying connections + * @method + * @param {boolean} force Force close, emitting no events + * @param {Db~noResultCallback} [callback] The result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.close = function(force, callback) { + if(typeof force == 'function') callback = force, force = false; + this.s.topology.close(force); + var self = this; + + // Fire close event if any listeners + if(this.listeners('close').length > 0) { + this.emit('close'); + + // If it's the top level db emit close on all children + if(this.parentDb == null) { + // Fire close on all children + for(var i = 0; i < this.s.children.length; i++) { + this.s.children[i].emit('close'); + } + } + + // Remove listeners after emit + self.removeAllListeners('close'); + } + + // Close parent db if set + if(this.s.parentDb) this.s.parentDb.close(); + // Callback after next event loop tick + if(typeof callback == 'function') return process.nextTick(function() { + handleCallback(callback, null); + }) + + // Return dummy promise + return new this.s.promiseLibrary(function(resolve, reject) { + resolve(); + }); +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + return new Admin(this, this.s.topology, this.s.promiseLibrary); +}; + +define.classMethod('admin', {callback: false, promise:false, returns: [Admin]}); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * 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'); + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {Db~collectionResultCallback} callback The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + options = shallowClone(options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // If we have not set a collection level readConcern set the db level one + options.readConcern = options.readConcern || this.s.readConcern; + + // Do we have ignoreUndefined set + if(this.s.options.ignoreUndefined) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute + if(options == null || !options.strict) { + try { + var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.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 toError(f("A callback is required in strict mode. While getting collection %s.", name)); + } + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + // Strict mode + this.listCollections({name:name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null); + + try { + return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + } catch(err) { + return handleCallback(callback, err, null); + } + }); +} + +define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); + +var createCollection = function(self, name, options, callback) { + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self, options); + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // Check if we have the name + self.listCollections({name: name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length > 0 && finalOptions.strict) { + return handleCallback(callback, MongoError.create({message: f("Collection %s already exists. Currently in strict mode.", name), driver:true}), null); + } else if (collections.length > 0) { + try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); } + catch(err) { return handleCallback(callback, err); } + } + + // Create collection command + var cmd = {'create':name}; + + // Add all optional parameters + for(var n in options) { + if(options[n] != null && typeof options[n] != 'function') + cmd[n] = options[n]; + } + + // Execute command + self.command(cmd, finalOptions, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + }); + }); +} + +/** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {number} [options.size=null] The size of the capped collection in bytes. + * @param {number} [options.max=null] The maximum number of documents in the capped collection. + * @param {boolean} [options.autoIndexId=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. + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createCollection = function(name, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + name = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Do we have a promisesLibrary + options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; + + // Check if the callback is in fact a string + if(typeof callback == 'string') name = callback; + + // Execute the fallback callback + if(typeof callback == 'function') return createCollection(self, name, options, callback); + return new this.s.promiseLibrary(function(resolve, reject) { + createCollection(self, name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('createCollection', {callback: true, promise:true}); + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Db~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.stats = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // 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 + return this.command(commandObject, options, callback); +} + +define.classMethod('stats', {callback: true, promise:true}); + +// Transformation methods for cursor results +var listCollectionsTranforms = function(databaseName) { + var matching = f('%s.', databaseName); + + return { + doc: function(doc) { + var index = doc.name.indexOf(matching); + // Remove database name if available + if(doc.name && index == 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + } +} + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} filter Query to filter collections by + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + // Shallow clone the object + options = shallowClone(options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // Ensure valid readPreference + if(options.readPreference) { + options.readPreference = convertReadPreference(options.readPreference); + } + + // We have a list collections command + if(this.serverConfig.capabilities().hasListCollectionsCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listCollections : true, filter: filter, cursor: cursor }; + // Set the AggregationCursor constructor + options.cursorFactory = CommandCursor; + // Create the cursor + var cursor = this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options); + // Do we have a readPreference, apply it + if(options.readPreference) { + cursor.setReadPreference(options.readPreference); + } + // Return the cursor + return cursor; + } + + // We cannot use the listCollectionsCommand + if(!this.serverConfig.capabilities().hasListCollectionsCommand) { + // If we have legacy mode and have not provided a full db name filter it + if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) { + filter = shallowClone(filter); + filter.name = f('%s.%s', this.s.databaseName, filter.name); + } + } + + // No filter, filter by current database + if(filter == null) { + filter.name = f('/%s/', this.s.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: listCollectionsTranforms(this.s.databaseName)} + // Get the cursor + var cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options); + // Do we have a readPreference, apply it + if(options.readPreference) cursor.setReadPreference(options.readPreference); + // 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; +}; + +define.classMethod('listCollections', {callback: false, promise:false, returns: [CommandCursor]}); + +var evaluate = function(self, code, parameters, options, callback) { + var finalCode = code; + var finalParameters = []; + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // If not a code object translate to one + if(!(finalCode instanceof Code)) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if(parameters != null && Array.isArray(parameters) && 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 = new CoreReadPreference(ReadPreference.PRIMARY); + + // Execute the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result && result.ok == 1) return handleCallback(callback, null, result.retval); + if(result) return handleCallback(callback, MongoError.create({message: f("eval failed: %s", result.errmsg), driver:true}), null); + handleCallback(callback, err, result); + }); +} + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.eval = function(code, parameters, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + // Check if the callback is in fact a string + if(typeof callback == 'function') return evaluate(self, code, parameters, options, callback); + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + evaluate(self, code, parameters, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('eval', {callback: true, promise:true}); + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Add return new collection + options.new_collection = true; + + // Check if the callback is in fact a string + if(typeof callback == 'function') { + return this.collection(fromCollection).rename(toCollection, options, callback); + } + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.collection(fromCollection).rename(toCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('renameCollection', {callback: true, promise:true}); + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropCollection = function(name, callback) { + var self = this; + + // Command to execute + var cmd = {'drop':name} + + // Check if the callback is in fact a string + if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(err) return handleCallback(callback, err); + if(result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); + + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + // Execute command + self.command(cmd, self.s.options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + if(result.ok) return resolve(true); + resolve(false); + }); + }); +}; + +define.classMethod('dropCollection', {callback: true, promise:true}); + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropDatabase = function(callback) { + var self = this; + // Drop database command + var cmd = {'dropDatabase':1}; + + // Check if the callback is in fact a string + if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); + + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + // Execute command + self.command(cmd, self.s.options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + if(result.ok) return resolve(true); + resolve(false); + }); + }); +} + +define.classMethod('dropDatabase', {callback: true, promise:true}); + +/** + * The callback format for the collections method. + * @callback Db~collectionsResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection[]} collections An array of all the collections objects for the db instance. + */ +var collections = function(self, callback) { + // Let's get the collection names + self.listCollections().toArray(function(err, documents) { + if(err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(function(doc) { + return doc.name.indexOf('$') == -1; + }); + + // Return the collection objects + handleCallback(callback, null, documents.map(function(d) { + return new Collection(self, self.s.topology, self.s.databaseName, d.name.replace(self.s.databaseName + ".", ''), self.s.pkFactory, self.s.options); + })); + }); +} + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.collections = function(callback) { + var self = this; + + // Return the callback + if(typeof callback == 'function') return collections(self, callback); + // Return the promise + return new self.s.promiseLibrary(function(resolve, reject) { + collections(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('collections', {callback: true, promise:true}); + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Ensure valid readPreference + if(options.readPreference + && !(options.readPreference instanceof ReadPreference) + && typeof options.readPreference == 'object') { + var mode = options.readPreference.mode || options.readPreference.preference; + if (mode && typeof mode == 'string') { + options.readPreference = new ReadPreference(mode, readPreference.tags); + } + } + + // Return the callback + if(typeof callback == 'function') return self.s.topology.command('admin.$cmd', selector, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); + + // Return promise + return new self.s.promiseLibrary(function(resolve, reject) { + self.s.topology.command('admin.$cmd', selector, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + resolve(result.result); + }); + }); +}; + +define.classMethod('executeDbAdminCommand', {callback: true, promise:true}); + +/** + * Creates an index on the db and collection collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + // Shallow clone the options + options = shallowClone(options); + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + // If we have a callback fallback + if(typeof callback == 'function') return createIndex(self, name, fieldOrSpec, options, callback); + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndex(self, name, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var createIndex = function(self, name, fieldOrSpec, options, callback) { + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Ensure we have a callback + if(finalOptions.writeConcern && typeof callback != 'function') { + throw MongoError.create({message: "Cannot use a writeConcern without a provided callback", driver:true}); + } + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) { + if(err == null) return handleCallback(callback, err, result); + // Create command + var doc = createCreateIndexCommand(self, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + }); + }); +} + +define.classMethod('createIndex', {callback: true, promise:true}); + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // If we have a callback fallback + if(typeof callback == 'function') return ensureIndex(self, name, fieldOrSpec, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + ensureIndex(self, name, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var ensureIndex = function(self, name, fieldOrSpec, options, callback) { + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Create command + var selector = createCreateIndexCommand(self, name, fieldOrSpec, options); + var index_name = selector.name; + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // Default command options + var commandOptions = {}; + // Check if the index allready exists + self.indexInformation(name, finalOptions, function(err, indexInformation) { + if(err != null && err.code != 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if(indexInformation == null || !indexInformation[index_name]) { + self.createIndex(name, fieldOrSpec, options, callback); + } else { + if(typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +} + +define.classMethod('ensureIndex', {callback: true, promise:true}); + +Db.prototype.addChild = function(db) { + if(this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +} + +/** + * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are + * related in a parent-child relationship to the original instance so that events are correctly emitted on child + * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. + * You can control these behaviors with the options noListener and returnNonCachedInstance. + * + * @method + * @param {string} name The name of the database we want to use. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {Db} + */ +Db.prototype.db = function(dbName, options) { + options = options || {}; + // Copy the options and add out internal override of the not shared flag + for(var key in this.options) { + options[key] = this.options[key]; + } + + // Do we have the db in the cache already + if(this.s.dbCache[dbName] && options.returnNonCachedInstance !== true) { + return this.s.dbCache[dbName]; + } + + // Add current db as parentDb + if(options.noListener == null || options.noListener == false) { + options.parentDb = this; + } + + // Add promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Return the db object + var db = new Db(dbName, this.s.topology, options) + + // Add as child + if(options.noListener == null || options.noListener == false) { + this.addChild(db); + } + + // Add the db to the cache + this.s.dbCache[dbName] = db; + // Return the database + return db; +}; + +define.classMethod('db', {callback: false, promise:false, returns: [Db]}); + +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') { + 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 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 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 + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // 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; + } + + // Force write using primary + commandOptions.readPreference = CoreReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, !result.ok ? toError(result) : null + , result.ok ? [{user: username, pwd: ''}] : null); + }) +} + +var addUser = function(self, username, password, options, callback) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // Attempt to execute auth command + _executeAuthCreateUserCommand(self, username, password, options, function(err, r) { + // We need to perform the backward compatible insert operation + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var userPassword = md5.digest('hex'); + + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.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 handleCallback(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 handleCallback(callback, err, null); + // Add command keys + finalOptions.upsert = true; + + // We have a user, let's update the password or upsert if not + collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err, results, full) { + if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]); + if(err) return handleCallback(callback, err, null) + handleCallback(callback, null, [{user:username, pwd:userPassword}]); + }); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, r); + }); +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.addUser = function(username, password, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // If we have a callback fallback + if(typeof callback == 'function') return addUser(self, username, password, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + addUser(self, username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('addUser', {callback: true, promise:true}); + +var _executeAuthRemoveUserCommand = function(self, username, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // Get the error 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 + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // Force write using primary + commandOptions.readPreference = CoreReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000}); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }) +} + +var removeUser = function(self, username, options, callback) { + // Attempt to execute command + _executeAuthRemoveUserCommand(self, username, options, function(err, result) { + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.SYSTEM_USER_COLLECTION); + + // Locate the user + collection.findOne({user: username}, {}, function(err, user) { + if(user == null) return handleCallback(callback, err, false); + collection.remove({user: username}, finalOptions, function(err, result) { + handleCallback(callback, err, true); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, result); + }); +} + +define.classMethod('removeUser', {callback: true, promise:true}); + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.removeUser = function(username, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // If we have a callback fallback + if(typeof callback == 'function') return removeUser(self, username, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + removeUser(self, username, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var authenticate = function(self, username, password, options, callback) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + // the default db to authenticate against is 'self' + // if authententicate is called from a retry context, it may be another one, like admin + var authdb = options.authdb ? options.authdb : options.dbName; + authdb = options.authSource ? options.authSource : authdb; + authdb = authdb ? authdb : self.databaseName; + + // Callback + var _callback = function(err, result) { + if(self.listeners('authenticated').length > 0) { + self.emit('authenticated', err, result); + } + + // Return to caller + handleCallback(callback, err, result); + } + + // authMechanism + var authMechanism = options.authMechanism || ''; + authMechanism = authMechanism.toUpperCase(); + + // If classic auth delegate to auth command + if(authMechanism == 'MONGODB-CR') { + self.s.topology.auth('mongocr', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'PLAIN') { + self.s.topology.auth('plain', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'MONGODB-X509') { + self.s.topology.auth('x509', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'SCRAM-SHA-1') { + self.s.topology.auth('scram-sha-1', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'GSSAPI') { + if(process.platform == 'win32') { + self.s.topology.auth('sspi', authdb, username, password, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + self.s.topology.auth('gssapi', authdb, username, password, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } + } else if(authMechanism == 'DEFAULT') { + self.s.topology.auth('default', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + handleCallback(callback, MongoError.create({message: f("authentication mechanism %s not supported", options.authMechanism), driver:true})); + } +} + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.authenticate = function(username, password, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + // Shallow copy the options + options = shallowClone(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 handleCallback(callback, MongoError.create({message: "only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism", driver:true})); + } + + // If we have a callback fallback + if(typeof callback == 'function') return authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; + // Reject error + if(err) return callback(err, r); + callback(null, r); + }); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; + // Reject error + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('authenticate', {callback: true, promise:true}); + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {object} [options=null] Optional settings. + * @param {string} [options.dbName=null] Logout against different database than current. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.logout = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // logout command + var cmd = {'logout':1}; + + // Add onAll to login to ensure all connection are logged out + options.onAll = true; + + // We authenticated against a different db use that + if(this.s.authSource) options.dbName = this.s.authSource; + + // Execute the command + if(typeof callback == 'function') return this.command(cmd, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true) + }); + + // Return promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.command(cmd, options, function(err, result) { + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed')); + if(err) return reject(err); + resolve(true); + }); + }); +} + +define.classMethod('logout', {callback: true, promise:true}); + +// Figure out the read preference +var getReadPreference = function(options, db) { + if(options.readPreference) return options; + if(db.readPreference) options.readPreference = db.readPreference; + return options; +} + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.indexInformation = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // If we have a callback fallback + if(typeof callback == 'function') return indexInformation(self, name, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexInformation(self, name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var indexInformation = function(self, name, options, callback) { + // If we specified full information + var full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); + + // 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 + self.collection(name).listIndexes().toArray(function(err, indexes) { + if(err) return callback(toError(err)); + if(!Array.isArray(indexes)) return handleCallback(callback, null, []); + if(full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +define.classMethod('indexInformation', {callback: true, promise:true}); + +var createCreateIndexCommand = function(db, name, fieldOrSpec, options) { + var indexParameters = 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 + "." + name, '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; + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) { + // Build the index + var indexParameters = 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]; + } + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete indexes[0][removeKeys[i]]; + } + } + + // Create command + var cmd = {createIndexes: name, indexes: indexes}; + + // Apply write concern to command + cmd = writeConcern(cmd, self, options); + + // Build the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result.ok == 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +// Validate the database name +var validateDatabaseName = function(databaseName) { + if(typeof databaseName !== 'string') throw MongoError.create({message: "database name must be a string", driver:true}); + if(databaseName.length === 0) throw MongoError.create({message: "database name cannot be the empty string", driver:true}); + if(databaseName == '$external') return; + + var invalidChars = [" ", ".", "$", "/", "\\"]; + for(var i = 0; i < invalidChars.length; i++) { + if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true}); + } +} + +// Get write concern +var writeConcern = function(target, db, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w) opts.w = options.w; + if(options.wtimeout) opts.wtimeout = options.wtimeout; + if(options.j) opts.j = options.j; + if(options.fsync) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Add listeners to topology +var createListener = function(self, e, object) { + var listener = function(err) { + if(e != 'error') { + object.emit(e, err, self); + + // Emit on all associated db's if available + for(var i = 0; i < self.s.children.length; i++) { + self.s.children[i].emit(e, err, self.s.children[i]); + } + } + } + return listener; +} + +/** + * Db close event + * + * Emitted after a socket closed against a single server or mongos proxy. + * + * @event Db#close + * @type {MongoError} + */ + +/** + * Db authenticated event + * + * Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated. + * + * @event Db#authenticated + * @type {object} + */ + +/** + * Db reconnect event + * + * * Server: Emitted when the driver has reconnected and re-authenticated. + * * ReplicaSet: N/A + * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * Emitted after an error occurred against a single server or mongos proxy. + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * Emitted after a socket timeout occurred against a single server or mongos proxy. + * + * @event Db#timeout + * @type {MongoError} + */ + +/** + * Db parseError event + * + * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. + * + * @event Db#parseError + * @type {MongoError} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. + * + * * Server: Emitted when the driver has connected to the single server and has authenticated. + * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. + * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; +Db.SYSTEM_INDEX_COLLECTION = "system.indexes"; +Db.SYSTEM_PROFILE_COLLECTION = "system.profile"; +Db.SYSTEM_USER_COLLECTION = "system.users"; +Db.SYSTEM_COMMAND_COLLECTION = "$cmd"; +Db.SYSTEM_JS_COLLECTION = "system.js"; + +module.exports = Db; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js new file mode 100644 index 0000000..3c9d64b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js @@ -0,0 +1,310 @@ +var shallowClone = require('../utils').shallowClone; +var stream = require('stream'); +var util = require('util'); + +module.exports = GridFSBucketReadStream; + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * + * @class + * @param {Collection} chunks Handle for chunks collection + * @param {Collection} files Handle for files collection + * @param {Object} readPreference The read preference to use + * @param {Object} filter The query to use to find the file document + * @param {Object} [options=null] Optional settings. + * @param {Number} [options.sort=null] Optional sort for the file find query + * @param {Number} [options.skip=null] Optional skip for the file find query + * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before + * @fires GridFSBucketReadStream#error + * @fires GridFSBucketReadStream#file + * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. + */ + +function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { + var _this = this; + this.s = { + bytesRead: 0, + chunks: chunks, + cursor: null, + expected: 0, + files: files, + filter: filter, + init: false, + expectedEnd: 0, + file: null, + options: options, + readPreference: readPreference + }; + + stream.Readable.call(this); +} + +util.inherits(GridFSBucketReadStream, stream.Readable); + +/** + * An error occurred + * + * @event GridFSBucketReadStream#error + * @type {Error} + */ + +/** + * Fires when the stream loaded the file document corresponding to the + * provided id. + * + * @event GridFSBucketReadStream#file + * @type {object} + */ + +/** + * Reads from the cursor and pushes to the stream. + * @method + */ + +GridFSBucketReadStream.prototype._read = function() { + var _this = this; + waitForFile(_this, function() { + doRead(_this); + }); +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} start Offset in bytes to start reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.start = function(start) { + throwIfInitialized(this); + this.s.options.start = start; + return this; +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} end Offset in bytes to stop reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.end = function(end) { + throwIfInitialized(this); + this.s.options.end = end; + return this; +}; + +/** + * @ignore + */ + +function throwIfInitialized(self) { + if (self.s.init) { + throw new Error('You cannot change options after the stream has entered' + + 'flowing mode!'); + } +} + +/** + * @ignore + */ + +function doRead(_this) { + _this.s.cursor.next(function(error, doc) { + if (error) { + return __handleError(_this, error); + } + if (!doc) { + return _this.push(null); + } + + var bytesRemaining = _this.s.file.length - _this.s.bytesRead; + var expectedN = _this.s.expected++; + var expectedLength = Math.min(_this.s.file.chunkSize, + bytesRemaining); + if (doc.n > expectedN) { + var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + if (doc.n < expectedN) { + var errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + if (doc.data.length() !== expectedLength) { + if (bytesRemaining <= 0) { + var errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; + return __handleError(_this, new Error(errmsg)); + } + var errmsg = 'ChunkIsWrongSize: Got unexpected length: ' + + doc.data.length() + ', expected: ' + expectedLength; + return __handleError(_this, new Error(errmsg)); + } + + _this.s.bytesRead += doc.data.length(); + + if (doc.data.buffer.length === 0) { + return _this.push(null); + } + + var sliceStart = null; + var sliceEnd = null; + var buf = doc.data.buffer; + if (_this.s.bytesToSkip != null) { + sliceStart = _this.s.bytesToSkip; + _this.s.bytesToSkip = 0; + } + + if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) { + sliceEnd = _this.s.bytesToTrim; + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); + } + + _this.push(buf); + }); +}; + +/** + * @ignore + */ + +function init(self) { + var findOneOptions = {}; + if (self.s.readPreference) { + findOneOptions.readPreference = self.s.readPreference; + } + if (self.s.options && self.s.options.sort) { + findOneOptions.sort = self.s.options.sort; + } + if (self.s.options && self.s.options.skip) { + findOneOptions.skip = self.s.options.skip; + } + + self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { + if (error) { + return __handleError(self, error); + } + if (!doc) { + var identifier = self.s.filter._id ? + self.s.filter._id.toString() : self.s.filter.filename; + var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; + return __handleError(self, new Error(errmsg)); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + self.push(null); + return; + } + + self.s.cursor = self.s.chunks.find({ files_id: doc._id }).sort({ n: 1 }); + if (self.s.readPreference) { + self.s.cursor.setReadPreference(self.s.readPreference); + } + + self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + self.s.file = doc; + self.s.bytesToSkip = handleStartOption(self, doc, self.s.cursor, + self.s.options); + self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, + self.s.options); + self.emit('file', doc); + }); +} + +/** + * @ignore + */ + +function waitForFile(_this, callback) { + if (_this.s.file) { + return callback(); + } + + if (!_this.s.init) { + init(_this); + _this.s.init = true; + } + + _this.once('file', function() { + callback(); + }); +}; + +/** + * @ignore + */ + +function handleStartOption(stream, doc, cursor, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new Error('Stream start (' + options.start + ') must not be ' + + 'more than the length of the file (' + doc.length +')') + } + if (options.start < 0) { + throw new Error('Stream start (' + options.start + ') must not be ' + + 'negative'); + } + if (options.end != null && options.end < options.start) { + throw new Error('Stream start (' + options.start + ') must not be ' + + 'greater than stream end (' + options.end + ')'); + } + + cursor.skip(Math.floor(options.start / doc.chunkSize)); + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * + doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } +} + +/** + * @ignore + */ + +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new Error('Stream end (' + options.end + ') must not be ' + + 'more than the length of the file (' + doc.length +')') + } + if (options.start < 0) { + throw new Error('Stream end (' + options.end + ') must not be ' + + 'negative'); + } + + var start = options.start != null ? + Math.floor(options.start / doc.chunkSize) : + 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return (Math.ceil(options.end / doc.chunkSize) * doc.chunkSize) - + options.end; + } +} + +/** + * @ignore + */ + +function __handleError(_this, error) { + _this.emit('error', error); +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js new file mode 100644 index 0000000..8d330ed --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js @@ -0,0 +1,335 @@ +var Emitter = require('events').EventEmitter; +var GridFSBucketReadStream = require('./download'); +var GridFSBucketWriteStream = require('./upload'); +var shallowClone = require('../utils').shallowClone; +var toError = require('../utils').toError; +var util = require('util'); + +var DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +module.exports = GridFSBucket; + +/** + * Constructor for a streaming GridFS interface + * @class + * @param {Db} db A db handle + * @param {object} [options=null] Optional settings. + * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. + * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB + * @param {object} [options.writeConcern=null] Optional write concern to be passed to write operations, for instance `{ w: 1 }` + * @param {object} [options.readPreference=null] Optional read preference to be passed to read operations + * @fires GridFSBucketWriteStream#index + * @return {GridFSBucket} + */ + +function GridFSBucket(db, options) { + Emitter.apply(this); + this.setMaxListeners(0); + + if (options && typeof options === 'object') { + options = shallowClone(options); + var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); + for (var i = 0; i < keys.length; ++i) { + if (!options[keys[i]]) { + options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; + } + } + } else { + options = DEFAULT_GRIDFS_BUCKET_OPTIONS; + } + + this.s = { + db: db, + options: options, + _chunksCollection: db.collection(options.bucketName + '.chunks'), + _filesCollection: db.collection(options.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false, + promiseLibrary: db.s.promiseLibrary || + (typeof global.Promise == 'function' ? global.Promise : require('es6-promise').Promise) + }; +}; + +util.inherits(GridFSBucket, Emitter); + +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * + * @event GridFSBucket#index + * @type {Error} + */ + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options=null] Optional settings. + * @param {number} [options.chunkSizeBytes=null] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata=null] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType=null] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases=null] Optional array of strings to store in the file document's `aliases` field + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStream = function(filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming file + * data from GridFS. + * @method + * @param {ObjectId} id The id of the file doc + * @param {Object} [options=null] Optional settings. + * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStream = function(id, options) { + var filter = { _id: id }; + var options = { + start: options && options.start, + end: options && options.end + }; + return new GridFSBucketReadStream(this.s._chunksCollection, + this.s._filesCollection, this.s.options.readPreference, filter, options); +}; + +/** + * Deletes a file with the given id + * @method + * @param {ObjectId} id The id of the file doc + * @param {Function} callback + */ + +GridFSBucket.prototype.delete = function(id, callback) { + if (typeof callback === 'function') { + return _delete(this, id, callback); + } + + var _this = this; + return new this.s.promiseLibrary(function(resolve, reject) { + _delete(_this, id, function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * @ignore + */ + +function _delete(_this, id, callback) { + _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { + if (error) { + return callback(error); + } + + _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { + if (error) { + return callback(error); + } + + // Delete orphaned chunks before returning FileNotFound + if (!res.result.n) { + var errmsg = 'FileNotFound: no file with id ' + id + ' found'; + return callback(new Error(errmsg)); + } + + callback(); + }); + }); +} + +/** + * Convenience wrapper around find on the files collection + * @method + * @param {Object} filter + * @param {Object} [options=null] Optional settings for cursor + * @param {number} [options.batchSize=null] Optional batch size for cursor + * @param {number} [options.limit=null] Optional limit for cursor + * @param {number} [options.maxTimeMS=null] Optional maxTimeMS for cursor + * @param {boolean} [options.noCursorTimeout=null] Optionally set cursor's `noCursorTimeout` flag + * @param {number} [options.skip=null] Optional skip for cursor + * @param {object} [options.sort=null] Optional sort for cursor + * @return {Cursor} + */ + +GridFSBucket.prototype.find = function(filter, options) { + filter = filter || {}; + options = options || {}; + + var cursor = this.s._filesCollection.find(filter); + + if (options.batchSize != null) { + cursor.batchSize(options.batchSize); + } + if (options.limit != null) { + cursor.limit(options.limit); + } + if (options.maxTimeMS != null) { + cursor.maxTimeMS(options.maxTimeMS); + } + if (options.noCursorTimeout != null) { + cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); + } + if (options.skip != null) { + cursor.skip(options.skip); + } + if (options.sort != null) { + cursor.sort(options.sort); + } + + return cursor; +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadedDate` field). You can set the `revision` + * option to change this behavior. + * @method + * @param {String} filename The name of the file to stream + * @param {Object} [options=null] Optional settings + * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. + * @param {Number} [options.start=null] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end=null] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { + var sort = { uploadedDate: -1 }; + var skip = null; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadedDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + + var filter = { filename: filename }; + var options = { + sort: sort, + skip: skip, + start: options && options.start, + end: options && options.end + }; + return new GridFSBucketReadStream(this.s._chunksCollection, + this.s._filesCollection, this.s.options.readPreference, filter, options); +}; + +/** + * Renames the file with the given _id to the given string + * @method + * @param {ObjectId} id the id of the file to rename + * @param {String} filename new name for the file + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.rename = function(id, filename, callback) { + if (typeof callback === 'function') { + return _rename(this, id, filename, callback); + } + + var _this = this; + return new this.s.promiseLibrary(function(resolve, reject) { + _rename(_this, id, filename, function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * @ignore + */ + +function _rename(_this, id, filename, callback) { + var filter = { _id: id }; + var update = { $set: { filename: filename } }; + _this.s._filesCollection.updateOne(filter, update, function(error, res) { + if (error) { + return callback(error); + } + if (!res.result.n) { + return callback(toError('File with id ' + id + ' not found')); + } + callback(); + }); +} + +/** + * Removes this bucket's files collection, followed by its chunks collection. + * @method + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.drop = function(callback) { + if (typeof callback === 'function') { + return _drop(this, callback); + } + + var _this = this; + return new this.s.promiseLibrary(function(resolve, reject) { + _drop(_this, function(error, res) { + if (error) { + reject(error); + } else { + resolve(res); + } + }); + }); +}; + +/** + * @ignore + */ + +function _drop(_this, callback) { + _this.s._filesCollection.drop(function(error) { + if (error) { + return callback(error); + } + _this.s._chunksCollection.drop(function(error) { + if (error) { + return callback(error); + } + + return callback(); + }); + }); +} + +/** + * Callback format for all GridFSBucket methods that can accept a callback. + * @callback GridFSBucket~errorCallback + * @param {MongoError} error An error instance representing any errors that occurred + */ diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js new file mode 100644 index 0000000..5395c6a --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js @@ -0,0 +1,449 @@ +var core = require('mongodb-core'); +var crypto = require('crypto'); +var shallowClone = require('../utils').shallowClone; +var stream = require('stream'); +var util = require('util'); + +var ERROR_NAMESPACE_NOT_FOUND = 26; + +module.exports = GridFSBucketWriteStream; + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * + * @class + * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options=null] Optional settings. + * @param {number} [options.chunkSizeBytes=null] The chunk size to use, in bytes + * @param {number} [options.w=null] The write concern + * @param {number} [options.wtimeout=null] The write concern timeout + * @param {number} [options.j=null] The journal write concern + * @fires GridFSBucketWriteStream#error + * @fires GridFSBucketWriteStream#finish + * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. + */ + +function GridFSBucketWriteStream(bucket, filename, options) { + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + + this.id = core.BSON.ObjectId(); + this.chunkSizeBytes = this.options.chunkSizeBytes; + this.bufToStore = new Buffer(this.chunkSizeBytes); + this.length = 0; + this.md5 = crypto.createHash('md5'); + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + var _this = this; + checkIndexes(this, function() { + _this.bucket.s.checkedIndexes = true; + _this.bucket.emit('index'); + }); + } +} + +util.inherits(GridFSBucketWriteStream, stream.Writable); + +/** + * An error occurred + * + * @event GridFSBucketWriteStream#error + * @type {Error} + */ + +/** + * end() was called and the write stream successfully wrote all chunks to + * MongoDB. + * + * @event GridFSBucketWriteStream#finish + * @type {object} + */ + +/** + * Write a buffer to the stream. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. + */ + +GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { + var _this = this; + return waitForIndexes(this, function() { + return doWrite(_this, chunk, encoding, callback); + }); +}; + +/** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB + */ + +GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { + var _this = this; + this.state.streamEnd = true; + + if (callback) { + this.once('finish', callback); + } + + if (!chunk) { + waitForIndexes(this, function() { + writeRemnant(_this); + }); + return; + } + + var _this = this; + var inputBuf = (Buffer.isBuffer(chunk)) ? + chunk : new Buffer(chunk, encoding); + + this.write(chunk, encoding, function() { + writeRemnant(_this); + }); +}; + +/** + * @ignore + */ + +function __handleError(_this, error, callback) { + if (_this.state.errored) { + return; + } + _this.state.errored = true; + if (callback) { + return callback(error); + } + _this.emit('error', error); +} + +/** + * @ignore + */ + +function createChunkDoc(filesId, n, data) { + return { + _id: core.BSON.ObjectId(), + files_id: filesId, + n: n, + data: data + }; +} + +/** + * @ignore + */ + +function checkChunksIndex(_this, callback) { + _this.chunks.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { files_id: 1, n: 1 }; + _this.chunks.createIndex(index, { background: false }, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + return; + } + return callback(error); + } + + var hasChunksIndex = false; + indexes.forEach(function(index) { + if (index.key) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && + index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + + if (hasChunksIndex) { + callback(); + } else { + var index = { files_id: 1, n: 1 }; + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + indexOptions.unique = true; + + _this.chunks.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + } + }); +} + +/** + * @ignore + */ + +function checkDone(_this, callback) { + if (_this.state.streamEnd && + _this.state.outstandingRequests === 0 && + !_this.state.errored) { + var filesDoc = createFilesDoc(_this.id, _this.length, _this.chunkSizeBytes, + _this.md5.digest('hex'), _this.filename, _this.options.contentType, + _this.options.aliases, _this.options.metadata); + + _this.files.insert(filesDoc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error, callback); + } + _this.emit('finish', filesDoc); + }); + + return true; + } + + return false; +} + +/** + * @ignore + */ + +function checkIndexes(_this, callback) { + _this.files.findOne({}, { _id: 1 }, function(error, doc) { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + + _this.files.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { filename: 1, uploadDate: 1 }; + _this.files.createIndex(index, { background: false }, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + return; + } + return callback(error); + } + + var hasFileIndex = false; + indexes.forEach(function(index) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && + index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + + if (hasFileIndex) { + checkChunksIndex(_this, callback); + } else { + var index = { filename: 1, uploadDate: 1 }; + + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + + _this.files.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + } + }); + }); +} + +/** + * @ignore + */ + +function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, + aliases, metadata) { + var ret = { + _id: _id, + length: length, + chunkSize: chunkSize, + uploadDate: new Date(), + md5: md5, + filename: filename + }; + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +/** + * @ignore + */ + +function doWrite(_this, chunk, encoding, callback) { + var inputBuf = (Buffer.isBuffer(chunk)) ? + chunk : new Buffer(chunk, encoding); + + _this.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { + inputBuf.copy(_this.bufToStore, _this.pos); + _this.pos += inputBuf.length; + + callback && callback(); + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + var inputBufRemaining = inputBuf.length; + var spaceRemaining = _this.chunkSizeBytes - _this.pos; + var numToCopy = Math.min(spaceRemaining, inputBuf.length); + var outstandingRequests = 0; + while (inputBufRemaining > 0) { + var inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(_this.bufToStore, _this.pos, + inputBufPos, inputBufPos + numToCopy); + _this.pos += numToCopy; + spaceRemaining -= numToCopy; + if (spaceRemaining === 0) { + _this.md5.update(_this.bufToStore); + var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); + ++_this.state.outstandingRequests; + ++outstandingRequests; + + _this.chunks.insert(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + --outstandingRequests; + if (!outstandingRequests) { + _this.emit('drain', doc); + callback && callback(); + checkDone(_this); + } + }); + + spaceRemaining = _this.chunkSizeBytes; + _this.pos = 0; + ++_this.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} + +/** + * @ignore + */ + +function getWriteOptions(_this) { + var obj = {}; + if (_this.options.writeConcern) { + obj.w = concern.w; + obj.wtimeout = concern.wtimeout; + obj.j = concern.j; + } + return obj; +} + +/** + * @ignore + */ + +function waitForIndexes(_this, callback) { + if (_this.bucket.s.checkedIndexes) { + return callback(false); + } + + _this.bucket.once('index', function() { + callback(true); + }); + + return true; +} + +/** + * @ignore + */ + +function writeRemnant(_this, callback) { + // Buffer is empty, so don't bother to insert + if (_this.pos === 0) { + return checkDone(_this, callback); + } + + ++_this.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + var remnant = new Buffer(_this.pos); + _this.bufToStore.copy(remnant, 0, 0, _this.pos); + _this.md5.update(remnant); + var doc = createChunkDoc(_this.id, _this.n, remnant); + + _this.chunks.insert(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + checkDone(_this); + }); +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js new file mode 100644 index 0000000..cbd3ee8 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js @@ -0,0 +1,233 @@ +"use strict"; + +var Binary = require('mongodb-core').BSON.Binary, + ObjectID = require('mongodb-core').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 = 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, 0, mongoObjectFinal.data.length, 'binary'); + this.data = new Binary(buffer); + } else if(Array.isArray(mongoObjectFinal.data)) { + var buffer = new Buffer(mongoObjectFinal.data.length); + var data = mongoObjectFinal.data.join(''); + buffer.write(data, 0, data.length, 'binary'); + this.data = new Binary(buffer); + } else if(mongoObjectFinal.data._bsontype === '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, data.length, 'binary'); + 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 = { upsert: true }; + for(var name in options) writeOptions[name] = options[name]; + for(var name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + 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.replaceOne({'_id':self.objectId}, 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; + +module.exports = Chunk; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js new file mode 100644 index 0000000..93afa50 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js @@ -0,0 +1,1956 @@ +"use strict"; + +/** + * @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. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * GridStore = require('mongodb').GridStore, + * ObjectID = require('mongodb').ObjectID, + * test = require('assert'); + * + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * var gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * db.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +var Chunk = require('./chunk'), + ObjectID = require('mongodb-core').BSON.ObjectID, + ReadPreference = require('../read_preference'), + Buffer = require('buffer').Buffer, + Collection = require('../collection'), + fs = require('fs'), + timers = require('timers'), + f = require('util').format, + util = require('util'), + Define = require('../metadata'), + MongoError = require('mongodb-core').MongoError, + inherits = util.inherits, + Duplex = require('stream').Duplex || require('readable-stream').Duplex, + shallowClone = require('../utils').shallowClone; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +/** + * Namespace provided by the mongodb-core and node.js + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwriten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [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=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata=null] Arbitrary data the user wants to store. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + * @deprecated Use GridFSBucket API instead + */ +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; + + // 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 || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = this.options.readPreference || db.options.readPreference || 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']; + + // Get the promiseLibrary + var promiseLibrary = this.options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set the promiseLibrary + this.promiseLibrary = promiseLibrary; + + Object.defineProperty(this, "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; + } + } + }); + + Object.defineProperty(this, "md5", { enumerable: true + , get: function () { + return this.internalMd5; + } + }); + + Object.defineProperty(this, "chunkNumber", { enumerable: true + , get: function () { + return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null; + } + }); +} + +var define = GridStore.define = new Define('Gridstore', GridStore, true); + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {GridStore~openCallback} [callback] this will be called after executing this method + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.open = function(callback) { + var self = this; + if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ + throw MongoError.create({message: "Illegal mode " + this.mode, driver:true}); + } + + // We provided a callback leg + if(typeof callback == 'function') return open(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + open(self, function(err, store) { + if(err) return reject(err); + resolve(store); + }) + }); +}; + +var open = function(self, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(self.db, self.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) { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Make an unique index for compatibility with mongo-cxx-driver:legacy + var chunkIndexOptions = shallowClone(writeConcern); + chunkIndexOptions.unique = true; + // Ensure index on chunk collection + chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function(err, index) { + // Open the connection + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + }); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +} + +// Push the definition for open +define.classMethod('open', {callback: true, promise:true}); + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.eof = function() { + return this.position == this.length ? true : false; +} + +define.classMethod('eof', {callback: false, promise:false, returns: [Boolean]}); + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.getc = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return eof(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + eof(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var eof = function(self, callback) { + 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()); + } +} + +define.classMethod('getc', {callback: true, promise:true}); + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.puts = function(string, callback) { + var self = this; + var finalString = string.match(/\n$/) == null ? string + "\n" : string; + // We provided a callback leg + if(typeof callback == 'function') return this.write(finalString, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + self.write(finalString, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +define.classMethod('puts', {callback: true, promise:true}); + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +} + +define.classMethod('stream', {callback: false, promise:false, returns: [GridStoreStream]}); + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.write = function write(data, close, callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return _writeNormal(this, data, close, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + _writeNormal(self, data, close, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +define.classMethod('write', {callback: true, promise:true}); + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + * @deprecated Use GridFSBucket API instead + */ +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'); + } +} + +define.classMethod('destroy', {callback: false, promise:false}); + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.writeFile = function (file, callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return writeFile(self, file, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + writeFile(self, file, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var writeFile = function(self, file, callback) { + 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 process.nextTick(writeChunk); + } + }); + }); + }); + } + + // Process the first write + process.nextTick(writeChunk); + }); + }); +} + +define.classMethod('writeFile', {callback: true, promise:true}); + +/** + * 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+". + * + * @method + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.close = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return close(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + close(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var close = function(self, callback) { + 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) { + 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(MongoError.create({message: f("Illegal mode %s", self.mode), driver:true})); + } +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.chunkCollection = function(callback) { + if(typeof callback == 'function') + return this.db.collection((this.root + ".chunks"), callback); + return this.db.collection((this.root + ".chunks")); +}; + +define.classMethod('chunkCollection', {callback: true, promise:false, returns: [Collection]}); + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.unlink = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return unlink(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + unlink(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var unlink = function(self, callback) { + deleteChunks(self, 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); + }); + }); + }); +} + +define.classMethod('unlink', {callback: true, promise:true}); + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.collection = function(callback) { + if(typeof callback == 'function') + this.db.collection(this.root + ".files", callback); + return this.db.collection(this.root + ".files"); +}; + +define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.readlines = function(separator, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + separator = args.length ? args.shift() : "\n"; + separator = separator || "\n"; + + // We provided a callback leg + if(typeof callback == 'function') return readlines(self, separator, callback); + + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + readlines(self, separator, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readlines = function(self, separator, callback) { + self.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); + }); +} + +define.classMethod('readlines', {callback: true, promise:true}); + +/** + * 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. + * + * @method + * @param {GridStore~resultCallback} [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 {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.rewind = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return rewind(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + rewind(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var rewind = function(self, callback) { + if(self.currentChunk.chunkNumber != 0) { + if(self.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); + } +} + +define.classMethod('rewind', {callback: true, promise:true}); + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * 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) + * + * @method + * @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 {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.read = function(length, buffer, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + // We provided a callback leg + if(typeof callback == 'function') return read(self, length, buffer, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + read(self, length, buffer, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var read = function(self, length, buffer, callback) { + // 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(MongoError.create({message: "File does not exist", driver:true}), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + 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(MongoError.create({message: "no chunks found for file, possibly corrupt", driver:true}), null); + } + } + }); +} + +define.classMethod('read', {callback: true, promise:true}); + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @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 {GridStore~tellCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.tell = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return callback(null, this.position); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + resolve(self.position); + }); +}; + +define.classMethod('tell', {callback: true, promise:true}); + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * 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. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {GridStore~gridStoreCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.seek = function(position, seekLocation, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + seekLocation = args.length ? args.shift() : null; + + // We provided a callback leg + if(typeof callback == 'function') return seek(self, position, seekLocation, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + seek(self, position, seekLocation, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var seek = function(self, position, seekLocation, callback) { + // Seek only supports read mode + if(self.mode != 'r') { + return callback(MongoError.create({message: "seek is only supported for mode r", driver:true})) + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if(seekLocationFinal == GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if(seekLocationFinal == GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition/self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + if(err) return callback(err, null); + if(chunk == null) return callback(new Error('no chunk found')); + + // Set the current chunk + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = (self.position % self.chunkSize); + callback(err, self); + }); + }; + + seekChunk(); +} + +define.classMethod('seek', {callback: true, promise:true}); + +/** + * @ignore + */ +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 = 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(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename)), driver:true}), 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" && doc) { + // 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") { + 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 = 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); + } +}; + +/** + * @ignore + */ +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 != "w") { + callback(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? self.referenceBy : self.filename)), driver:true}), 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. + * + *

+ *        {
+ *          '_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 + */ +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); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +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 + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +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); + } +}; + +/** +* 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. + * + * @method + * @static + * @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 {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return exists(db, fileIdObject, rootCollection, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + exists(db, fileIdObject, rootCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var exists = function(db, fileIdObject, rootCollection, options, callback) { + // Establish read preference + var readPreference = options.readPreference || 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 + + // We have a specific query + if(fileIdObject != null + && typeof fileIdObject == 'object' + && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, {readPreference:readPreference}, function(err, item) { + if(err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +} + +define.staticMethod('exist', {callback: true, promise:true}); + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @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 {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return list(db, rootCollection, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + list(db, rootCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var list = function(db, rootCollection, options, callback) { + // Ensure we have correct values + if(rootCollection != null && typeof rootCollection == 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || 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); + } + }); + }); + }); +} + +define.staticMethod('list', {callback: true, promise:true}); + +/** + * 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) + * + * @method + * @static + * @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=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options ? options.promiseLibrary : null; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return readStatic(db, name, length, offset, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + readStatic(db, name, length, offset, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readStatic = function(db, name, length, offset, options, callback) { + 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); + } + }); +} + +define.staticMethod('read', {callback: true, promise:true}); + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options ? options.promiseLibrary : null; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return readlinesStatic(db, name, separator, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + readlinesStatic(db, name, separator, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readlinesStatic = function(db, name, separator, options, callback) { + 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); + }); +} + +define.staticMethod('readlines', {callback: true, promise:true}); + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options=null] Optional settings. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.unlink = function(db, names, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return unlinkStatic(self, db, names, options, callback); + + // Return promise + return new promiseLibrary(function(resolve, reject) { + unlinkStatic(self, db, names, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var unlinkStatic = function(self, db, names, options, callback) { + // 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); + }); + }); + }); + }); + } +} + +define.staticMethod('unlink', {callback: true, promise:true}); + +/** + * @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); + } +} + +/** + * @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 && (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 MongoError.create({message: "No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true", driver:true}); + + // Return the options + return finalOptions; +} + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStoreStream = function(gs) { + var self = this; + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +} + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if(!self.gs.isOpen) { + self.gs.open(function(err) { + if(err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } + + return destination; +} + +// Called by stream +GridStoreStream.prototype._read = function(n) { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if(err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if(self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if(buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if(buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if(self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + } + + // Set read length + var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if(!self.gs.isOpen) { + self.gs.open(function(err, gs) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if(err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +} + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +} + +GridStoreStream.prototype.write = function(chunk, encoding, callback) { + var self = this; + if(self.endCalled) return self.emit('error', MongoError.create({message: 'attempting to write to stream after end called', driver:true})) + // Do we have to open the gridstore + if(!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +} + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if(chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); + }); + } + + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); +} + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/metadata.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/metadata.js new file mode 100644 index 0000000..7dae562 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/metadata.js @@ -0,0 +1,64 @@ +var f = require('util').format; + +var Define = function(name, object, stream) { + this.name = name; + this.object = object; + this.stream = typeof stream == 'boolean' ? stream : false; + this.instrumentations = {}; +} + +Define.prototype.classMethod = function(name, options) { + var keys = Object.keys(options).sort(); + var key = generateKey(keys, options); + + // Add a list of instrumentations + if(this.instrumentations[key] == null) { + this.instrumentations[key] = { + methods: [], options: options + } + } + + // Push to list of method for this instrumentation + this.instrumentations[key].methods.push(name); +} + +var generateKey = function(keys, options) { + var parts = []; + for(var i = 0; i < keys.length; i++) { + parts.push(f('%s=%s', keys[i], options[keys[i]])); + } + + return parts.join(); +} + +Define.prototype.staticMethod = function(name, options) { + options.static = true; + var keys = Object.keys(options).sort(); + var key = generateKey(keys, options); + + // Add a list of instrumentations + if(this.instrumentations[key] == null) { + this.instrumentations[key] = { + methods: [], options: options + } + } + + // Push to list of method for this instrumentation + this.instrumentations[key].methods.push(name); +} + +Define.prototype.generate = function(keys, options) { + // Generate the return object + var object = { + name: this.name, obj: this.object, stream: this.stream, + instrumentations: [] + } + + for(var name in this.instrumentations) { + object.instrumentations.push(this.instrumentations[name]); + } + + return object; +} + +module.exports = Define; \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 0000000..aac1342 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,472 @@ +"use strict"; + +var parse = require('./url_parser') + , Server = require('./server') + , Mongos = require('./mongos') + , ReplSet = require('./replset') + , Define = require('./metadata') + , ReadPreference = require('./read_preference') + , Db = require('./db'); + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new MongoClient instance + * @class + * @return {MongoClient} a MongoClient instance. + */ +function MongoClient() { + /** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The connected database. + */ + + /** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ + this.connect = MongoClient.connect; +} + +var define = MongoClient.define = new Define('MongoClient', MongoClient, false); + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +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 || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Return a promise + if(typeof callback != 'function') { + return new promiseLibrary(function(resolve, reject) { + connect(url, options, function(err, db) { + if(err) return reject(err); + resolve(db); + }); + }); + } + + // Fallback to callback based connect + connect(url, options, callback); +} + +define.staticMethod('connect', {callback: true, promise:true}); + +var connect = function(url, options, callback) { + 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]; + } + + if(replSetServersOptions.ssl + || replSetServersOptions.sslValidate + || replSetServersOptions.checkServerIdentity + || replSetServersOptions.sslCA + || replSetServersOptions.sslCert + || replSetServersOptions.sslKey + || replSetServersOptions.sslPass) { + object.server_options.ssl = replSetServersOptions.ssl; + object.server_options.sslValidate = replSetServersOptions.sslValidate; + object.server_options.checkServerIdentity = replSetServersOptions.checkServerIdentity; + object.server_options.sslCA = replSetServersOptions.sslCA; + object.server_options.sslCert = replSetServersOptions.sslCert; + object.server_options.sslKey = replSetServersOptions.sslKey; + object.server_options.sslPass = replSetServersOptions.sslPass; + } + + // Merge in any replicaset server options + if(mongosOptions) { + for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; + } + + if(typeof object.server_options.poolSize == 'number') { + if(!object.mongos_options.poolSize) object.mongos_options.poolSize = object.server_options.poolSize; + if(!object.rs_options.poolSize) object.rs_options.poolSize = object.server_options.poolSize; + } + + if(mongosOptions.ssl + || mongosOptions.sslValidate + || mongosOptions.checkServerIdentity + || mongosOptions.sslCA + || mongosOptions.sslCert + || mongosOptions.sslKey + || mongosOptions.sslPass) { + object.server_options.ssl = mongosOptions.ssl; + object.server_options.sslValidate = mongosOptions.sslValidate; + object.server_options.checkServerIdentity = mongosOptions.checkServerIdentity; + object.server_options.sslCA = mongosOptions.sslCA; + object.server_options.sslCert = mongosOptions.sslCert; + object.server_options.sslKey = mongosOptions.sslKey; + object.server_options.sslPass = mongosOptions.sslPass; + } + + // Set the promise library + object.db_options.promiseLibrary = options.promiseLibrary; + + // 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; + } + + // 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 providedSocketOptions = object.server_options.socketOptions || {}; + + var _server_options = { + poolSize:1 + , socketOptions: { + connectTimeoutMS: providedSocketOptions.connectTimeoutMS || (1000 * 120) + , socketTimeoutMS: providedSocketOptions.socketTimeoutMS || (1000 * 120) + } + , auto_reconnect:false}; + + // Ensure we have ssl setup for the servers + if(object.server_options.ssl) { + _server_options.ssl = object.server_options.ssl; + _server_options.sslValidate = object.server_options.sslValidate; + _server_options.checkServerIdentity = object.server_options.checkServerIdentity; + _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; + } else if(object.rs_options.ssl) { + _server_options.ssl = object.rs_options.ssl; + _server_options.sslValidate = object.rs_options.sslValidate; + _server_options.checkServerIdentity = object.rs_options.checkServerIdentity; + _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; + } + + // Error + var error = null; + // 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, promiseLibrary:options.promiseLibrary}).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(); + // Get the last ismaster document + var isMasterDoc = db.serverConfig.isMasterDoc; + + // Check what type of server we have + if(isMasterDoc.setName) { + totalNumberOfMongodServers++; + } + + if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; + } else { + error = err; + errorServers[__server.host + ":" + __server.port] = __server; + } + + if(totalNumberOfServers == 0) { + // Error out + if(totalNumberOfMongodServers == 0 && totalNumberOfMongosServers == 0 && error) { + return callback(error, null); + } + + // If we have a mix of mongod and mongos, throw an error + if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { + if(db) db.close(); + return process.nextTick(function() { + try { + callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); + } catch (err) { + throw err + } + }) + } + + if(totalNumberOfMongodServers == 0 + && totalNumberOfMongosServers == 0 + && object.servers.length == 1 + && (!object.rs_options.replicaSet || !object.rs_options.rs_name)) { + + 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 + || object.rs_options.replicaSet || object.rs_options.rs_name) { + + var finalServers = object.servers + .filter(function(serverObj) { + return errorServers[serverObj.host + ":" + serverObj.port] == null; + }) + .map(function(serverObj) { + return serverObj.domain_socket ? + new Server(serverObj.domain_socket, 27017, object.server_options) + : new Server(serverObj.host, serverObj.port, object.server_options); + }); + + // Clean out any error servers + errorServers = {}; + + // Set up the final configuration + if(totalNumberOfMongodServers > 0) { + try { + + // If no replicaset name was provided, we wish to perform a + // direct connection + if(totalNumberOfMongodServers == 1 + && (!object.rs_options.replicaSet && !object.rs_options.rs_name)) { + serverConfig = finalServers[0]; + } else if(totalNumberOfMongodServers == 1) { + object.rs_options.replicaSet = object.rs_options.replicaSet || object.rs_options.rs_name; + serverConfig = new ReplSet(finalServers, object.rs_options); + } else { + serverConfig = new ReplSet(finalServers, object.rs_options); + } + + } catch(err) { + return callback(err, null); + } + } 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 of 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('mongodb-core').BSON.BSONNative.BSON; + return true; + } catch(err) { + return false; + } +} + +var _finishConnecting = function(serverConfig, object, options, callback) { + // If we have a readPreference passed in by the db options + if(typeof object.db_options.readPreference == 'string') { + object.db_options.readPreference = new ReadPreference(object.db_options.readPreference); + } else if(typeof object.db_options.read_preference == 'string') { + object.db_options.readPreference = new ReadPreference(object.db_options.read_preference); + } + + // Do we have readPreference tags + if(object.db_options.readPreference && object.db_options.readPreferenceTags) { + object.db_options.readPreference.tags = object.db_options.readPreferenceTags; + } else if(object.db_options.readPreference && object.db_options.read_preference_tags) { + object.db_options.readPreference.tags = object.db_options.read_preference_tags; + } + + // Get the socketTimeoutMS + var socketTimeoutMS = object.server_options.socketOptions.socketTimeoutMS || 0; + + // 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 the same as the connectTimeoutMS or 30 sec + serverConfig.connectTimeoutMS = serverConfig.connectTimeoutMS || 30000; + serverConfig.socketTimeoutMS = serverConfig.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 + } + }); + } + + // Reset the socket timeout + serverConfig.socketTimeoutMS = socketTimeoutMS || 0; + + // Return object + 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){ + 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 { + process.nextTick(function() { + try { + callback(err, db); + } catch (err) { + if(db) db.close(); + throw err + } + }) + } + }); +} + +module.exports = MongoClient diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/mongos.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/mongos.js new file mode 100644 index 0000000..c3b7c96 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/mongos.js @@ -0,0 +1,499 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , MongoCR = require('mongodb-core').MongoCR + , MongoError = require('mongodb-core').MongoError + , CMongos = require('mongodb-core').Mongos + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , Define = require('./metadata') + , Server = require('./server') + , Store = require('./topology_base').Store + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Mongos = require('mongodb').Mongos, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using Mongos + * var server = new Server('localhost', 27017); + * var db = new Db('test', new Mongos([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=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) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @return {Mongos} a Mongos instance. + */ +var Mongos = function(servers, options) { + if(!(this instanceof Mongos)) return new Mongos(servers, options); + options = options || {}; + var self = this; + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); + } + } + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Debug tag + var tag = options.tag; + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Final options + var finalOptions = shallowClone(options); + + // Default values + finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; + finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + finalOptions.cursorFactory = Cursor; + + // Add the store + finalOptions.disconnectHandler = store; + + // Ensure we change the sslCA option to ca if available + if(options.sslCA) finalOptions.ca = options.sslCA; + if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; + if(options.sslKey) finalOptions.key = options.sslKey; + if(options.sslCert) finalOptions.cert = options.sslCert; + if(options.sslPass) finalOptions.passphrase = options.sslPass; + if(options.checkServerIdentity) finalOptions.checkServerIdentity = options.checkServerIdentity; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + if(options.socketOptions.socketTimeoutMS) + finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + + // Are we running in debug mode + var debug = typeof options.debug == 'boolean' ? options.debug : false; + if(debug) { + finalOptions.debug = debug; + } + + // Map keep alive setting + if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAlive = true; + if(typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + } + } + + // Connection timeout + if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { + finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; + } + + // Socket timeout + if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { + finalOptions.socketTimeout = options.socketOptions.socketTimeout; + } + + // noDelay + if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { + finalOptions.noDelay = options.socketOptions.noDelay; + } + + if(typeof options.secondaryAcceptableLatencyMS == 'number') { + finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; + } + + // Add the non connection store + finalOptions.disconnectHandler = store; + + // Create the Mongos + var mongos = new CMongos(seedlist, finalOptions) + // Server capabilities + var sCapabilities = null; + // Add auth prbufferMaxEntriesoviders + mongos.addAuthProvider('mongocr', new MongoCR()); + + // Internal state + this.s = { + // Create the Mongos + mongos: mongos + // Server capabilities + , sCapabilities: sCapabilities + // Debug turned on + , debug: debug + // Store option defaults + , storeOptions: storeOptions + // Cloned options + , clonedOptions: finalOptions + // Actual store of callbacks + , store: store + // Options + , options: options + } + + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { return self.s.mongos.lastIsMaster(); } + }); + + // Last ismaster + Object.defineProperty(this, 'numberOfConnectedServers', { + enumerable:true, get: function() { + return self.s.mongos.s.mongosState.connectedServers().length; + } + }); + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return self.s.mongos.bson; + } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.mongos.haInterval; } + }); +} + +/** + * @ignore + */ +inherits(Mongos, EventEmitter); + +var define = Mongos.define = new Define('Mongos', Mongos, false); + +// Connect +Mongos.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.mongos.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function(err) { + self.emit('reconnect'); + self.s.store.execute(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.mongos.removeAllListeners(e); + }); + + // Set up listeners + self.s.mongos.once('timeout', errorHandler('timeout')); + self.s.mongos.once('error', errorHandler('error')); + self.s.mongos.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Set up serverConfig listeners + self.s.mongos.on('joined', relay('joined')); + self.s.mongos.on('left', relay('left')); + self.s.mongos.on('fullsetup', relay('fullsetup')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + self.s.mongos.once('timeout', connectErrorHandler('timeout')); + self.s.mongos.once('error', connectErrorHandler('error')); + self.s.mongos.once('close', connectErrorHandler('close')); + self.s.mongos.once('connect', connectHandler); + // Reconnect server + self.s.mongos.on('reconnect', reconnectHandler); + + // Start connection + self.s.mongos.connect(_options); +} + +Mongos.prototype.parserType = function() { + return this.s.mongos.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Server capabilities +Mongos.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.mongos.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.mongos.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +Mongos.prototype.command = function(ns, cmd, options, callback) { + this.s.mongos.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +Mongos.prototype.insert = function(ns, ops, options, callback) { + this.s.mongos.insert(ns, ops, options, function(e, m) { + callback(e, m) + }); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +Mongos.prototype.update = function(ns, ops, options, callback) { + this.s.mongos.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +Mongos.prototype.remove = function(ns, ops, options, callback) { + this.s.mongos.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// Destroyed +Mongos.prototype.isDestroyed = function() { + return this.s.mongos.isDestroyed(); +} + +// IsConnected +Mongos.prototype.isConnected = function() { + return this.s.mongos.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +Mongos.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.mongos.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +Mongos.prototype.setBSONParserType = function(type) { + return this.s.mongos.setBSONParserType(type); +} + +Mongos.prototype.lastIsMaster = function() { + return this.s.mongos.lastIsMaster(); +} + +Mongos.prototype.close = function(forceClosed) { + this.s.mongos.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +define.classMethod('close', {callback: false, promise:false}); + +Mongos.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.mongos.auth.apply(this.s.mongos, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +Mongos.prototype.connections = function() { + return this.s.mongos.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +module.exports = Mongos; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/read_preference.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/read_preference.js new file mode 100644 index 0000000..73b253a --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/read_preference.js @@ -0,0 +1,104 @@ +"use strict"; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * ReadPreference = require('mongodb').ReadPreference, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * test.equal(null, err); + * // Perform a read + * var cursor = db.collection('t').find({}); + * cursor.setReadPreference(ReadPreference.PRIMARY); + * cursor.toArray(function(err, docs) { + * test.equal(null, err); + * db.close(); + * }); + * }); + */ + +/** + * Creates a new ReadPreference instance + * + * 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 + * @param {string} mode The ReadPreference mode as listed above. + * @param {object} tags An object representing read preference tags. + * @property {string} mode The ReadPreference mode. + * @property {object} tags The ReadPreference tags. + * @return {ReadPreference} a ReadPreference instance. + */ +var ReadPreference = function(mode, tags) { + if(!(this instanceof ReadPreference)) + return new ReadPreference(mode, tags); + this._type = 'ReadPreference'; + this.mode = mode; + this.tags = tags; +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +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); +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +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 + */ +module.exports = ReadPreference; \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/replset.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/replset.js new file mode 100644 index 0000000..bc04047 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/replset.js @@ -0,0 +1,560 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , Server = require('./server') + , Mongos = require('./mongos') + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , ReadPreference = require('./read_preference') + , MongoCR = require('mongodb-core').MongoCR + , MongoError = require('mongodb-core').MongoError + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , Define = require('./metadata') + , CServer = require('mongodb-core').Server + , CReplSet = require('mongodb-core').ReplSet + , CoreReadPreference = require('mongodb-core').ReadPreference + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {string} options.replicaSet The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=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) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=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) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @return {ReplSet} a ReplSet instance. + */ +var ReplSet = function(servers, options) { + if(!(this instanceof ReplSet)) return new ReplSet(servers, options); + options = options || {}; + var self = this; + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); + } + } + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Debug tag + var tag = options.tag; + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Final options + var finalOptions = shallowClone(options); + + // Default values + finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; + finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + finalOptions.cursorFactory = Cursor; + + // Add the store + finalOptions.disconnectHandler = store; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + + if(options.socketOptions.socketTimeoutMS) { + finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + } + + // Get the name + var replicaSet = options.replicaSet || options.rs_name; + + // Set up options + finalOptions.setName = replicaSet; + + // Are we running in debug mode + var debug = typeof options.debug == 'boolean' ? options.debug : false; + if(debug) { + finalOptions.debug = debug; + } + + // Map keep alive setting + if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAlive = true; + if(typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + } + } + + // Connection timeout + if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { + finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; + } + + // Socket timeout + if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { + finalOptions.socketTimeout = options.socketOptions.socketTimeout; + } + + // noDelay + if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { + finalOptions.noDelay = options.socketOptions.noDelay; + } + + if(typeof options.secondaryAcceptableLatencyMS == 'number') { + finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; + } + + if(options.connectWithNoPrimary == true) { + finalOptions.secondaryOnlyConnectionAllowed = true; + } + + // Add the non connection store + finalOptions.disconnectHandler = store; + + // Translate the options + if(options.sslCA) finalOptions.ca = options.sslCA; + if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; + if(options.sslKey) finalOptions.key = options.sslKey; + if(options.sslCert) finalOptions.cert = options.sslCert; + if(options.sslPass) finalOptions.passphrase = options.sslPass; + if(options.checkServerIdentity) finalOptions.checkServerIdentity = options.checkServerIdentity; + + // Create the ReplSet + var replset = new CReplSet(seedlist, finalOptions) + // Server capabilities + var sCapabilities = null; + + // Listen to reconnect event + replset.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + replset: replset + // Server capabilities + , sCapabilities: null + // Debug tag + , tag: options.tag + // Store options + , storeOptions: storeOptions + // Cloned options + , clonedOptions: finalOptions + // Store + , store: store + // Options + , options: options + } + + // Debug + if(debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable:true, get: function() { return replset; } + }); + } + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { return replset.lastIsMaster(); } + }); + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return replset.bson; + } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return replset.haInterval; } + }); +} + +/** + * @ignore + */ +inherits(ReplSet, EventEmitter); + +var define = ReplSet.define = new Define('ReplSet', ReplSet, false); + +// Ensure the right read Preference object +var translateReadPreference = function(options) { + if(typeof options.readPreference == 'string') { + options.readPreference = new CoreReadPreference(options.readPreference); + } else if(options.readPreference instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(options.readPreference.mode + , options.readPreference.tags); + } + + return options; +} + +ReplSet.prototype.parserType = function() { + return this.s.replset.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Connect method +ReplSet.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.replset.removeAllListeners(e); + }); + + // Set up listeners + self.s.replset.once('timeout', errorHandler('timeout')); + self.s.replset.once('error', errorHandler('error')); + self.s.replset.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + } + } + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if(t == 'start') { + self.emit('ha_connect', t, state); + } else if(t == 'end') { + self.emit('ha_ismaster', t, state); + } + } + + // Set up serverConfig listeners + self.s.replset.on('joined', replsetRelay('joined')); + self.s.replset.on('left', relay('left')); + self.s.replset.on('ping', relay('ping')); + self.s.replset.on('ha', relayHa); + + self.s.replset.on('fullsetup', function(topology) { + self.emit('fullsetup', null, self); + }); + + self.s.replset.on('all', function(topology) { + self.emit('all', null, self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.replset.removeListener(e, connectErrorHandler); + }); + + self.s.replset.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.replset.destroy(); + + // Try to callback + try { + callback(err); + } catch(err) { + if(!self.s.replset.isConnected()) + process.nextTick(function() { throw err; }) + } + } + } + + // Set up listeners + self.s.replset.once('timeout', connectErrorHandler('timeout')); + self.s.replset.once('error', connectErrorHandler('error')); + self.s.replset.once('close', connectErrorHandler('close')); + self.s.replset.once('connect', connectHandler); + + // Start connection + self.s.replset.connect(_options); +} + +// Server capabilities +ReplSet.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.replset.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.replset.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +ReplSet.prototype.command = function(ns, cmd, options, callback) { + options = translateReadPreference(options); + this.s.replset.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +ReplSet.prototype.insert = function(ns, ops, options, callback) { + this.s.replset.insert(ns, ops, options, callback); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +ReplSet.prototype.update = function(ns, ops, options, callback) { + this.s.replset.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +ReplSet.prototype.remove = function(ns, ops, options, callback) { + this.s.replset.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// Destroyed +ReplSet.prototype.isDestroyed = function() { + return this.s.replset.isDestroyed(); +} + +// IsConnected +ReplSet.prototype.isConnected = function() { + return this.s.replset.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +ReplSet.prototype.setBSONParserType = function(type) { + return this.s.replset.setBSONParserType(type); +} + +// Insert +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = translateReadPreference(options); + options.disconnectHandler = this.s.store; + return this.s.replset.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +ReplSet.prototype.lastIsMaster = function() { + return this.s.replset.lastIsMaster(); +} + +ReplSet.prototype.close = function(forceClosed) { + var self = this; + this.s.replset.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); +} + +define.classMethod('close', {callback: false, promise:false}); + +ReplSet.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.replset.auth.apply(this.s.replset, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +ReplSet.prototype.connections = function() { + return this.s.replset.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +module.exports = ReplSet; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/server.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/server.js new file mode 100644 index 0000000..76a708d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/server.js @@ -0,0 +1,442 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , CServer = require('mongodb-core').Server + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , Define = require('./metadata') + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using single Server + * var db = new Db('test', new Server('localhost', 27017);); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options=null] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=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) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=false] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @return {Server} a Server instance. + */ +var Server = function(host, port, options) { + options = options || {}; + if(!(this instanceof Server)) return new Server(host, port, options); + EventEmitter.call(this); + var self = this; + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if(host.indexOf('\/') != -1) { + if(port != null && typeof port == 'object') { + options = port; + port = null; + } + } else if(port == null) { + throw MongoError.create({message: 'port must be specified', driver:true}); + } + + // Clone options + var clonedOptions = shallowClone(options); + clonedOptions.host = host; + clonedOptions.port = port; + + // Reconnect + var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; + var emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + var poolSize = typeof options.poolSize == 'number' ? options.poolSize : 5; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + clonedOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + + if(options.socketOptions.socketTimeoutMS) { + clonedOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + + if(typeof options.socketOptions.keepAlive == 'number') { + clonedOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + clonedOptions.keepAlive = true; + } + + if(typeof options.socketOptions.noDelay == 'boolean') { + clonedOptions.noDelay = options.socketOptions.noDelay; + } + } + + // Add the cursor factory function + clonedOptions.cursorFactory = Cursor; + clonedOptions.reconnect = reconnect; + clonedOptions.emitError = emitError; + clonedOptions.size = poolSize; + + // Translate the options + if(clonedOptions.sslCA) clonedOptions.ca = clonedOptions.sslCA; + if(typeof clonedOptions.sslValidate == 'boolean') clonedOptions.rejectUnauthorized = clonedOptions.sslValidate; + if(clonedOptions.sslKey) clonedOptions.key = clonedOptions.sslKey; + if(clonedOptions.sslCert) clonedOptions.cert = clonedOptions.sslCert; + if(clonedOptions.sslPass) clonedOptions.passphrase = clonedOptions.sslPass; + + // Add the non connection store + clonedOptions.disconnectHandler = store; + + // Create an instance of a server instance from mongodb-core + var server = new CServer(clonedOptions); + // Server capabilities + var sCapabilities = null; + + // Define the internal properties + this.s = { + // Create an instance of a server instance from mongodb-core + server: server + // Server capabilities + , sCapabilities: null + // Cloned options + , clonedOptions: clonedOptions + // Reconnect + , reconnect: reconnect + // Emit error + , emitError: emitError + // Pool size + , poolSize: poolSize + // Store Options + , storeOptions: storeOptions + // Store + , store: store + // Host + , host: host + // Port + , port: port + // Options + , options: options + } + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return self.s.server.bson; + } + }); + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { + return self.s.server.lastIsMaster(); + } + }); + + // Last ismaster + Object.defineProperty(this, 'poolSize', { + enumerable:true, get: function() { return self.s.server.connections().length; } + }); + + Object.defineProperty(this, 'autoReconnect', { + enumerable:true, get: function() { return self.s.reconnect; } + }); + + Object.defineProperty(this, 'host', { + enumerable:true, get: function() { return self.s.host; } + }); + + Object.defineProperty(this, 'port', { + enumerable:true, get: function() { return self.s.port; } + }); +} + +inherits(Server, EventEmitter); + +var define = Server.define = new Define('Server', Server, false); + +Server.prototype.parserType = function() { + return this.s.server.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Connect +Server.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.server.removeListener(e, connectHandlers[e]); + }); + + self.s.server.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function(err) { + self.emit('reconnect', self); + self.s.store.execute(); + } + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.server.removeAllListeners(e); + }); + + // Set up listeners + self.s.server.once('timeout', errorHandler('timeout')); + self.s.server.once('error', errorHandler('error')); + self.s.server.on('close', errorHandler('close')); + // Only called on destroy + self.s.server.once('destroy', destroyHandler); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + console.log(err.stack) + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Add the event handlers + self.s.server.once('timeout', connectHandlers.timeout); + self.s.server.once('error', connectHandlers.error); + self.s.server.once('close', connectHandlers.close); + self.s.server.once('connect', connectHandler); + // Reconnect server + self.s.server.on('reconnect', reconnectHandler); + + // Start connection + self.s.server.connect(_options); +} + +// Server capabilities +Server.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.server.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +Server.prototype.command = function(ns, cmd, options, callback) { + this.s.server.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +Server.prototype.insert = function(ns, ops, options, callback) { + this.s.server.insert(ns, ops, options, callback); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +Server.prototype.update = function(ns, ops, options, callback) { + this.s.server.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +Server.prototype.remove = function(ns, ops, options, callback) { + this.s.server.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// IsConnected +Server.prototype.isConnected = function() { + return this.s.server.isConnected(); +} + +Server.prototype.isDestroyed = function() { + return this.s.server.isDestroyed(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +Server.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.server.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +Server.prototype.setBSONParserType = function(type) { + return this.s.server.setBSONParserType(type); +} + +Server.prototype.lastIsMaster = function() { + return this.s.server.lastIsMaster(); +} + +Server.prototype.close = function(forceClosed) { + this.s.server.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +define.classMethod('close', {callback: false, promise:false}); + +Server.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.server.auth.apply(this.s.server, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +Server.prototype.connections = function() { + return this.s.server.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +module.exports = Server; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/topology_base.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/topology_base.js new file mode 100644 index 0000000..000f7ec --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/topology_base.js @@ -0,0 +1,152 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError + , f = require('util').format; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || {force:false, bufferMaxEntries: -1} + + // Internal state + this.s = { + storedOps: storedOps + , storeOptions: storeOptions + , topology: topology + } + + Object.defineProperty(this, 'length', { + enumerable:true, get: function() { return self.s.storedOps.length; } + }); +} + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if(this.s.storeOptions.force) { + return callback(MongoError.create({message: "db closed by application", driver:true})); + } + + if(this.s.storeOptions.bufferMaxEntries == 0) { + return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + return; + } + + this.s.storedOps.push({t: opType, n: ns, o: ops, op: options, c: callback}) +} + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if(this.s.storeOptions.force) { + return callback(MongoError.create({message: "db closed by application", driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries == 0) { + return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + return; + } + + this.s.storedOps.push({t: opType, m: method, o: object, p: params, c: callback}) +} + +Store.prototype.flush = function() { + while(this.s.storedOps.length > 0) { + this.s.storedOps.shift().c(MongoError.create({message: f("no connection available for operation"), driver:true })); + } +} + +Store.prototype.execute = function() { + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Execute all the stored ops + while(ops.length > 0) { + var op = ops.shift(); + + if(op.t == 'cursor') { + op.o[op.m].apply(op.o, op.p); + } else { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } +} + +Store.prototype.all = function() { + return this.s.storedOps; +} + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true + , get: function () { return value; } + }); + } + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + + if(ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if(ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if(ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if(ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + // If no min or max wire version set to 0 + if(ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if(ismaster.maxWireVersion == null) { + ismaster.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", ismaster.minWireVersion); + setup_get_property(this, "maxWireVersion", ismaster.maxWireVersion); + setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); +} + +exports.Store = Store; +exports.ServerCapabilities = ServerCapabilities; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js new file mode 100644 index 0000000..a86bd5f --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js @@ -0,0 +1,393 @@ +"use strict"; + +var ReadPreference = require('./read_preference'), + parser = require('url'), + f = require('util').format; + +module.exports = 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'; + + // Url parser result + var result = parser.parse(url, true); + + if(result.protocol != 'mongodb:') { + throw new Error('invalid schema, expected mongodb'); + } + + if((result.hostname == null || result.hostname == '') && url.indexOf('.sock') == -1) { + throw new Error('no hostname or hostnames provided in connection string'); + } + + if(result.port == '0') { + throw new Error('invalid port (zero) with hostname'); + } + + if(!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { + throw new Error('invalid port (larger than 65535) with hostname'); + } + + if(result.path + && result.path.length > 0 + && result.path[0] != '/' + && url.indexOf('.sock') == -1) { + throw new Error('missing delimiting slash between hosts and options'); + } + + if(result.query) { + for(var name in result.query) { + if(name.indexOf(':') != -1) { + throw new Error('double colon in host identifier'); + } + + if(result.query[name] == '') { + throw new Error('query parameter ' + name + ' is an incomplete value pair'); + } + } + } + + if(result.auth) { + var parts = result.auth.split(':'); + if(url.indexOf(result.auth) != -1 && parts.length > 2) { + throw new Error('Username with password containing an unescaped colon'); + } + + if(url.indexOf(result.auth) != -1 && result.auth.indexOf('@') != -1) { + throw new Error('Username containing an unescaped at-sign'); + } + } + + // Remove query + var clean = url.split('?').shift(); + + // Extract the list of hosts + var strings = clean.split(','); + var hosts = []; + + for(var i = 0; i < strings.length; i++) { + var hostString = strings[i]; + + if(hostString.indexOf('mongodb') != -1) { + if(hostString.indexOf('@') != -1) { + hosts.push(hostString.split('@').pop()) + } else { + hosts.push(hostString.substr('mongodb://'.length)); + } + } else if(hostString.indexOf('/') != -1) { + hosts.push(hostString.split('/').shift()); + } else if(hostString.indexOf('/') == -1) { + hosts.push(hostString.trim()); + } + } + + for(var i = 0; i < hosts.length; i++) { + var r = parser.parse(f('mongodb://%s', hosts[i].trim())); + if(r.path && r.path.indexOf(':') != -1) { + throw new Error('double colon in host identifier'); + } + } + + // 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]; + // Check if multiple database names provided, or just an illegal trailing backslash + if (dbName.indexOf("/") != -1) { + if (dbName.split("/").length == 2 && dbName.split("/")[1].length == 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); + } + } else if(connection_part.indexOf("/") != -1) { + // Check if multiple database names provided, or just an illegal trailing backslash + if (connection_part.split("/").length > 2) { + if (connection_part.split("/")[2].length == 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + 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); + + // Decode the URI components + 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; + // Deduplicate servers + var deduplicatedServers = {}; + + // 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]; + } + + // No entry returned for duplicate servr + if(deduplicatedServers[_host + "_" + _port]) return null; + deduplicatedServers[_host + "_" + _port] = 1; + + // Return the mapped object + return {host: _host, port: _port}; + }).filter(function(x) { + return x != null; + }); + } + + // 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 'sslValidate': + serverOptions.sslValidate = (value == 'true'); + replSetServerOptions.sslValidate = (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.j = (value == 'true'); + break; + case 'safe': + dbOptions.safe = (value == 'true'); + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = (value == 'true'); + break; + case 'readConcernLevel': + dbOptions.readConcern = {level: value}; + 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 != 'MONGODB-CR' + && value != 'DEFAULT' + && value != 'SCRAM-SHA-1' + && value != 'PLAIN') + throw new Error("only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + // Split up into key, value pairs + var values = value.split(','); + var o = {}; + // For each value split into key, value + values.forEach(function(x) { + var v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if(typeof o.SERVICE_NAME == 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + 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.readPreference = 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.readPreference) { + dbOptions.readPreference = 'primary'; + } + + // Add servers to result + object.servers = servers; + // Returned parsed object + return object; +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/lib/utils.js b/5-3/node_modules/mongoose/node_modules/mongodb/lib/utils.js new file mode 100644 index 0000000..cb20e67 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/lib/utils.js @@ -0,0 +1,234 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError, + f = require('util').format; + +var shallowClone = function(obj) { + var copy = {}; + for(var name in obj) copy[name] = obj[name]; + return copy; +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +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; +}; + +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"); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if(callback == null) return; + if(value2) return callback(err, value1, value2); + return callback(err, value1); + } catch(err) { + process.nextTick(function() { throw err; }); + return false; + } + + return true; +} + +/** + * 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; + var e = MongoError.create({message: msg, driver:true}); + + // 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; +} + +/** + * @ignore + */ +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; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var 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 + } +} + +var isObject = exports.isObject = function (arg) { + return '[object Object]' == toString.call(arg) +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +var decorateCommand = function(command, options, exclude) { + for(var name in options) { + if(exclude[name] == null) command[name] = options[name]; + } + + return command; +} + +exports.shallowClone = shallowClone; +exports.getSingleProperty = getSingleProperty; +exports.checkCollectionName = checkCollectionName; +exports.toError = toError; +exports.formattedOrderClause = formattedOrderClause; +exports.parseIndexOptions = parseIndexOptions; +exports.normalizeHintField = normalizeHintField; +exports.handleCallback = handleCallback; +exports.decorateCommand = decorateCommand; +exports.isObject = isObject; +exports.debugOptions = debugOptions; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md new file mode 100644 index 0000000..fbe4053 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md @@ -0,0 +1,29 @@ +# Master + +# 3.0.2 + +* correctly bump both bower and package.json versions + +# 3.0.1 + +* no longer include dist/test in npm releases + +# 3.0.0 + +* use nextTick() instead of setImmediate() to schedule microtasks with node 0.10. Later versions of + nodes are not affected as they were already using nextTick(). Note that using nextTick() might + trigger a depreciation warning on 0.10 as described at https://github.com/cujojs/when/issues/410. + The reason why nextTick() is preferred is that is setImmediate() would schedule a macrotask + instead of a microtask and might result in a different scheduling. + If needed you can revert to the former behavior as follow: + + var Promise = require('es6-promise').Promise; + Promise._setScheduler(setImmediate); + +# 2.0.0 + +* re-sync with RSVP. Many large performance improvements and bugfixes. + +# 1.0.0 + +* first subset of RSVP diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/LICENSE b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/LICENSE new file mode 100644 index 0000000..954ec59 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/README.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/README.md new file mode 100644 index 0000000..d952fa7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/README.md @@ -0,0 +1,61 @@ +# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) + +This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js), if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js). + +For API details and how to use promises, see the JavaScript Promises HTML5Rocks article. + +## Downloads + +* [es6-promise](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise.js) +* [es6-promise-min](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise.min.js) + +## Node.js + +To install: + +```sh +npm install es6-promise +``` + +To use: + +```js +var Promise = require('es6-promise').Promise; +``` + +## Usage in IE<9 + +`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example. + +However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production: + +```js +promise['catch'](function(err) { + // ... +}); +``` + +Or use `.then` instead: + +```js +promise.then(undefined, function(err) { + // ... +}); +``` + +## Auto-polyfill + +To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet: + +```js +require('es6-promise').polyfill(); +``` + +Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called. + +## Building & Testing + +* `npm run build` to build +* `npm test` to run tests +* `npm start` to run a build watcher, and webserver to test +* `npm run test:server` for a testem test runner and watching builder diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js new file mode 100644 index 0000000..88144c9 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js @@ -0,0 +1,967 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.0.2 + */ + +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$toString = {}.toString; + var lib$es6$promise$asap$$vertxNext; + var lib$es6$promise$asap$$customSchedulerFn; + + var lib$es6$promise$asap$$asap = function asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (lib$es6$promise$asap$$customSchedulerFn) { + lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); + } else { + lib$es6$promise$asap$$scheduleFlush(); + } + } + } + + function lib$es6$promise$asap$$setScheduler(scheduleFn) { + lib$es6$promise$asap$$customSchedulerFn = scheduleFn; + } + + function lib$es6$promise$asap$$setAsap(asapFn) { + lib$es6$promise$asap$$asap = asapFn; + } + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + process.nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$asap(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + var then = lib$es6$promise$$internal$$getThen(maybeThenable); + + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + } + } else { + lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); + } + } + + lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { + return lib$es6$promise$utils$$isArray(input); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { + this._result = new Array(this.length); + }; + + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (lib$es6$promise$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + enumerator._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, enumerator._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + var lib$es6$promise$promise$$counter = 0; + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + if (!lib$es6$promise$utils$$isFunction(resolver)) { + lib$es6$promise$promise$$needsResolver(); + } + + if (!(this instanceof lib$es6$promise$promise$$Promise)) { + lib$es6$promise$promise$$needsNew(); + } + + lib$es6$promise$$internal$$initializePromise(this, resolver); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; + lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; + lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$asap(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js new file mode 100644 index 0000000..2d48351 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js @@ -0,0 +1,9 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.0.2 + */ + +(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;var lib$es6$promise$asap$$customSchedulerFn;var lib$es6$promise$asap$$asap=function asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){if(lib$es6$promise$asap$$customSchedulerFn){lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush)}else{lib$es6$promise$asap$$scheduleFlush()}}};function lib$es6$promise$asap$$setScheduler(scheduleFn){lib$es6$promise$asap$$customSchedulerFn=scheduleFn}function lib$es6$promise$asap$$setAsap(asapFn){lib$es6$promise$asap$$asap=asapFn}var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){return function(){process.nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ +function Promise(resolver) { + this._id = counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (noop !== resolver) { + if (!isFunction(resolver)) { + needsResolver(); + } + + if (!(this instanceof Promise)) { + needsNew(); + } + + initializePromise(this, resolver); + } +} + +Promise.all = all; +Promise.race = race; +Promise.resolve = Resolve; +Promise.reject = Reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; + +Promise.prototype = { + constructor: Promise, + +/** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} +*/ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + asap(function(){ + invokeCallback(state, child, callback, result); + }); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + +/** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} +*/ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } +}; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js new file mode 100644 index 0000000..03033f0 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js @@ -0,0 +1,52 @@ +import Enumerator from '../enumerator'; + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = resolve(2); + var promise3 = resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = reject(new Error("2")); + var promise3 = reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +export default function all(entries) { + return new Enumerator(this, entries).promise; +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js new file mode 100644 index 0000000..0d7ff13 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js @@ -0,0 +1,104 @@ +import { + isArray +} from "../utils"; + +import { + noop, + resolve, + reject, + subscribe, + PENDING +} from '../-internal'; + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +export default function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(noop); + + if (!isArray(entries)) { + reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + resolve(promise, value); + } + + function onRejection(reason) { + reject(promise, reason); + } + + for (var i = 0; promise._state === PENDING && i < length; i++) { + subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js new file mode 100644 index 0000000..63b86cb --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js @@ -0,0 +1,46 @@ +import { + noop, + reject as _reject +} from '../-internal'; + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +export default function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js new file mode 100644 index 0000000..201a545 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js @@ -0,0 +1,48 @@ +import { + noop, + resolve as _resolve +} from '../-internal'; + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +export default function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js new file mode 100644 index 0000000..31ec6f9 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js @@ -0,0 +1,22 @@ +export function objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); +} + +export function isFunction(x) { + return typeof x === 'function'; +} + +export function isMaybeThenable(x) { + return typeof x === 'object' && x !== null; +} + +var _isArray; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +export var isArray = _isArray; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/package.json new file mode 100644 index 0000000..ee791bb --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/es6-promise/package.json @@ -0,0 +1,94 @@ +{ + "name": "es6-promise", + "namespace": "es6-promise", + "version": "3.0.2", + "description": "A lightweight library that provides tools for organizing asynchronous code", + "main": "dist/es6-promise.js", + "directories": { + "lib": "lib" + }, + "files": [ + "dist", + "lib", + "!dist/test" + ], + "devDependencies": { + "bower": "^1.3.9", + "brfs": "0.0.8", + "broccoli-es3-safe-recast": "0.0.8", + "broccoli-es6-module-transpiler": "^0.5.0", + "broccoli-jshint": "^0.5.1", + "broccoli-merge-trees": "^0.1.4", + "broccoli-replace": "^0.2.0", + "broccoli-stew": "0.0.6", + "broccoli-uglify-js": "^0.1.3", + "broccoli-watchify": "^0.2.0", + "ember-cli": "0.2.3", + "ember-publisher": "0.0.7", + "git-repo-version": "0.0.2", + "json3": "^3.3.2", + "minimatch": "^2.0.1", + "mocha": "^1.20.1", + "promises-aplus-tests-phantom": "^2.1.0-revise", + "release-it": "0.0.10" + }, + "scripts": { + "build": "ember build", + "start": "ember s", + "test": "ember test", + "test:server": "ember test --server", + "test:node": "ember build && mocha ./dist/test/browserify", + "lint": "jshint lib", + "prepublish": "ember build --environment production", + "dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive" + }, + "repository": { + "type": "git", + "url": "git://github.com/jakearchibald/ES6-Promises.git" + }, + "bugs": { + "url": "https://github.com/jakearchibald/ES6-Promises/issues" + }, + "browser": { + "vertx": false + }, + "keywords": [ + "promises", + "futures" + ], + "author": { + "name": "Yehuda Katz, Tom Dale, Stefan Penner and contributors", + "url": "Conversion to ES6 API by Jake Archibald" + }, + "license": "MIT", + "spm": { + "main": "dist/es6-promise.js" + }, + "gitHead": "6c49ef79609737bac2b496d508806a3d5e37303e", + "homepage": "https://github.com/jakearchibald/ES6-Promises#readme", + "_id": "es6-promise@3.0.2", + "_shasum": "010d5858423a5f118979665f46486a95c6ee2bb6", + "_from": "es6-promise@3.0.2", + "_npmVersion": "2.13.4", + "_nodeVersion": "2.2.1", + "_npmUser": { + "name": "stefanpenner", + "email": "stefan.penner@gmail.com" + }, + "maintainers": [ + { + "name": "jaffathecake", + "email": "jaffathecake@gmail.com" + }, + { + "name": "stefanpenner", + "email": "stefan.penner@gmail.com" + } + ], + "dist": { + "shasum": "010d5858423a5f118979665f46486a95c6ee2bb6", + "tarball": "http://registry.npmjs.org/es6-promise/-/es6-promise-3.0.2.tgz" + }, + "_resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/.coveralls.yml b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/.coveralls.yml new file mode 100644 index 0000000..a0b4fb6 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/.coveralls.yml @@ -0,0 +1 @@ +repo_token: 47iIZ0B3llo2Wc4dxWRltvgdImqcrVDTi diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md new file mode 100644 index 0000000..e0f93d7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md @@ -0,0 +1,351 @@ +1.3.1 2016-02-05 +---------------- +- Removed annoying missing Kerberos error (NODE-654). + +1.3.0 2016-02-03 +---------------- +- Added raw support for the command function on topologies. +- Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +- Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +- Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +- NODE-638, Cannot authenticate database user with utf-8 password. +- Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +- Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +- Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +- Switched to using Array.push instead of concat for use cases of a lot of documents. +- Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +- Added peer optional dependencies support using require_optional module. + +1.2.32 2016-01-12 +----------------- +- Bumped bson to V0.4.21 to allow using minor optimizations. + +1.2.31 2016-01-04 +----------------- +- Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +1.2.30 2015-12-23 +----------------- +- Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +- Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +1.2.29 2015-12-17 +----------------- +- Correctly emit close event when calling destroy on server topology. + +1.2.28 2015-12-13 +----------------- +- Backed out Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous) as it breaks node 0.10.x support. + +1.2.27 2015-12-13 +----------------- +- Added [options.checkServerIdentity=true] {boolean|function}. Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function, (Issue #29). +- Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous). +- State is not defined in mongos, (Issue #63, https://github.com/flyingfisher). +- Fixed corner case issue on exhaust cursors on pre 3.0.x MongoDB. + +1.2.26 2015-11-23 +----------------- +- Converted test suite to use mongodb-topology-manager. +- Upgraded bson library to V0.4.20. +- Minor fixes for 3.2 readPreferences. + +1.2.25 2015-11-23 +----------------- +- Correctly error out when passed a seedlist of non-valid server members. + +1.2.24 2015-11-20 +----------------- +- Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). +- $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + +1.2.23 2015-11-16 +----------------- +- ismaster runs against admin.$cmd instead of system.$cmd. + +1.2.22 2015-11-16 +----------------- +- Fixes to handle getMore command errors for MongoDB 3.2 +- Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +1.2.21 2015-11-07 +----------------- +- Hardened the checking for replicaset equality checks. +- OpReplay flag correctly set on Wire protocol query. +- Mongos load balancing added, introduced localThresholdMS to control the feature. +- Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +1.2.20 2015-10-28 +----------------- +- Fixed bug in arbiter connection capping code. +- NODE-599 correctly handle arrays of server tags in order of priority. +- Fix for 2.6 wire protocol handler related to readPreference handling. +- Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +- Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +1.2.19 2015-10-15 +----------------- +- Make batchSize always be > 0 for 3.2 wire protocol to make it work consistently with pre 3.2 servers. +- Locked to bson 0.4.19. + +1.2.18 2015-10-15 +----------------- +- Minor 3.2 fix for handling readPreferences on sharded commands. +- Minor fixes to correctly pass APM specification test suite. + +1.2.17 2015-10-08 +----------------- +- Connections to arbiters only maintain a single connection. + +1.2.15 2015-10-06 +----------------- +- Set slaveOk to true for getMore and killCursors commands. +- Don't swallow callback errors for 2.4 single server (Issue #49, https://github.com/vkarpov15). +- Apply toString('hex') to each buffer in an array when logging (Issue #48, https://github.com/nbrachet). + +1.2.14 2015-09-28 +----------------- +- NODE-547 only emit error if there are any listeners. +- Fixed APM issue with issuing readConcern. + +1.2.13 2015-09-18 +----------------- +- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. + +1.2.12 2015-09-08 +----------------- +- NODE-541 Added initial support for readConcern. + +1.2.11 2015-08-31 +----------------- +- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. +- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. +- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). + +1.2.10 2015-08-14 +----------------- +- Added missing Mongos.prototype.parserType function. + +1.2.9 2015-08-05 +---------------- +- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +- NODE-518 connectTimeoutMS is doubled in 2.0.39. + +1.2.8 2015-07-24 +----------------- +- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. + +1.2.7 2015-07-16 +----------------- +- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. + +1.2.6 2015-07-14 +----------------- +- NODE-505 Query fails to find records that have a 'result' property with an array value. + +1.2.5 2015-07-14 +----------------- +- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. + +1.2.4 2015-07-07 +----------------- +- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. + +1.2.3 2015-06-26 +----------------- +- Minor bug fixes. + +1.2.2 2015-06-22 +----------------- +- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). + +1.2.1 2015-06-17 +----------------- +- Ensure serializeFunctions passed down correctly to wire protocol. + +1.2.0 2015-06-17 +----------------- +- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. +- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. +- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +1.1.33 2015-05-31 +----------------- +- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. + +1.1.32 2015-05-20 +----------------- +- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) + +1.1.31 2015-05-19 +----------------- +- Minor fixes for issues with re-authentication of mongos. + +1.1.30 2015-05-18 +----------------- +- Correctly emit 'all' event when primary + all secondaries have connected. + +1.1.29 2015-05-17 +----------------- +- NODE-464 Only use a single socket against arbiters and hidden servers. +- Ensure we filter out hidden servers from any server queries. + +1.1.28 2015-05-12 +----------------- +- Fixed buffer compare for electionId for < node 12.0.2 + +1.1.27 2015-05-12 +----------------- +- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. + +1.1.26 2015-05-06 +----------------- +- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. +- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. + +1.1.25 2015-04-24 +----------------- +- Handle lack of callback in crud operations when returning error on application closed. + +1.1.24 2015-04-22 +----------------- +- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. + +1.1.23 2015-04-15 +----------------- +- Standardizing mongoErrors and its API (Issue #14) +- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) +- remove mkdirp and rimraf dependencies (Issue #12) +- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) +- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) +- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) + +1.1.22 2015-04-10 +----------------- +- Minor refactorings in cursor code to make extending the cursor simpler. +- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. + +1.1.21 2015-03-26 +----------------- +- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. + +1.1.20 2015-03-24 +----------------- +- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. + +1.1.19 2015-03-21 +----------------- +- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. + +1.1.18 2015-03-17 +----------------- +- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. + +1.1.17 2015-03-16 +----------------- +- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. + +1.1.16 2015-03-06 +----------------- +- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. + +1.1.15 2015-03-04 +----------------- +- Removed check for type in replset pickserver function. + +1.1.14 2015-02-26 +----------------- +- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads + +1.1.13 2015-02-24 +----------------- +- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) + +1.1.12 2015-02-16 +----------------- +- Fixed cursor transforms for buffered document reads from cursor. + +1.1.11 2015-02-02 +----------------- +- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +1.1.10 2015-31-01 +----------------- +- Added tranforms.doc option to cursor to allow for pr. document transformations. + +1.1.9 2015-21-01 +---------------- +- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. +- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. +- Don't treat findOne() as a command cursor. +- Refactored out state changes into methods to simplify read the next method. + +1.1.8 2015-09-12 +---------------- +- Stripped out Object.defineProperty for performance reasons +- Applied more performance optimizations. +- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit + +1.1.7 2014-18-12 +---------------- +- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. + +1.1.6 2014-18-12 +---------------- +- Server manager fixed to support 2.2.X servers for travis test matrix. + +1.1.5 2014-17-12 +---------------- +- Fall back to errmsg when creating MongoError for command errors + +1.1.4 2014-17-12 +---------------- +- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. +- Fixed variable leak in scram. +- Fixed server manager to deal better with killing processes. +- Bumped bson to 0.2.16. + +1.1.3 2014-01-12 +---------------- +- Fixed error handling issue with nonce generation in mongocr. +- Fixed issues with restarting servers when using ssl. +- Using strict for all classes. +- Cleaned up any escaping global variables. + +1.1.2 2014-20-11 +---------------- +- Correctly encoding UTF8 collection names on wire protocol messages. +- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. + +1.1.1 2014-14-11 +---------------- +- Refactored code to use prototype instead of privileged methods. +- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. +- Several deopt optimizations for v8 to improve performance and reduce GC pauses. + +1.0.5 2014-29-10 +---------------- +- Fixed issue with wrong namespace being created for command cursors. + +1.0.4 2014-24-10 +---------------- +- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. + +1.0.3 2014-21-10 +---------------- +- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. + +1.0.2 2014-07-10 +---------------- +- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. +- fixed issue with replset_state logging. + +1.0.1 2014-07-10 +---------------- +- Dependency issue solved + +1.0.0 2014-07-10 +---------------- +- Initial release of mongodb-core diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/LICENSE b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/LICENSE @@ -0,0 +1,201 @@ +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. \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/Makefile b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/Makefile new file mode 100644 index 0000000..36e1202 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/Makefile @@ -0,0 +1,11 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + hugo -s docs/reference -d ../../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/README.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/README.md new file mode 100644 index 0000000..433dd88 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/README.md @@ -0,0 +1,228 @@ +[![Build Status](https://secure.travis-ci.org/christkv/mongodb-core.png)](http://travis-ci.org/christkv/mongodb-core) +[![Coverage Status](https://coveralls.io/repos/github/christkv/mongodb-core/badge.svg?branch=1.3)](https://coveralls.io/github/christkv/mongodb-core?branch=1.3) + +# Description + +The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. + +## MongoDB Node.JS Core Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| apidoc | http://mongodb.github.io/node-mongodb-native/ | +| source | https://github.com/christkv/mongodb-core | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) + +### 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 + +# QuickStart + +The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. + +## Create the package.json file + +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Create a **package.json** using your favorite text editor and fill it in. + +```json +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb-core": "~1.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +## Connecting to MongoDB + +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + test.done(); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + + // Execute the ismaster command + _server.command('system.$cmd', {ismaster: true}, function(err, result) { + + // Perform a document insert + _server.insert('myproject.inserts1', [{a:1}, {a:2}], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(2, results.result.n); + + // Perform a document update + _server.update('myproject.inserts1', [{ + q: {a: 1}, u: {'$set': {b:1}} + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Remove a document + _server.remove('myproject.inserts1', [{ + q: {a: 1}, limit: 1 + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Get a document + var cursor = _server.cursor('integration_tests.inserts_example4', { + find: 'integration_tests.example4' + , query: {a:1} + }); + + // Get the first document + cursor.next(function(err, doc) { + assert.equal(null, err); + assert.equal(2, doc.a); + + // Execute the ismaster command + _server.command("system.$cmd" + , {ismaster: true}, function(err, result) { + assert.equal(null, err) + _server.destroy(); + }); + }); + }); + }); + + test.done(); + }); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. + +* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. +* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. +* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. +* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. +* `command`, Executes a command against MongoDB and returns the result. +* `auth`, Authenticates the current topology using a supported authentication scheme. + +The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. + +## Next steps + +The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/TESTING.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/TESTING.md new file mode 100644 index 0000000..fe03ea0 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/TESTING.md @@ -0,0 +1,18 @@ +Testing setup +============= + +Single Server +------------- +mongod --dbpath=./db + +Replicaset +---------- +mongo --nodb +var x = new ReplSetTest({"useHostName":"false", "nodes" : {node0 : {}, node1 : {}, node2 : {}}}) +x.startSet(); +var config = x.getReplSetConfig() +x.initiate(config); + +Mongos +------ +var s = new ShardingTest( "auth1", 1 , 0 , 2 , {rs: true, noChunkSize : true}); \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/conf.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/conf.json new file mode 100644 index 0000000..c5eca92 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/conf.json @@ -0,0 +1,60 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/tests/functional/operation_example_tests.js", + "lib/topologies/mongos.js", + "lib/topologies/command_result.js", + "lib/topologies/read_preference.js", + "lib/topologies/replset.js", + "lib/topologies/server.js", + "lib/topologies/session.js", + "lib/topologies/replset_state.js", + "lib/connection/logger.js", + "lib/connection/connection.js", + "lib/cursor.js", + "lib/error.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/index.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/index.js new file mode 100644 index 0000000..8f10860 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/index.js @@ -0,0 +1,18 @@ +module.exports = { + MongoError: require('./lib/error') + , Server: require('./lib/topologies/server') + , ReplSet: require('./lib/topologies/replset') + , Mongos: require('./lib/topologies/mongos') + , Logger: require('./lib/connection/logger') + , Cursor: require('./lib/cursor') + , ReadPreference: require('./lib/topologies/read_preference') + , BSON: require('bson') + // Raw operations + , Query: require('./lib/connection/commands').Query + // Auth mechanisms + , MongoCR: require('./lib/auth/mongocr') + , X509: require('./lib/auth/x509') + , Plain: require('./lib/auth/plain') + , GSSAPI: require('./lib/auth/gssapi') + , ScramSHA1: require('./lib/auth/scram') +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js new file mode 100644 index 0000000..dc7b546 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js @@ -0,0 +1,246 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , require_optional = require('require_optional') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require_optional('kerberos').Kerberos; + // Authentication process for Mongo + MongoAuthProcess = require_optional('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new GSSAPI authentication mechanism + * @class + * @return {GSSAPI} A cursor instance + */ +var GSSAPI = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.auth = function(server, connections, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // 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 execute = function(connection) { + // Start Auth process for a connection + GSSAPIInitialize(db, username, password, db, gssapiServiceName, server, connection, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// +// Initialize step +var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, server, connection, callback) { + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.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, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback) { + // Build the sasl start command + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: payload + , autoAuthorize: 1 + }; + + // Execute first sasl step + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // Execute mongodb transition + mongo_auth_process.transition(r.result.payload, function(err, payload) { + if(err) return callback(err, false); + + // MongoDB API Second Step + MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // 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, server, connection, callback); + }); + }); +} + +var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build final command + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + mongo_auth_process.transition(null, function(err, payload) { + if(err) return callback(err, null); + callback(null, r); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var err = null; + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, authStore[i].options, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = GSSAPI; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js new file mode 100644 index 0000000..a23bcb9 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js @@ -0,0 +1,161 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new MongoCR authentication mechanism + * @class + * @return {MongoCR} A cursor instance + */ +var MongoCR = function() { + this.authStore = []; +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // 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 executeMongoCR = function(connection) { + // Let's start the process + server.command(f("%s.$cmd", db) + , { getnonce: 1 } + , { connection: connection }, function(err, r) { + var nonce = null; + var key = null; + + // Adjust the number of connections left + // Get nonce + if(err == null) { + nonce = r.result.nonce; + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password, 'utf8'); + var hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + + // Execute command + server.command(f("%s.$cmd", db) + , { authenticate: 1, user: username, nonce: nonce, key:key} + , { connection: connection }, function(err, r) { + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + }); + } + + // Get the connection + executeMongoCR(connections.shift()); + } +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var err = null; + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = MongoCR; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js new file mode 100644 index 0000000..83eb3d3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js @@ -0,0 +1,151 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Binary = require('bson').Binary + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new Plain authentication mechanism + * @class + * @return {Plain} A cursor instance + */ +var Plain = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // 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 execute = function(connection) { + // Create payload + var payload = new Binary(f("\x00%s\x00%s", username, password)); + + // Let's start the sasl process + var command = { + saslStart: 1 + , mechanism: 'PLAIN' + , payload: payload + , autoAuthorize: 1 + }; + + // Let's start the process + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var err = null; + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = Plain; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js new file mode 100644 index 0000000..7f8e60b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js @@ -0,0 +1,322 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Binary = require('bson').Binary + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +var id = 0; + +/** + * Creates a new ScramSHA1 authentication mechanism + * @class + * @return {ScramSHA1} A cursor instance + */ +var ScramSHA1 = function() { + this.authStore = []; + this.id = id++; +} + +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 new MongoError("username must be a string"); + if(typeof password != 'string') throw new MongoError("password must be a string"); + if(password.length == 0) throw new MongoError("password cannot be empty"); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password, 'utf8'); + 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); + return new Buffer(hmac.digest('base64'), 'base64'); + } + + // 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; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // 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) { + numberOfValidConnections = numberOfValidConnections - 1; + errorObject = err; return false; + } else if(r.result['$err']) { + errorObject = r.result; return false; + } else if(r.result['errmsg']) { + errorObject = r.result; return false; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + return true + } + + // Finish up + var finish = function(_count, _numberOfValidConnections) { + if(_count == 0 && _numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(_count == 0) { + if(errorObject == null) errorObject = new MongoError(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 + server.command(f("%s.$cmd", db) + , 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(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); + return callback(errorObject, false); + } + + return; + } + + // Get the dictionary + var dict = parsePayload(r.result.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 = new Buffer(hmac.digest('base64'), 'base64'); + + // Create the stored key + var hash = crypto.createHash('sha1'); + hash.update(clientKey); + var storedKey = new Buffer(hash.digest('base64'), 'base64'); + + // Create the authentication message + var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join(','); + + // Create client signature + var hmac = crypto.createHmac('sha1', storedKey); + hmac.update(new Buffer(authMsg)); + var clientSig = new Buffer(hmac.digest('base64'), 'base64'); + + // 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 = new Buffer(hmac.digest('base64'), 'base64'); + + // Generate server signature + var hmac = crypto.createHmac('sha1', serverKey); + hmac.update(new Buffer(authMsg)) + var serverSig = new Buffer(hmac.digest('base64'), 'base64'); + + // + // Create continue message + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Binary(new Buffer(clientFinal)) + } + + // + // Execute sasl continue + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + if(r && r.result.done == false) { + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Buffer(0) + } + + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + handleEnd(err, r); + }); + } else { + handleEnd(err, r); + } + }); + }); + } + + // Get the connection + executeScram(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + var err = null; + // No connections + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + + +module.exports = ScramSHA1; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js new file mode 100644 index 0000000..44eece7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js @@ -0,0 +1,236 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , require_optional = require('require_optional') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require_optional('kerberos').Kerberos + // Authentication process for Mongo + MongoAuthProcess = require_optional('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new SSPI authentication mechanism + * @class + * @return {SSPI} A cursor instance + */ +var SSPI = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.auth = function(server, connections, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // 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 execute = function(connection) { + // Start Auth process for a connection + SSIPAuthenticate(username, password, gssapiServiceName, server, connection, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r && typeof r == 'object' && r.result['$err']) { + errorObject = r.result; + } else if(r && typeof r == 'object' && r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +var SSIPAuthenticate = function(username, password, gssapiServiceName, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: '' + , autoAuthorize: 1 + }; + + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); + + // Execute first sasl step + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + 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 + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + 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 + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + 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 + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + if(doc.done) return callback(null, true); + callback(new Error("Authentication failed"), false); + }); + }); + }); + }); + }); + }); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var err = null; + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, authStore[i].options, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = SSPI; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js new file mode 100644 index 0000000..59839c3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js @@ -0,0 +1,146 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new X509 authentication mechanism + * @class + * @return {X509} A cursor instance + */ +var X509 = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // 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 execute = function(connection) { + // Let's start the sasl process + var command = { + authenticate: 1 + , mechanism: 'MONGODB-X509' + , user: username + }; + + // Let's start the process + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var err = null; + var count = authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < authStore.length; i++) { + this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err, r) { + if(err) err = err; + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(err, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = X509; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js new file mode 100644 index 0000000..98950e4 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js @@ -0,0 +1,540 @@ +"use strict"; + +var f = require('util').format + , Long = require('bson').Long + , setProperty = require('./utils').setProperty + , getProperty = require('./utils').getProperty + , getSingleProperty = require('./utils').getSingleProperty; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var OP_QUERY = 2004; +var OP_GETMORE = 2005; +var OP_KILL_CURSORS = 2007; + +// Query flags +var OPTS_NONE = 0; +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 0; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if(ns == null) throw new Error("ns must be specified for query"); + if(query == null) throw new Error("query must be specified for query"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new Error("namespace cannot contain a null character"); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Ensure empty options + this.options = options || {}; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = _requestId++; + + // Serialization option + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +} + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +} + +// +// Assign a new request Id +Query.nextRequestId = function() { + return _requestId + 1; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + var buffers = []; + var projection = null; + + // Set up the flags + var flags = 0; + if(this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if(this.slaveOk) { + flags |= OPTS_SLAVE; + } + + if(this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if(this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if(this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if(this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if(this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to self.numberToReturn + if(self.batchSize != self.numberToReturn) self.numberToReturn = self.batchSize; + + // Allocate write protocol header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // Flags + + Buffer.byteLength(self.ns) + 1 // namespace + + 4 // numberToSkip + + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + var query = self.bson.serialize(this.query + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + + // Add query document + buffers.push(query); + + if(self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = self.bson.serialize(this.returnFieldSelector, this.checkKeys, true, this.serializeFunctions, this.ignoreUndefined); + // Add projection document + buffers.push(projection); + } + + // Total message size + var totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + var index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = (totalLength) & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (OP_QUERY >> 24) & 0xff; + header[index + 2] = (OP_QUERY >> 16) & 0xff; + header[index + 1] = (OP_QUERY >> 8) & 0xff; + header[index] = (OP_QUERY) & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = (flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = (this.numberToSkip) & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +Query.getRequestId = function() { + return ++_requestId; +} + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + (4 * 4); + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; + _buffer[index] = (OP_GETMORE) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getHighBits()) & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +} + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, cursorIds) { + this.requestId = _requestId++; + this.cursorIds = cursorIds; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); + + // Create command buffer + var index = 0; + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = (OP_KILL_CURSORS) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = (this.cursorIds.length) & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for(var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getHighBits()) & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +} + +var Response = function(connection, bson, data, opts) { + opts = opts || {promoteLongs: true}; + this.parsed = false; + this.connection = connection; + + // + // Parse Header + // + this.index = 0; + this.raw = data; + this.data = data; + this.bson = bson; + this.opts = opts; + + // Read the message length + this.length = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the request id for this reply + this.requestId = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the id of the request that triggered the response + this.responseTo = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Skip op-code field + this.index = this.index + 4; + + // Unpack flags + this.responseFlags = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the cursor + var lowBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + var highBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + // Create long object + this.cursorId = new Long(lowBits, highBits); + + // Unpack the starting from + this.startingFrom = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the number of objects returned + this.numberReturned = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) != 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) != 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) != 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) != 0; + this.promoteLongs = typeof opts.promoteLongs == 'boolean' ? opts.promoteLongs : true; +} + +Response.prototype.isParsed = function() { + return this.parsed; +} + +// Validation buffers +var firstBatch = new Buffer('firstBatch', 'utf8'); +var nextBatch = new Buffer('nextBatch', 'utf8'); +var cursorId = new Buffer('id', 'utf8').toString('hex'); + +var documentBuffers = { + firstBatch: firstBatch.toString('hex'), + nextBatch: nextBatch.toString('hex') +}; + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if(this.parsed) return; + options = options || {}; + + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + var documentsReturnedIn = options.documentsReturnedIn || null; + + // + // Single document and documentsReturnedIn set + // + if(this.numberReturned == 1 && documentsReturnedIn != null && raw) { + // Calculate the bson size + var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + // Slice out the buffer containing the command result document + var document = this.data.slice(this.index, this.index + bsonSize); + // Set up field we wish to keep as raw + var fieldsAsRaw = {} + fieldsAsRaw[documentsReturnedIn] = true; + // Set up the options + var _options = {promoteLongs: this.opts.promoteLongs, fieldsAsRaw: fieldsAsRaw}; + + // Deserialize but keep the array of documents in non-parsed form + var doc = this.bson.deserialize(document, _options); + + // Get the documents + this.documents = doc.cursor[documentsReturnedIn]; + this.numberReturned = this.documents.length; + // Ensure we have a Long valie cursor id + this.cursorId = typeof doc.cursor.id == 'number' + ? Long.fromNumber(doc.cursor.id) + : doc.cursor.id; + + // Adjust the index + this.index = this.index + bsonSize; + + // Set as parsed + this.parsed = true + return; + } + + // + // Parse Body + // + for(var i = 0; i < this.numberReturned; i++) { + var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + // Parse options + var _options = {promoteLongs: this.opts.promoteLongs}; + + // If we have raw results specified slice the return document + if(raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + // Set parsed + this.parsed = true; +} + +module.exports = { + Query: Query + , GetMore: GetMore + , Response: Response + , KillCursor: KillCursor +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js new file mode 100644 index 0000000..6359e6a --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js @@ -0,0 +1,496 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , net = require('net') + , tls = require('tls') + , f = require('util').format + , crypto = require('crypto') + , getSingleProperty = require('./utils').getSingleProperty + , debugOptions = require('./utils').debugOptions + , Response = require('./commands').Response + , MongoError = require('../error') + , Logger = require('./logger'); + +var _id = 0; +var debugFields = ['host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay' + , 'connectionTimeout', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert' + , 'rejectUnauthorized', 'promoteLongs', 'checkServerIdentity']; + +/** + * Creates a new Connection instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @return {Connection} A cursor instance + */ +var Connection = function(options) { + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + // Identification information + this.id = _id++; + // Logger instance + this.logger = Logger('Connection', options); + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Get bson parser + this.bson = options.bson; + // Grouping tag used for debugging purposes + this.tag = options.tag; + // Message handler + this.messageHandler = options.messageHandler; + + // Max BSON message size + this.maxBsonMessageSize = options.maxBsonMessageSize || (1024 * 1024 * 16 * 4); + // Debug information + if(this.logger.isDebug()) this.logger.debug(f('creating connection %s with options [%s]', this.id, JSON.stringify(debugOptions(debugFields, options)))); + + // Default options + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.keepAlive = typeof options.keepAlive == 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = options.keepAliveInitialDelay || 0; + this.noDelay = typeof options.noDelay == 'boolean' ? options.noDelay : true; + this.connectionTimeout = options.connectionTimeout || 0; + this.socketTimeout = options.socketTimeout || 0; + + // If connection was destroyed + this.destroyed = false; + + // Check if we have a domain socket + this.domainSocket = this.host.indexOf('\/') != -1; + + // Serialize commands using function + this.singleBufferSerializtion = typeof options.singleBufferSerializtion == 'boolean' ? options.singleBufferSerializtion : true; + this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; + + // SSL options + this.ca = options.ca || null; + this.cert = options.cert || null; + this.key = options.key || null; + this.passphrase = options.passphrase || null; + this.ssl = typeof options.ssl == 'boolean' ? options.ssl : false; + this.rejectUnauthorized = typeof options.rejectUnauthorized == 'boolean' ? options.rejectUnauthorized : true; + this.checkServerIdentity = typeof options.checkServerIdentity == 'boolean' + || typeof options.checkServerIdentity == 'function' ? options.checkServerIdentity : true; + + // If ssl not enabled + if(!this.ssl) this.rejectUnauthorized = false; + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true + } + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.connection = null; + this.writeStream = null; + + // Create hash method + var hash = crypto.createHash('sha1'); + hash.update(f('%s:%s', this.host, this.port)); + + // Create a hash name + this.hashedName = hash.digest('hex'); +} + +inherits(Connection, EventEmitter); + +// +// Connection handlers +var errorHandler = function(self) { + return function(err) { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] errored out with [%s]', self.id, self.host, self.port, JSON.stringify(err))); + // Emit the error + if(self.listeners('error').length > 0) self.emit("error", MongoError.create(err), self); + } +} + +var timeoutHandler = function(self) { + return function() { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); + // Emit timeout error + self.emit("timeout" + , MongoError.create(f("connection %s to %s:%s timed out", self.id, self.host, self.port)) + , self); + } +} + +var closeHandler = function(self) { + return function(hadError) { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); + // Emit close event + if(!hadError) { + self.emit("close" + , MongoError.create(f("connection %s to %s:%s closed", self.id, self.host, self.port)) + , self); + } + } +} + +var dataHandler = function(self) { + 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.messageHandler(new Response(self, self.bson, emitBuffer, self.responseOptions), self); + } catch(err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // 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 = data.readUInt32LE(0); + var sizeOfMessage = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; + // If we have a negative sizeOfMessage emit error and return + if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { + var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ + sizeOfMessage: sizeOfMessage, + bytesRead: self.bytesRead, + stubBuffer: self.stubBuffer}}; + // 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.maxBsonMessageSize && 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.maxBsonMessageSize && 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.messageHandler(new Response(self, self.bson, emitBuffer, self.responseOptions), self); + } catch (err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + } + } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { + var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ + sizeOfMessage:sizeOfMessage, + bytesRead:0, + buffer:null, + stubBuffer:null}}; + // 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 { + 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.messageHandler(new Response(self, self.bson, emitBuffer, self.responseOptions), 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); + } + } + } + } + } +} + +/** + * Connect + * @method + */ +Connection.prototype.connect = function(_options) { + var self = this; + _options = _options || {}; + // Check if we are overriding the promoteLongs + if(typeof _options.promoteLongs == 'boolean') { + self.responseOptions.promoteLongs = _options.promoteLongs; + } + + // Create new connection instance + self.connection = self.domainSocket + ? net.createConnection(self.host) + : net.createConnection(self.port, self.host); + + // Set the options for the connection + self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); + self.connection.setTimeout(self.connectionTimeout); + self.connection.setNoDelay(self.noDelay); + + // If we have ssl enabled + if(self.ssl) { + var sslOptions = { + socket: self.connection + , rejectUnauthorized: self.rejectUnauthorized + } + + if(self.ca) sslOptions.ca = self.ca; + if(self.cert) sslOptions.cert = self.cert; + if(self.key) sslOptions.key = self.key; + if(self.passphrase) sslOptions.passphrase = self.passphrase; + + // Override checkServerIdentity behavior + if(self.checkServerIdentity == false) { + // Skip the identiy check by retuning undefined as per node documents + // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback + sslOptions.checkServerIdentity = function(servername, cert) { + return undefined; + } + } else if(typeof self.checkServerIdentity == 'function') { + sslOptions.checkServerIdentity = self.checkServerIdentity; + } + + // Attempt SSL connection + self.connection = tls.connect(self.port, self.host, sslOptions, function() { + // Error on auth or skip + if(self.connection.authorizationError && self.rejectUnauthorized) { + return self.emit("error", self.connection.authorizationError, self, {ssl:true}); + } + + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // We are done emit connect + self.emit('connect', self); + }); + self.connection.setTimeout(self.connectionTimeout); + } else { + self.connection.on('connect', function() { + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // Emit connect event + self.emit('connect', self); + }); + } + + // Add handlers for events + self.connection.once('error', errorHandler(self)); + self.connection.once('timeout', timeoutHandler(self)); + self.connection.once('close', closeHandler(self)); + self.connection.on('data', dataHandler(self)); +} + +/** + * Destroy connection + * @method + */ +Connection.prototype.destroy = function() { + if(this.connection) { + this.connection.end(); + this.connection.destroy(); + } + + this.destroyed = true; +} + +/** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ +Connection.prototype.write = function(buffer) { + // Debug Log + if(this.logger.isDebug()) { + if(!Array.isArray(buffer)) { + this.logger.debug(f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port)); + } else { + for(var i = 0; i < buffer.length; i++) + this.logger.debug(f('writing buffer [%s] to %s:%s', buffer[i].toString('hex'), this.host, this.port)); + } + } + + // Write out the command + if(!Array.isArray(buffer)) return this.connection.write(buffer, 'binary'); + // Iterate over all buffers and write them in order to the socket + for(var i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); +} + +/** + * Return id of connection as a string + * @method + * @return {string} + */ +Connection.prototype.toString = function() { + return "" + this.id; +} + +/** + * Return json object of connection + * @method + * @return {object} + */ +Connection.prototype.toJSON = function() { + return {id: this.id, host: this.host, port: this.port}; +} + +/** + * Is the connection connected + * @method + * @return {boolean} + */ +Connection.prototype.isConnected = function() { + if(this.destroyed) return false; + return !this.connection.destroyed && this.connection.writable; +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +module.exports = Connection; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js new file mode 100644 index 0000000..69c6f93 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js @@ -0,0 +1,196 @@ +"use strict"; + +var f = require('util').format + , MongoError = require('../error'); + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Function} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + * @return {Logger} a Logger instance. + */ +var Logger = function(className, options) { + if(!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + var self = this; + this.className = className; + + // Current logger + if(currentLogger == null && options.logger) { + currentLogger = options.logger; + } else if(currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if(level == null) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if(filteredClasses[this.className] == null) classFilters[this.className] = true; +} + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if(this.isDebug() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +} + +/** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.info = function(message, object) { + if(this.isInfo() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.error = function(message, object) { + if(this.isError() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Is the logger set at info level + * @method + * @return {boolean} + */ +Logger.prototype.isInfo = function() { + return level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at error level + * @method + * @return {boolean} + */ +Logger.prototype.isError = function() { + return level == 'error' || level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at debug level + * @method + * @return {boolean} + */ +Logger.prototype.isDebug = function() { + return level == 'debug'; +} + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +} + +/** + * Get the current logger function + * @method + * @return {function} + */ +Logger.currentLogger = function() { + return currentLogger; +} + +/** + * Set the current logger function + * @method + * @param {function} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if(typeof logger != 'function') throw new MongoError("current logger must be a function"); + currentLogger = logger; +} + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if(type == 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +} + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if(_level != 'info' && _level != 'error' && _level != 'debug') throw new Error(f("%s is an illegal logging level", _level)); + level = _level; +} + +module.exports = Logger; \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js new file mode 100644 index 0000000..9d488a9 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js @@ -0,0 +1,614 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , Connection = require('./connection') + , Query = require('./commands').Query + , Logger = require('./logger') + , f = require('util').format; + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +var _id = 0; + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=1] Max server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passPhrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(options) { + var self = this; + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + this.size = typeof options.size == 'number' && !isNaN(options.size) ? options.size : 5; + this.waitMS = typeof options.waitMS == 'number' && !isNaN(options.waitMS) ? options.waitMS : 1000; + + // Save host and port + this.host = options.host; + this.port = options.port; + + // Message handler + this.messageHandler = options.messageHandler; + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Contains all connections + this.connections = []; + // Contains all available connections + this.availableConnections = []; + this.inUseConnections = []; + this.newConnections = []; + this.connectingConnections = []; + // Current status of the pool + this.state = DISCONNECTED; + // Round robin index + this.index = 0; + this.dead = false; + // Logger instance + this.logger = Logger('Pool', options); + // If we are monitoring this server we will create an exclusive reserved socket for that + this.monitoring = typeof options.monitoring == 'boolean' ? options.monitoring : false; + // Maintain the monitoring connection + this.monitorConnection = null; + // Pool id + this.id = _id++; + // Grouping tag used for debugging purposes + this.tag = options.tag; + // Operation work queue + this.queue = []; + // Currently executing + this.executing = false; +} + +inherits(Pool, EventEmitter); + +var removeConnection = function(self, connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! number Of connection :: " + self.getAll().length) + var remove = function(connections) { + for(var i = 0; i < connections.length; i++) { + if(connections[i] === connection) { + // console.log("!!!!!!!!!!!!! removing the connection") + connections.splice(i, 1); + return true; + } + } + } + + // self.availableConnections.forEach(function(x) { + // console.log(x === connection) + // }) + // + // console.log("availableConnections :: " + self.availableConnections.length); + // console.log("inUseConnections :: " + self.inUseConnections.length); + // console.log("newConnections :: " + self.newConnections.length); + // console.log("connectingConnections :: " + self.connectingConnections.length); + + // Set the monitoring connection to undefined + if(self.monitorConnection === connection) { + self.monitorConnection = null; + } + + // Clean out the connection + if(remove(self.availableConnections)) return; + if(remove(self.inUseConnections)) return; + if(remove(self.newConnections)) return; + if(remove(self.connectingConnections)) return; +} + +var errorHandler = function(self) { + return function(err, connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! error POOL") + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + // Remove the connection + removeConnection(self, connection); + // Emit error + if(self.listeners('error').length > 0) { + self.emit('error', err, connection); + } + } +} + +var timeoutHandler = function(self) { + return function(err, connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! timeout POOL :: " + self.port) + // console.log("----------------------- pool.write _execute 0 :: availableConnections = " + self.availableConnections.length) + // console.log("----------------------- pool.write _execute 0 :: inUseConnections = " + self.inUseConnections.length) + // console.log("----------------------- pool.write _execute 0 :: newConnections = " + self.newConnections.length) + // console.log("----------------------- pool.write _execute 0 :: queue = " + self.queue.length) + + // // Get all connections + // self.availableConnections.forEach(function(x) { + // if(x === self.monitorConnection) { + // // console.log("!!!!!!!!!!!!!!!!!!!!!!!!! MONITORING CONNECTION") + // } + // }) + + + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] timed out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + // Remove the connection + removeConnection(self, connection); + // Emit connection timeout to server instance + self.emit('timeout', err, connection); + } +} + +var closeHandler = function(self) { + return function(err, connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! close POOL") + // if(connection === self.monitorConnection){ + // console.log(" monitorConnection closed") + // } + + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] closed [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + // Remove the connection + removeConnection(self, connection); + // Emit connection close to server instance + self.emit('close', err, connection); + } +} + +var parseErrorHandler = function(self) { + return function(err, connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! parseError POOL") + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + // Remove the connection + removeConnection(self, connection); + // Emit error to server instance + self.emit('parseError', err, connection); + } +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function() { + this.state = DESTROYED; + // Set dead + this.dead = true; + // Get all the connections + var connections = this.getAll(); + // Destroy all the connections + connections.forEach(function(c) { + // Destroy all event emitters + ["close", "message", "error", "timeout", "parseError", "connect"].forEach(function(e) { + c.removeAllListeners(e); + }); + + // Destroy the connection + c.destroy(); + }); + + // Do we have a monitoring connection + if(this.monitorConnection) { + this.monitorConnection.destroy(); + } +} + +var execute = null; + +try { + execute = setImmediate; +} catch(err) { + execute = process.nextTick; +} + +// execute = function(x) { +// setTimeout(x, 1) +// } + +// execute = setTimeout; + +/** + * Connect pool + * @method + */ +Pool.prototype.connect = function(_options) { + // console.log("---------------------- CONNECT") + var self = this; + // Set to connecting + this.state = CONNECTING + // No dead + this.dead = false; + + // Ensure we allow for a little time to setup connections + var wait = 1; + + // Number of initial connections to perform + var numberOfConnections = this.monitoring ? 2 : 1; + + // Connect all sockets + for(var i = 0; i < numberOfConnections; i++) { + setTimeout(function() { + execute(function() { + self.options.messageHandler = self.messageHandler; + var connection = new Connection(self.options); + + // Add all handlers + connection.once('close', closeHandler(self)); + connection.once('error', errorHandler(self)); + connection.once('timeout', timeoutHandler(self)); + connection.once('parseError', parseErrorHandler(self)); + connection.on('connect', function(connection) { + // Add the connection to the list of available connections + self.availableConnections.push(connection); + + // Have we finished the initial connection + if(self.availableConnections.length == numberOfConnections) { + // Reserve a monitoring socket + if(self.monitoring) { + self.monitorConnection = self.availableConnections.pop(); + } + + // Done connecting + self.emit("connect", self); + } + }); + + // Start connection + connection.connect(_options); + }); + }, wait); + + // wait for 1 miliseconds before attempting to connect, spacing out connections + wait = wait + 1; + } +} + +var _createConnection = function(self) { + self.options.messageHandler = self.messageHandler; + var connection = new Connection(self.options); + + // Push the connection + self.connectingConnections.push(connection); + + // Handle any errors + var tempErrorHandler = function(err) { + // self.emit('error', err); + } + + // All event handlers + var handlers = ["close", "message", "error", "timeout", "parseError", "connect"]; + + // Handle successful connection + var tempConnectHandler = function() { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 0") + // Destroy all event emitters + handlers.forEach(function(e) { + connection.removeAllListeners(e); + }); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 1") + + // Add the final handlers + connection.once('close', closeHandler(self)); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 3") + connection.once('error', errorHandler(self)); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 4") + connection.once('timeout', timeoutHandler(self)); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 5") + connection.once('parseError', parseErrorHandler(self)); + + // Remove the connection from the connectingConnections + var index = self.connectingConnections.indexOf(connection); + if(index != -1) { + self.connectingConnections.splice(index, 1); + } + + // connection.destroy() + + // Add to queue of new connection + self.newConnections.push(connection); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! tempConnectHandler 8") + // Emit connection to server instance + // alowing it to apply any needed authentication + self.emit('connection', connection); + + // Execute any work waiting + _execute(self)(); + } + + // Add all handlers + connection.once('close', tempErrorHandler); + connection.once('error', tempErrorHandler); + connection.once('timeout', tempErrorHandler); + connection.once('parseError', tempErrorHandler); + connection.once('connect', tempConnectHandler); + + // Start connection + connection.connect(); +} + +var _execute = function(self) { + return function() { + if(self.state == 'DESTROYED') return; + // Already executing, skip + if(self.executing) return; + // Set pool as executing + self.executing = true; + // console.log("----------------------- _execute") + // console.log("----------------------- pool.write _execute 0 :: availableConnections = " + self.availableConnections.length) + // console.log("----------------------- pool.write _execute 0 :: inUseConnections = " + self.inUseConnections.length) + // console.log("----------------------- pool.write _execute 0 :: newConnections = " + self.newConnections.length) + // console.log("----------------------- pool.write _execute 0 :: queue = " + self.queue.length) + + // Total availble connections + var totalConnections = self.availableConnections.length + + self.connectingConnections.length + + self.inUseConnections.length + + self.newConnections.length; + + // Have we not reached the max connection size yet + if(self.availableConnections.length == 0 + && self.connectingConnections.length == 0 + && totalConnections < self.size + && self.queue.length > 0) { + // Create a new connection + _createConnection(self); + // Attempt to execute again + self.executing = false; + return; + } + + // Number of ops to do + var numberOfOps = self.availableConnections.length > self.queue.length + ? self.queue.length : self.availableConnections.length; + + // As long as we have available connections + while(true) { + // No available connections available + if(self.availableConnections.length == 0) break; + if(self.queue.length == 0) break; + + // Get a connection + var connection = self.availableConnections.pop(); + if(connection.isConnected()) { + var workItem = self.queue.shift(); + + // Add connection to callback so we can flush out + // only ops for that connection on a socket closure + if(workItem.cb) { + workItem.cb.connection = connection; + } + + // Get actual binary commands + var buffer = workItem.buffer; + + // Add connection to workers in flight + if(connection !== self.monitorConnection) { + self.inUseConnections.push(connection); + } + + // console.log("---------- write to connection " + connection.id) + + if(Array.isArray(buffer)) { + for(var i = 0; i < buffer.length; i++) { + connection.write(buffer[i]); + } + } else { + connection.write(buffer); + } + + // Fire and forgot message + if(workItem.immediateRelease) { + self.availableConnections.push(connection); + } + } + } + + self.executing = false; + } +} + +/** + * Write a message to MongoDB + * @method + * @return {Connection} + */ +Pool.prototype.write = function(buffer, cb, options) { + // We have a monitoring operation and need to use + // the dedicated connection + if(options && options.monitoring && !this.monitorConnection) { + this.monitorConnection = this.availableConnections.pop(); + } + + if(options && options.monitoring && this.monitorConnection) { + return this.monitorConnection.write(buffer); + } + + // Do we have an operation + var operation = {buffer:buffer, cb: cb}; + // Do we immediately release the connection back to available (fire and forget) + if(options && options.immediateRelease) { + operation.immediateRelease = true; + } + + // Push the operation to the queue of operations in progress + this.queue.push(operation); + // Attempt to write all buffers out + _execute(this)(); +} + +/** + * Make a passed connection available + * @method + * @return {Connection} + */ +Pool.prototype.connectionAvailable = function(connection) { + // console.log("@@@@@@ connectionAvailable :: " + connection.id) + // Get the connection from the newConnections + var index = this.newConnections.indexOf(connection); + if(index != -1) { + this.newConnections.splice(index, 1); + } + + // If it's in the inUseConnections + index = this.inUseConnections.indexOf(connection); + if(index != -1) { + this.inUseConnections.splice(index, 1); + } + + // Add the connection to available connections if it's not a monitoring threads + if(this.availableConnections.indexOf(connection) == -1 + && connection !== this.monitorConnection) { + this.availableConnections.push(connection); + } + + // Fire execute loop + _execute(this)(); +} + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function(options) { + options = options || {}; + + // Set the current index + this.index = this.index + 1; + + // Get all connections + var connections = this.availableConnections.slice(0); + + if(connections.length == 1) { + return connections[0]; + } else { + this.index = this.index % connections.length; + return connections[this.index]; + } +} + +/** + * Reduce the poolSize to the provided max connections value + * @method + * @param {number} maxConnections reduce the poolsize to maxConnections + */ +Pool.prototype.capConnections = function(maxConnections) { + // Do we have more connections than specified slice it + if(this.connections.length > maxConnections) { + // Get the rest of the connections + var connections = this.connections.slice(maxConnections); + // Cap the active connections + this.connections = this.connections.slice(0, maxConnections); + + if (this.index >= maxConnections){ + // Go back to the beggining of the pool if capping connections + this.index = 0; + } + + // Remove all listeners + for(var i = 0; i < connections.length; i++) { + connections[i].removeAllListeners('close'); + connections[i].removeAllListeners('error'); + connections[i].removeAllListeners('timeout'); + connections[i].removeAllListeners('parseError'); + connections[i].removeAllListeners('connect'); + connections[i].destroy(); + } + } +} + +/** + * Get all pool connections + * @method + * @return {array} + */ +Pool.prototype.getAll = function() { + return this.availableConnections + .concat(this.inUseConnections) + .concat(this.connectingConnections) + .concat(this.newConnections); +} + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + // Available connections + for(var i = 0; i < this.availableConnections.length; i++) { + if(this.availableConnections[i].isConnected()) return true; + } + + // inUseConnections + for(var i = 0; i < this.inUseConnections.length; i++) { + if(this.inUseConnections[i].isConnected()) return true; + } + + return this.state == CONNECTED; +} + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state == DESTROYED; +} + + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +module.exports = Pool; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js new file mode 100644 index 0000000..07e4233 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js @@ -0,0 +1,85 @@ +"use strict"; + +// Set property function +var setProperty = function(obj, prop, flag, values) { + Object.defineProperty(obj, prop.name, { + enumerable:true, + set: function(value) { + if(typeof value != 'boolean') throw new Error(f("%s required a boolean", prop.name)); + // Flip the bit to 1 + if(value == true) values.flags |= flag; + // Flip the bit to 0 if it's set, otherwise ignore + if(value == false && (values.flags & flag) == flag) values.flags ^= flag; + prop.value = value; + } + , get: function() { return prop.value; } + }); +} + +// Set property function +var getProperty = function(obj, propName, fieldName, values, func) { + Object.defineProperty(obj, propName, { + enumerable:true, + get: function() { + // Not parsed yet, parse it + if(values[fieldName] == null && obj.isParsed && !obj.isParsed()) { + obj.parse(); + } + + // Do we have a post processing function + if(typeof func == 'function') return func(values[fieldName]); + // Return raw value + return values[fieldName]; + } + }); +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +// Shallow copy +var copy = function(fObj, tObj) { + tObj = tObj || {}; + for(var name in fObj) tObj[name] = fObj[name]; + return tObj; +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) return callback; + var boundCallback = domain.bind(callback); + + // Copy all fields over + for(var name in callback) { + boundCallback[name] = callback[name]; + } + + // Return the bound callback + return boundCallback; +} + +exports.setProperty = setProperty; +exports.getProperty = getProperty; +exports.getSingleProperty = getSingleProperty; +exports.copy = copy; +exports.bindToCurrentDomain = bindToCurrentDomain; +exports.debugOptions = debugOptions; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js new file mode 100644 index 0000000..b435bb3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js @@ -0,0 +1,688 @@ +"use strict"; + +var Long = require('bson').Long + , Logger = require('./connection/logger') + , MongoError = require('./error') + , f = require('util').format; + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * assert.equal(null, err); + * + * // Execute the write + * var cursor = _server.cursor('integration_tests.inserts_example4', { + * find: 'integration_tests.example4' + * , query: {a:1} + * }, { + * readPreference: new ReadPreference('secondary'); + * }); + * + * // Get the first document + * cursor.next(function(err, doc) { + * assert.equal(null, err); + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Cursor, not to be used directly + * @class + * @param {object} bson An instance of the BSON parser + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next + * @param {object} topology The server topology instance. + * @param {object} topologyOptions The server topology options. + * @return {Cursor} A cursor instance + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + options = options || {}; + // Cursor reference + var self = this; + // Initial query + var query = null; + + // Cursor pool + this.pool = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = bson; + this.ns = ns; + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null + , cmd: cmd + , documents: options.documents || [] + , cursorIndex: 0 + , dead: false + , killed: false + , init: false + , notified: false + , limit: options.limit || cmd.limit || 0 + , skip: options.skip || cmd.skip || 0 + , batchSize: options.batchSize || cmd.batchSize || 1000 + , currentLimit: 0 + // Result field name if not a cursor (contains the array of results) + , transforms: options.transforms + } + + // Callback controller + this.callbacks = null; + + // Logger + this.logger = Logger('Cursor', options); + + // + // Did we pass in a cursor id + if(typeof cmd == 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + this.cursorState.lastCursorId = this.cursorState.cursorId; + } else if(cmd instanceof Long) { + this.cursorState.cursorId = cmd; + this.cursorState.lastCursorId = cmd; + } +} + +Cursor.prototype.setCursorBatchSize = function(value) { + this.cursorState.batchSize = value; +} + +Cursor.prototype.cursorBatchSize = function() { + return this.cursorState.batchSize; +} + +Cursor.prototype.setCursorLimit = function(value) { + this.cursorState.limit = value; +} + +Cursor.prototype.cursorLimit = function() { + return this.cursorState.limit; +} + +Cursor.prototype.setCursorSkip = function(value) { + this.cursorState.skip = value; +} + +Cursor.prototype.cursorSkip = function() { + return this.cursorState.skip; +} + +// +// Handle callback (including any exceptions thrown) +var handleCallback = function(callback, err, result) { + try { + callback(err, result); + } catch(err) { + process.nextTick(function() { + throw err; + }); + } +} + +// Internal methods +Cursor.prototype._find = function(callback) { + var self = this; + + if(self.logger.isDebug()) { + self.logger.debug(f("issue initial query [%s] with flags [%s]" + , JSON.stringify(self.cmd) + , JSON.stringify(self.query))); + } + + var queryCallback = function(err, result) { + if(err) return callback(err); + + if(result.queryFailure) { + return callback(MongoError.create(result.documents[0]), null); + } + + // Check if we have a command cursor + if(Array.isArray(result.documents) && result.documents.length == 1 + && (!self.cmd.find || (self.cmd.find && self.cmd.virtual == false)) + && (result.documents[0].cursor != 'string' + || result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || Array.isArray(result.documents[0].result)) + ) { + + // We have a an error document return the error + if(result.documents[0]['$err'] + || result.documents[0]['errmsg']) { + return callback(MongoError.create(result.documents[0]), null); + } + + // We have a cursor document + if(result.documents[0].cursor != null + && typeof result.documents[0].cursor != 'string') { + var id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if(result.documents[0].cursor.ns) { + self.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + self.cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; + self.cursorState.lastCursorId = self.cursorState.cursorId; + // If we have a firstBatch set it + if(Array.isArray(result.documents[0].cursor.firstBatch)) { + self.cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); + } + + // Return after processing command cursor + return callback(null, null); + } + + if(Array.isArray(result.documents[0].result)) { + self.cursorState.documents = result.documents[0].result; + self.cursorState.cursorId = Long.ZERO; + return callback(null, null); + } + } + + // Otherwise fall back to regular find path + self.cursorState.cursorId = result.cursorId; + self.cursorState.documents = result.documents; + self.cursorState.lastCursorId = result.cursorId; + + // Transform the results with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.query == 'function') { + self.cursorState.documents = self.cursorState.transforms.query(result); + } + + // Return callback + callback(null, null); + } + + // If we have a raw query decorate the function + if(self.options.raw || self.cmd.raw) { + queryCallback.raw = self.options.raw || self.cmd.raw; + } + + // Do we have documentsReturnedIn set on the query + if(typeof self.query.documentsReturnedIn == 'string') { + queryCallback.documentsReturnedIn = self.query.documentsReturnedIn; + } + + // Set up callback + self.callbacks.register(self.query.requestId, queryCallback); + + // Write the initial command out + self.pool.write(self.query.toBin(), queryCallback); +} + +Cursor.prototype._getmore = function(callback) { + if(this.logger.isDebug()) this.logger.debug(f("schedule getMore call for query [%s]", JSON.stringify(this.query))) + // Determine if it's a raw query + var raw = this.options.raw || this.cmd.raw; + + // Set the current batchSize + var batchSize = this.cursorState.batchSize; + if(this.cursorState.limit > 0 + && ((this.cursorState.currentLimit + batchSize) > this.cursorState.limit)) { + batchSize = this.cursorState.limit - this.cursorState.currentLimit; + } + + // We have a wire protocol handler + this.server.wireProtocolHandler.getMore(this.bson, this.ns, this.cursorState, batchSize, raw, this.pool, this.callbacks, this.options, callback); +} + +Cursor.prototype._killcursor = function(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if(this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init == false) { + if(callback) callback(null, null); + return; + } + + // Execute command + this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState.cursorId, this.pool, this.callbacks, callback); +} + +/** + * Clone the cursor + * @method + * @return {Cursor} + */ +Cursor.prototype.clone = function() { + return this.topology.cursor(this.ns, this.cmd, this.options); +} + +/** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ +Cursor.prototype.isDead = function() { + return this.cursorState.dead == true; +} + +/** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ +Cursor.prototype.isKilled = function() { + return this.cursorState.killed == true; +} + +/** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ +Cursor.prototype.isNotified = function() { + return this.cursorState.notified == true; +} + +/** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ +Cursor.prototype.bufferedCount = function() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; +} + +/** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ +Cursor.prototype.readBufferedDocuments = function(number) { + var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + var elements = this.cursorState.documents.slice(this.cursorState.cursorIndex, this.cursorState.cursorIndex + length); + + // Transform the doc with passed in transformation method if provided + if(this.cursorState.transforms && typeof this.cursorState.transforms.doc == 'function') { + // Transform all the elements + for(var i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if(this.cursorState.limit > 0 && (this.cursorState.currentLimit + elements.length) > this.cursorState.limit) { + elements = elements.slice(0, (this.cursorState.limit - this.cursorState.currentLimit)); + this.kill(); + } + + // Adjust current limit + this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; + + // Return elements + return elements; +} + +/** + * Kill the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.kill = function(callback) { + this._killcursor(callback); +} + +/** + * Resets the cursor + * @method + * @return {null} + */ +Cursor.prototype.rewind = function() { + if(this.cursorState.init) { + if(!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } +} + +/** + * Validate if the pool is dead and return error + */ +var isConnectionDead = function(self, callback) { + if(self.pool + && !self.pool.isConnected()) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + callback(MongoError.create(f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port))) + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +var isCursorDeadButNotkilled = function(self, callback) { + // Cursor is dead but not marked killed, return null + if(self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +var isCursorDeadAndKilled = function(self, callback) { + if(self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, MongoError.create("cursor is dead")); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +var isCursorKilled = function(self, callback) { + if(self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +var setCursorDeadAndNotified = function(self, callback) { + self.cursorState.dead = true; + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +/** + * Mark cursor as being notified + */ +var setCursorNotified = function(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +var push = Array.prototype.push; + +var nextFunction = function(self, callback) { + // Exhaust message and cursor already finished and notified + if(self.cmd.exhaust && self.cursorState.notified) return; + // We have notified about it + if(self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if(isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if(isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if(isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if(!self.cursorState.init) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.topology.isConnected(self.options) && self.disconnectHandler != null) { + return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); + } + + try { + // Get a server + self.server = self.topology.getServer(self.options); + // Get a connection + self.pool = self.server.s.pool; + // Get the callbacks + self.callbacks = self.server.getCallbacks(); + } catch(err) { + return callback(err); + } + + // Set as init + self.cursorState.init = true; + + try { + // Get the right wire protocol command + self.query = self.server.wireProtocolHandler.command(self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options); + } catch(err) { + return callback(err); + } + } + + // Process exhaust messages + var processExhaustMessages = function(err, result) { + if(err) { + self.cursorState.dead = true; + self.callbacks.unregister(self.query.requestId); + return callback(err); + } + + // Concatenate all the documents + push.apply(self.cursorState.documents, result.documents); + + // If we have no documents left + if(Long.ZERO.equals(result.cursorId)) { + self.cursorState.cursorId = Long.ZERO; + self.callbacks.unregister(self.query.requestId); + return nextFunction(self, callback); + } + + // Set up next listener + self.callbacks.register(result.requestId, processExhaustMessages) + + // Initial result + if(self.cursorState.cursorId == null) { + self.cursorState.cursorId = result.cursorId; + self.cursorState.lastCursorId = result.cursorId; + nextFunction(self, callback); + } + } + + // If we have exhaust + if(self.cmd.exhaust && self.cursorState.cursorId == null) { + // Handle all the exhaust responses + self.callbacks.register(self.query.requestId, processExhaustMessages); + // Write the initial command out + return self.pool.write(self.query.toBin(), processExhaustMessages); + } else if(self.cmd.exhaust && self.cursorState.cursorIndex < self.cursorState.documents.length) { + return handleCallback(callback, null, self.cursorState.documents[self.cursorState.cursorIndex++]); + } else if(self.cmd.exhaust && Long.ZERO.equals(self.cursorState.cursorId)) { + self.callbacks.unregister(self.query.requestId); + return setCursorNotified(self, callback); + } else if(self.cmd.exhaust) { + return setTimeout(function() { + if(Long.ZERO.equals(self.cursorState.cursorId)) return; + nextFunction(self, callback); + }, 1); + } + + // If we don't have a cursorId execute the first query + if(self.cursorState.cursorId == null) { + // Check if pool is dead and return if not possible to + // execute the query against the db + if(isConnectionDead(self, callback)) return; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); + + // query, cmd, options, cursorState, callback + self._find(function(err, r) { + if(err) return handleCallback(callback, err, null); + if(self.cursorState.documents.length == 0 && !self.cmd.tailable && !self.cmd.awaitData) { + return setCursorNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } else if(self.cursorState.cursorIndex == self.cursorState.documents.length + && !Long.ZERO.equals(self.cursorState.cursorId)) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); + + // Check if connection is dead and return if not possible to + // execute a getmore on this connection + if(isConnectionDead(self, callback)) return; + + // Execute the next get more + self._getmore(function(err, doc) { + if(err) return handleCallback(callback, err); + if(self.cursorState.documents.length == 0 + && Long.ZERO.equals(self.cursorState.cursorId) && !self.cmd.tailable) { + self.cursorState.dead = true; + // Finished iterating over the cursor + return setCursorDeadAndNotified(self, callback); + } + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if(self.cursorState.documents.length == 0 && self.cmd.tailable) { + return handleCallback(callback, MongoError.create({ + message: "No more documents in tailed cursor" + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } + + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && self.cmd.tailable) { + return handleCallback(callback, MongoError.create({ + message: "No more documents in tailed cursor" + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && Long.ZERO.equals(self.cursorState.cursorId)) { + setCursorDeadAndNotified(self, callback); + } else { + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Doc overflow + if(doc.$err) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, function() { + handleCallback(callback, new MongoError(doc.$err)); + }); + } + + // Transform the doc with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +} + +/** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.next = function(callback) { + nextFunction(this, callback); +} + +module.exports = Cursor; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js new file mode 100644 index 0000000..4e17ef3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js @@ -0,0 +1,44 @@ +"use strict"; + +/** + * Creates a new MongoError + * @class + * @augments Error + * @param {string} message The error message + * @return {MongoError} A MongoError instance + */ +function MongoError(message) { + this.name = 'MongoError'; + this.message = message; + Error.captureStackTrace(this, MongoError); +} + +/** + * Creates a new MongoError object + * @method + * @param {object} options The error options + * @return {MongoError} A MongoError instance + */ +MongoError.create = function(options) { + var err = null; + + if(options instanceof Error) { + err = new MongoError(options.message); + err.stack = options.stack; + } else if(typeof options == 'string') { + err = new MongoError(options); + } else { + err = new MongoError(options.message || options.errmsg || options.$err || "n/a"); + // Other options + for(var name in options) { + err[name] = options[name]; + } + } + + return err; +} + +// Extend JavaScript error +MongoError.prototype = new Error; + +module.exports = MongoError; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js new file mode 100644 index 0000000..dcceda4 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js @@ -0,0 +1,59 @@ +var fs = require('fs'); + +/* Note: because this plugin uses process.on('uncaughtException'), only one + * of these can exist at any given time. This plugin and anything else that + * uses process.on('uncaughtException') will conflict. */ +exports.attachToRunner = function(runner, outputFile) { + var smokeOutput = { results : [] }; + var runningTests = {}; + + var integraPlugin = { + beforeTest: function(test, callback) { + test.startTime = Date.now(); + runningTests[test.name] = test; + callback(); + }, + afterTest: function(test, callback) { + smokeOutput.results.push({ + status: test.status, + start: test.startTime, + end: Date.now(), + test_file: test.name, + exit_code: 0, + url: "" + }); + delete runningTests[test.name]; + callback(); + }, + beforeExit: function(obj, callback) { + fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { + callback(); + }); + } + }; + + // In case of exception, make sure we write file + process.on('uncaughtException', function(err) { + // Mark all currently running tests as failed + for (var testName in runningTests) { + smokeOutput.results.push({ + status: "fail", + start: runningTests[testName].startTime, + end: Date.now(), + test_file: testName, + exit_code: 0, + url: "" + }); + } + + // write file + fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); + + // Standard NodeJS uncaught exception handler + console.error(err.stack); + process.exit(1); + }); + + runner.plugin(integraPlugin); + return integraPlugin; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js new file mode 100644 index 0000000..ff7bf1b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js @@ -0,0 +1,37 @@ +"use strict"; + +var setProperty = require('../connection/utils').setProperty + , getProperty = require('../connection/utils').getProperty + , getSingleProperty = require('../connection/utils').getSingleProperty; + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection) { + this.result = result; + this.connection = connection; +} + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + return this.result; +} + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +} + +module.exports = CommandResult; \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js new file mode 100644 index 0000000..bd926e7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js @@ -0,0 +1,1056 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , b = require('bson') + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , EventEmitter = require('events').EventEmitter + , BasicCursor = require('../cursor') + , BSON = require('bson').native().BSON + , BasicCursor = require('../cursor') + , Server = require('./server') + , MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram') + , Logger = require('../connection/logger') + , ReadPreference = require('./read_preference') + , Session = require('./session') + , MongoError = require('../error'); + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * @example + * var Mongos = require('mongodb-core').Mongos + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Mongos([{host: 'localhost', port: 30000}]); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; + +// Instance id +var mongosId = 0; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +var State = function(readPreferenceStrategies, localThresholdMS) { + // Internal state + this.s = { + connectedServers: [] + , disconnectedServers: [] + , readPreferenceStrategies: readPreferenceStrategies + , lowerBoundLatency: Number.MAX_VALUE + , localThresholdMS: localThresholdMS + , index: 0 + } +} + +// +// A Mongos connected +State.prototype.connected = function(server) { + // Locate in disconnected servers and remove + this.s.disconnectedServers = this.s.disconnectedServers.filter(function(s) { + return !s.equals(server); + }); + + var found = false; + // Check if the server exists + this.s.connectedServers.forEach(function(s) { + if(s.equals(server)) found = true; + }); + + // Add to disconnected list if it does not already exist + if(!found) this.s.connectedServers.push(server); + + // Adjust lower bound + if(this.s.lowerBoundLatency > server.s.isMasterLatencyMS) { + this.s.lowerBoundLatency = server.s.isMasterLatencyMS; + } +} + +// +// A Mongos disconnected +State.prototype.disconnected = function(server) { + // Locate in disconnected servers and remove + this.s.connectedServers = this.s.connectedServers.filter(function(s) { + return !s.equals(server); + }); + + var found = false; + // Check if the server exists + this.s.disconnectedServers.forEach(function(s) { + if(s.equals(server)) found = true; + }); + + // Add to disconnected list if it does not already exist + if(!found) this.s.disconnectedServers.push(server); +} + +// +// Return the list of disconnected servers +State.prototype.disconnectedServers = function() { + return this.s.disconnectedServers.slice(0); +} + +// +// Get connectedServers +State.prototype.connectedServers = function() { + return this.s.connectedServers.slice(0) +} + +// +// Get all servers +State.prototype.getAll = function() { + return this.s.connectedServers.slice(0).concat(this.s.disconnectedServers); +} + +// +// Get all connections +State.prototype.getAllConnections = function() { + var connections = []; + + this.s.connectedServers.forEach(function(e) { + connections = connections.concat(e.connections()); + }); + return connections; +} + +// +// Destroy the state +State.prototype.destroy = function() { + // Destroy any connected servers + while(this.s.connectedServers.length > 0) { + var server = this.s.connectedServers.shift(); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Server destroy + server.destroy(); + // Add to list of disconnected servers + this.s.disconnectedServers.push(server); + } +} + +// +// Are we connected +State.prototype.isConnected = function() { + return this.s.connectedServers.length > 0; +} + +// +// Pick a server +State.prototype.pickServer = function(readPreference) { + var self = this; + readPreference = readPreference || ReadPreference.primary; + + // Filter out the possible servers + var servers = this.s.connectedServers.filter(function(server) { + if((server.s.isMasterLatencyMS <= (self.s.lowerBoundLatency + self.s.localThresholdMS)) + && server.isConnected()) { + return true; + } + }); + + // Do we have a custom readPreference strategy, use it + if(this.s.readPreferenceStrategies != null && this.s.readPreferenceStrategies[readPreference] != null) { + return this.s.readPreferenceStrategies[readPreference].pickServer(servers, readPreference); + } + + // No valid connections + if(servers.length == 0) throw new MongoError("no mongos proxy available"); + + // Update index + this.s.index = (this.s.index + 1) % servers.length; + + // Pick first one + return servers[this.s.index]; +} + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.reconnectTries=30] Reconnect retries for HA if no servers available + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#joined + * @fires Mongos#left + */ +var Mongos = function(seedlist, options) { + var self = this; + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // BSON Parser, ensure we have a single instance + bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; + // Pick the right bson parser + var bson = options.bson ? options.bson : bsonInstance; + // Add bson parser to options + options.bson = bson; + + // The Mongos state + this.s = { + // Seed list for sharding passed in + seedlist: seedlist + // Passed in options + , options: options + // Logger + , logger: Logger('Mongos', options) + // Reconnect tries + , reconnectTries: options.reconnectTries || 30 + // Ha interval + , haInterval: options.haInterval || 5000 + // localThresholdMS + , localThresholdMS: options.localThresholdMS || 15 + // Have omitted fullsetup + , fullsetup: false + // Cursor factory + , Cursor: options.cursorFactory || BasicCursor + // Current credentials used for auth + , credentials: [] + // BSON Parser + , bsonInstance: bsonInstance + , bson: bson + // Pings + , pings: {} + // Default state + , state: DISCONNECTED + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Contains any alternate strategies for picking + , readPreferenceStrategies: {} + // Auth providers + , authProviders: {} + // Unique instance id + , id: mongosId++ + // Authentication in progress + , authInProgress: false + // Servers added while auth in progress + , authInProgressServers: [] + // Current retries left + , retriesLeft: options.reconnectTries || 30 + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + } + + // Set up the connection timeout for the options + options.connectionTimeout = options.connectionTimeout || 1000; + + // Create a new state for the mongos + this.s.mongosState = new State(this.s.readPreferenceStrategies, this.s.localThresholdMS); + + // Add the authentication mechanisms + this.addAuthProvider('mongocr', new MongoCR()); + this.addAuthProvider('x509', new X509()); + this.addAuthProvider('plain', new Plain()); + this.addAuthProvider('gssapi', new GSSAPI()); + this.addAuthProvider('sspi', new SSPI()); + this.addAuthProvider('scram-sha-1', new ScramSHA1()); + + // BSON property (find a server and pass it along) + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + var servers = self.s.mongosState.getAll(); + return servers.length > 0 ? servers[0].bson : null; + } + }); + + Object.defineProperty(this, 'id', { + enumerable:true, get: function() { return self.s.id; } + }); + + Object.defineProperty(this, 'type', { + enumerable:true, get: function() { return 'mongos'; } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.haInterval; } + }); + + Object.defineProperty(this, 'state', { + enumerable:true, get: function() { return self.s.mongosState; } + }); +} + +inherits(Mongos, EventEmitter); + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +Mongos.prototype.parserType = function() { + if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +Mongos.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + var connectedServers = this.s.mongosState.connectedServers(); + if(connectedServers.length > 0) return connectedServers[0].lastIsMaster(); + return null; +} + +/** + * Initiate server connect + * @method + */ +Mongos.prototype.connect = function(_options) { + var self = this; + // Start replicaset inquiry process + setTimeout(mongosInquirer(self, self.s), self.s.haInterval); + // Additional options + if(_options) for(var name in _options) self.s.options[name] = _options[name]; + // For all entries in the seedlist build a server instance + self.s.seedlist.forEach(function(e) { + // Clone options + var opts = cloneOptions(self.s.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = self.s.readPreferenceStrategies; + // Share the auth store + opts.authProviders = self.s.authProviders; + // Don't emit errors + opts.emitError = true; + // Create a new Server + self.s.mongosState.disconnected(new Server(opts)); + }); + + // Get the disconnected servers + var servers = self.s.mongosState.disconnectedServers(); + + // Set connecting state + this.s.state = CONNECTING; + + // Attempt to connect to all the servers + while(servers.length > 0) { + // Get the server + var server = servers.shift(); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // Set up the event handlers + server.once('error', errorHandlerTemp(self, self.s, server)); + server.once('close', errorHandlerTemp(self, self.s, server)); + server.once('timeout', errorHandlerTemp(self, self.s, server)); + server.once('parseError', errorHandlerTemp(self, self.s, server)); + server.once('connect', connectHandler(self, self.s, 'connect')); + + if(self.s.logger.isInfo()) self.s.logger.info(f('connecting to server %s', server.name)); + // Attempt to connect + server.connect(); + } +} + +/** + * Destroy the server connection + * @method + */ +Mongos.prototype.destroy = function(emitClose) { + this.s.state = DESTROYED; + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + // Destroy the state + this.s.mongosState.destroy(); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.s.mongosState.isConnected(); +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.s.state == DESTROYED; +} + +// +// Operations +// + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'update', ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'remove', ns, ops, options, callback); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + var server = null; + // Ensure we have no options + options = options || {}; + + // We need to execute the command on all servers + if(options.onAll) { + var servers = self.s.mongosState.getAll(); + var count = servers.length; + var cmdErr = null; + + for(var i = 0; i < servers.length; i++) { + servers[i].command(ns, cmd, options, function(err, r) { + count = count - 1; + // Finished executing command + if(count == 0) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // Return the error + callback(err, r); + } + }); + } + + return; + } + + + try { + // Get a primary + server = self.s.mongosState.pickServer(options.writeConcern ? ReadPreference.primary : options.readPreference); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no mongos found")); + server.command(ns, cmd, options, function(err, r) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + callback(err, r); + }); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // Authenticate against all the servers + var servers = this.s.mongosState.connectedServers().slice(0); + var count = servers.length; + // Correct authentication + var authenticated = true; + var authErr = null; + // Set auth in progress + this.s.authInProgress = true; + + // Authenticate against all servers + while(servers.length > 0) { + var server = servers.shift(); + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err, r) { + count = count - 1; + if(err) authErr = err; + if(!r) authenticated = false; + + // We are done + if(count == 0) { + // We have more servers that are not authenticated, let's authenticate + if(self.s.authInProgressServers.length > 0) { + self.s.authInProgressServers = []; + return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); + } + + // Auth is done + self.s.authInProgress = false; + // Add successful credentials + if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); + // Return the auth error + if(authErr) return callback(authErr, false); + // Successfully authenticated session + callback(null, new Session({}, self)); + } + }]); + + // Execute the auth + server.auth.apply(server, finalArguments); + } +} + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +Mongos.prototype.addReadPreferenceStrategy = function(name, strategy) { + if(this.s.readPreferenceStrategies == null) this.s.readPreferenceStrategies = {}; + this.s.readPreferenceStrategies[name] = strategy; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +Mongos.prototype.addAuthProvider = function(name, provider) { + this.s.authProviders[name] = provider; +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +Mongos.prototype.getConnection = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + var server = this.s.mongosState.pickServer(options.readPreference); + if(server == null) return null; + // Return connection + return server.getConnection(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Mongos.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + return this.s.mongosState.pickServer(options.readPreference); +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + return this.s.mongosState.getAllConnections(); +} + +// +// Inquires about state changes +// +var mongosInquirer = function(self, state) { + return function() { + if(state.state == DESTROYED) return + if(state.state == CONNECTED) state.retriesLeft = state.reconnectTries; + + // If we have a disconnected site + if(state.state == DISCONNECTED && state.retriesLeft == 0) { + self.destroy(); + return self.emit('error', new MongoError(f('failed to reconnect after %s', state.reconnectTries))); + } else if(state == DISCONNECTED) { + state.retriesLeft = state.retriesLeft - 1; + } + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(state.mongosState.isConnected() && state.disconnectHandler) { + state.disconnectHandler.execute(); + } + + // Log the information + if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess running')); + + // Let's query any disconnected proxies + var disconnectedServers = state.mongosState.disconnectedServers(); + if(disconnectedServers.length == 0) return setTimeout(mongosInquirer(self, state), state.haInterval); + + // Count of connections waiting to be connected + var connectionCount = disconnectedServers.length; + if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess found %d disconnected proxies', connectionCount)); + + // Let's attempt to reconnect + while(disconnectedServers.length > 0) { + // Connect to proxy + var connectToProxy = function(_server) { + setTimeout(function() { + var events = ['error', 'close', 'timeout', 'connect', 'message', 'parseError']; + // Remove any listeners + events.forEach(function(e) { + _server.removeAllListeners(e); + }); + + // Set up the event handlers + _server.once('error', errorHandlerTemp(self, state, server)); + _server.once('close', errorHandlerTemp(self, state, server)); + _server.once('timeout', errorHandlerTemp(self, state, server)); + _server.once('connect', connectHandler(self, state, 'ha')); + // Start connect + _server.connect(); + }, 1); + } + + var server = disconnectedServers.shift(); + if(state.logger.isDebug()) state.logger.debug(f('attempting to connect to server %s', server.name)); + connectToProxy(server); + } + + // Let's keep monitoring but wait for possible timeout to happen + return setTimeout(mongosInquirer(self, state), state.options.connectionTimeout + state.haInterval); + } +} + +// +// Error handler for initial connect +var errorHandlerTemp = function(self, state, server) { + return function(err, server) { + // Log the information + if(state.logger.isInfo()) state.logger.info(f('server %s disconnected with error %s', server.name, JSON.stringify(err))); + + // Signal disconnect of server + state.mongosState.disconnected(server); + + // Remove any non used handlers + var events = ['error', 'close', 'timeout', 'connect']; + events.forEach(function(e) { + server.removeAllListeners(e); + }) + } +} + +// +// Handlers +var errorHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', server.name, JSON.stringify(err))); + state.mongosState.disconnected(server); + // No more servers left emit close + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + if(state.emitError) self.emit('error', err, server); + } +} + +var timeoutHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s timed out', server.name)); + state.mongosState.disconnected(server); + + // No more servers emit close event if no entries left + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + } +} + +var closeHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s closed', server.name)); + state.mongosState.disconnected(server); + + // No more servers left emit close + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + } +} + +// Connect handler +var connectHandler = function(self, state, e) { + return function(server) { + if(state.logger.isInfo()) state.logger.info(f('connected to %s', server.name)); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // finish processing the server + var processNewServer = function(_server) { + // Add the server handling code + if(_server.isConnected()) { + _server.once('error', errorHandler(self, state)); + _server.once('close', closeHandler(self, state)); + _server.once('timeout', timeoutHandler(self, state)); + _server.once('parseError', timeoutHandler(self, state)); + } + + // Emit joined event + self.emit('joined', 'mongos', _server); + + // Add to list connected servers + state.mongosState.connected(_server); + + // Do we have a reconnect event + if('ha' == e && state.mongosState.connectedServers().length == 1) { + self.emit('reconnect', _server); + } + + // Full setup + if(state.mongosState.disconnectedServers().length == 0 && + state.mongosState.connectedServers().length > 0 && + !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup'); + } + + // all connected + if(state.mongosState.disconnectedServers().length == 0 && + state.mongosState.connectedServers().length == state.seedlist.length && + !state.all) { + state.all = true; + self.emit('all'); + } + + // Set connected + if(state.state == DISCONNECTED) { + state.state = CONNECTED; + self.emit('reconnect', self); + } else if(state.state == CONNECTING) { + state.state = CONNECTED; + self.emit('connect', self); + } + } + + // Is there an authentication process ongoing + if(state.authInProgress) { + state.authInProgressServers.push(server); + } + + // No credentials just process server + if(state.credentials.length == 0) return processNewServer(server); + + // Do we have credentials, let's apply them all + var count = state.credentials.length; + // Apply the credentials + for(var i = 0; i < state.credentials.length; i++) { + server.auth.apply(server, state.credentials[i].concat([function(err, r) { + count = count - 1; + if(count == 0) processNewServer(server); + }])); + } + } +} + +// +// Add server to the list if it does not exist +var addToListIfNotExist = function(list, server) { + var found = false; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Check if the server already exists + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) found = true; + } + + if(!found) { + list.push(server); + } +} + +// Add the new credential for a db, removing the old +// credential from the cache +var addCredentials = function(state, db, argsWithoutCallback) { + // Remove any credentials for the db + clearCredentials(state, db + ".dummy"); + // Add new credentials to list + state.credentials.push(argsWithoutCallback); +} + +// Clear out credentials for a namespace +var clearCredentials = function(state, ns) { + var db = ns.split('.')[0]; + var filteredCredentials = []; + + // Filter out all credentials for the db the user is logging out off + for(var i = 0; i < state.credentials.length; i++) { + if(state.credentials[i][1] != db) filteredCredentials.push(state.credentials[i]); + } + + // Set new list of credentials + state.credentials = filteredCredentials; +} + +var processReadPreference = function(cmd, options) { + options = options || {} + // No read preference specified + if(options.readPreference == null) return cmd; +} + +// +// Execute write operation +var executeWriteOperation = function(state, op, ns, ops, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + var server = null; + // Ensure we have no options + options = options || {}; + try { + // Get a primary + server = state.mongosState.pickServer(); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no mongos found")); + // Execute the command + server[op](ns, ops, options, callback); +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +module.exports = Mongos; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js new file mode 100644 index 0000000..913ca1b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js @@ -0,0 +1,106 @@ +"use strict"; + +var needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * var cursor = server.cursor('db.test' + * , {find: 'db.test', query: {}} + * , {readPreference: new ReadPreference('secondary')}); + * cursor.next(function(err, doc) { + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Pool instance + * @class + * @param {string} preference A string describing the preference (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {object} tags The tags object + * @param {object} [options] Additional read preference options + * @property {string} preference The preference string (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @property {object} tags The tags object + * @property {object} options Additional read preference options + * @return {ReadPreference} + */ +var ReadPreference = function(preference, tags, options) { + this.preference = preference; + this.tags = tags; + this.options = options; +} + +/** + * This needs slaveOk bit set + * @method + * @return {boolean} + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.preference) != -1; +} + +/** + * Are the two read preference equal + * @method + * @return {boolean} + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.preference == this.preference; +} + +/** + * Return JSON representation + * @method + * @return {Object} + */ +ReadPreference.prototype.toJSON = function() { + var readPreference = {mode: this.preference}; + if(Array.isArray(this.tags)) readPreference.tags = this.tags; + return readPreference; +} + +/** + * Primary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js new file mode 100644 index 0000000..5f74546 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js @@ -0,0 +1,1562 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , b = require('bson') + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , debugOptions = require('../connection/utils').debugOptions + , EventEmitter = require('events').EventEmitter + , Server = require('./server') + , ReadPreference = require('./read_preference') + , MongoError = require('../error') + , Ping = require('./strategies/ping') + , Session = require('./session') + , BasicCursor = require('../cursor') + , BSON = require('bson').native().BSON + , State = require('./replset_state') + , MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram') + , Logger = require('../connection/logger'); + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connecctions. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// +// ReplSet instance id +var replSetId = 1; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + // Clone the options + options = cloneOptions(options); + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // Add event listener + EventEmitter.call(this); + + // Set the bson instance + bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; + + // Internal state hash for the object + this.s = { + options: options + // Logger instance + , logger: Logger('ReplSet', options) + // Uniquely identify the replicaset instance + , id: replSetId++ + // Index + , index: 0 + // Ha Index + , haId: 0 + // Current credentials used for auth + , credentials: [] + // Factory overrides + , Cursor: options.cursorFactory || BasicCursor + // BSON Parser, ensure we have a single instance + , bsonInstance: bsonInstance + // Pick the right bson parser + , bson: options.bson ? options.bson : bsonInstance + // Special replicaset options + , secondaryOnlyConnectionAllowed: typeof options.secondaryOnlyConnectionAllowed == 'boolean' + ? options.secondaryOnlyConnectionAllowed : false + , haInterval: options.haInterval || 10000 + // Are we running in debug mode + , debug: typeof options.debug == 'boolean' ? options.debug : false + // The replicaset name + , setName: options.setName + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Grouping tag used for debugging purposes + , tag: options.tag + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + // Currently connecting servers + , connectingServers: {} + // Contains any alternate strategies for picking + , readPreferenceStrategies: {} + // Auth providers + , authProviders: {} + // All the servers + , disconnectedServers: [] + // Initial connection servers + , initialConnectionServers: [] + // High availability process running + , highAvailabilityProcessRunning: false + // Full setup + , fullsetup: false + // All servers accounted for (used for testing) + , all: false + // Seedlist + , seedlist: seedlist + // Authentication in progress + , authInProgress: false + // Servers added while auth in progress + , authInProgressServers: [] + // Minimum heartbeat frequency used if we detect a server close + , minHeartbeatFrequencyMS: 500 + // stores high availability timer to allow efficient destroy + , haTimer : null + } + + // Add bson parser to options + options.bson = this.s.bson; + // Set up the connection timeout for the options + options.connectionTimeout = options.connectionTimeout || 10000; + + // Replicaset state + var replState = new State(this, { + id: this.s.id, setName: this.s.setName + , connectingServers: this.s.connectingServers + , secondaryOnlyConnectionAllowed: this.s.secondaryOnlyConnectionAllowed + }); + + // Add Replicaset state to our internal state + this.s.replState = replState; + + // Add the authentication mechanisms + this.addAuthProvider('mongocr', new MongoCR()); + this.addAuthProvider('x509', new X509()); + this.addAuthProvider('plain', new Plain()); + this.addAuthProvider('gssapi', new GSSAPI()); + this.addAuthProvider('sspi', new SSPI()); + this.addAuthProvider('scram-sha-1', new ScramSHA1()); + + // BSON property (find a server and pass it along) + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + var servers = self.s.replState.getAll(); + return servers.length > 0 ? servers[0].bson : null; + } + }); + + Object.defineProperty(this, 'id', { + enumerable:true, get: function() { return self.s.id; } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.haInterval; } + }); + + Object.defineProperty(this, 'state', { + enumerable:true, get: function() { return self.s.replState; } + }); + + // + // Debug options + if(self.s.debug) { + // Add access to the read Preference Strategies + Object.defineProperty(this, 'readPreferenceStrategies', { + enumerable: true, get: function() { return self.s.readPreferenceStrategies; } + }); + } + + Object.defineProperty(this, 'type', { + enumerable:true, get: function() { return 'replset'; } + }); + + // Add the ping strategy for nearest + this.addReadPreferenceStrategy('nearest', new Ping(options)); +} + +inherits(ReplSet, EventEmitter); + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +ReplSet.prototype.addReadPreferenceStrategy = function(name, func) { + this.s.readPreferenceStrategies[name] = func; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +ReplSet.prototype.addAuthProvider = function(name, provider) { + if(this.s.authProviders == null) this.s.authProviders = {}; + this.s.authProviders[name] = provider; +} + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +ReplSet.prototype.parserType = function() { + if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +ReplSet.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + return this.s.replState.lastIsMaster(); +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +ReplSet.prototype.getConnection = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + var server = pickServer(this, this.s, options.readPreference); + if(server == null) return null; + // Return connection + return server.getConnection(); +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + return this.s.replState.getAllConnections(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +ReplSet.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + return pickServer(this, this.s, options.readPreference); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +// +// Execute write operation +var executeWriteOperation = function(self, op, ns, ops, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + var server = null; + // Ensure we have no options + options = options || {}; + // Get a primary + try { + server = pickServer(self, self.s, ReadPreference.primary); + if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no server found")); + + // Handler + var handler = function(err, r) { + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); + // Return the result + callback(err, r); + } + + // Add operationId if existing + if(callback.operationId) handler.operationId = callback.operationId; + // Execute the command + server[op](ns, ops, options, handler); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + var server = null; + var self = this; + // Ensure we have no options + options = options || {}; + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected(options) && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // We need to execute the command on all servers + if(options.onAll) { + var servers = this.s.replState.getAll(); + var count = servers.length; + var cmdErr = null; + + for(var i = 0; i < servers.length; i++) { + servers[i].command(ns, cmd, options, function(err, r) { + count = count - 1; + // Finished executing command + if(count == 0) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); + // Return the error + callback(err, r); + } + }); + } + + return; + } + + // Pick the right server based on readPreference + try { + server = pickServer(self, self.s, options.writeConcern ? ReadPreference.primary : options.readPreference); + if(self.s.debug) self.emit('pickedServer', options.writeConcern ? ReadPreference.primary : options.readPreference, server); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no server found")); + // Execute the command + server.command(ns, cmd, options, function(err, r) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) { + replicasetInquirer(self, self.s, true)(); + } + // Return the error + callback(err, r); + }); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + executeWriteOperation(this, 'remove', ns, ops, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + executeWriteOperation(this, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + executeWriteOperation(this, 'update', ns, ops, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(mechanism, db) { + // console.log("=========================== REPLSET.auth") + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.s.authProviders[mechanism] == null && mechanism != 'default') { + throw new MongoError(f("auth provider %s does not exist", mechanism)); + } + + // Authenticate against all the servers + var servers = this.s.replState.getAll().slice(0); + var count = servers.length; + // Correct authentication + var authenticated = true; + var authErr = null; + // Set auth in progress + this.s.authInProgress = true; + + // Authenticate against all servers + while(servers.length > 0) { + var server = servers.shift(); + + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err, r) { + count = count - 1; + if(err) authErr = err; + if(!r) authenticated = false; + + // We are done + if(count == 0) { + // We have more servers that are not authenticated, let's authenticate + if(self.s.authInProgressServers.length > 0) { + self.s.authInProgressServers = []; + return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); + } + + // Auth is done + self.s.authInProgress = false; + // Add successful credentials + if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); + // Return the auth error + if(authErr) return callback(authErr, false); + // Successfully authenticated session + callback(null, new Session({}, self)); + } + }]); + + // Execute the auth + server.auth.apply(server, finalArguments); + } +} + +ReplSet.prototype.state = function() { + return this.s.replState.state; +} + +/** + * Ensure single socket connections to arbiters and hidden servers + * @method + */ +var handleIsmaster = function(self) { + return function(ismaster, _server) { + if(ismaster.arbiterOnly) { + _server.s.options.size = 1; + } else if(ismaster.hidden) { + _server.s.options.size = 1; + } + } +} + +/** + * Initiate server connect + * @method + */ +ReplSet.prototype.connect = function(_options) { + var self = this; + // Start replicaset inquiry process + setHaTimer(self, self.s); + // Additional options + if(_options) for(var name in _options) this.s.options[name] = _options[name]; + + // Set the state as connecting + this.s.replState.state = CONNECTING; + + // No fullsetup reached + this.s.fullsetup = false; + + // For all entries in the seedlist build a server instance + this.s.seedlist.forEach(function(e) { + // Clone options + var opts = cloneOptions(self.s.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = self.s.readPreferenceStrategies; + opts.emitError = true; + // Add a reserved connection for monitoring + opts.size = opts.size + 1; + opts.monitoring = true; + // Set up tags if any + if(self.s.tag) opts.tag = self.s.tag; + // Share the auth store + opts.authProviders = self.s.authProviders; + // Create a new Server + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + // Add to list of disconnected servers + self.s.disconnectedServers.push(server); + // Add to list of inflight Connections + self.s.initialConnectionServers.push(server); + }); + + // Attempt to connect to all the servers + while(this.s.disconnectedServers.length > 0) { + // Get the server + var server = self.s.disconnectedServers.shift(); + + // Set up the event handlers + server.once('error', errorHandlerTemp(self, self.s, 'error')); + server.once('close', errorHandlerTemp(self, self.s, 'close')); + server.once('timeout', errorHandlerTemp(self, self.s, 'timeout')); + server.once('connect', connectHandler(self, self.s)); + + // Ensure we schedule the opening of new socket + // on separate ticks of the event loop + var execute = function(_server) { + // Attempt to connect + process.nextTick(function() { + _server.connect(); + }); + } + + execute(server); + } +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + // If we specified a read preference check if we are connected to something + // than can satisfy this + if(options.readPreference + && options.readPreference.equals(ReadPreference.secondary)) + return this.s.replState.isSecondaryConnected(); + + if(options.readPreference + && options.readPreference.equals(ReadPreference.primary)) + return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); + + if(options.readPreference + && options.readPreference.equals(ReadPreference.primaryPreferred)) + return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); + + if(options.readPreference + && options.readPreference.equals(ReadPreference.secondaryPreferred)) + return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); + + if(this.s.secondaryOnlyConnectionAllowed + && this.s.replState.isSecondaryConnected()) return true; + + return this.s.replState.isPrimaryConnected(); +} + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.s.replState.state == DESTROYED; +} + +/** + * Destroy the server connection + * @method + */ +ReplSet.prototype.destroy = function(emitClose) { + var self = this; + if(this.s.logger.isInfo()) this.s.logger.info(f('[%s] destroyed', this.s.id)); + this.s.replState.state = DESTROYED; + + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + + // Destroy state + this.s.replState.destroy(); + + // Clear out any listeners + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); + + clearTimeout(self.s.haTimer); +} + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +// +// Inquires about state changes +// + +// Add the new credential for a db, removing the old +// credential from the cache +var addCredentials = function(s, db, argsWithoutCallback) { + // Remove any credentials for the db + clearCredentials(s, db + ".dummy"); + // Add new credentials to list + s.credentials.push(argsWithoutCallback); +} + +// Clear out credentials for a namespace +var clearCredentials = function(s, ns) { + var db = ns.split('.')[0]; + var filteredCredentials = []; + + // Filter out all credentials for the db the user is logging out off + for(var i = 0; i < s.credentials.length; i++) { + if(s.credentials[i][1] != db) filteredCredentials.push(s.credentials[i]); + } + + // Set new list of credentials + s.credentials = filteredCredentials; +} + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tagsArray = !Array.isArray(readPreference.tags) ? [tags] : tags; + + // Iterate over the tags + for(var j = 0; j < tagsArray.length; j++) { + var tags = tagsArray[j]; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) found = false; + } + + // Add to candidate list + if(found) { + filteredServers.push(servers[i]); + } + } + + // We found servers by the highest priority + if(found) break; + } + + // Returned filtered servers + return filteredServers; +} + +// +// Pick a server based on readPreference +var pickServer = function(self, s, readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // Do we have a custom readPreference strategy, use it + if(s.readPreferenceStrategies != null && s.readPreferenceStrategies[readPreference.preference] != null) { + if(s.readPreferenceStrategies[readPreference.preference] == null) throw new MongoError(f("cannot locate read preference handler for %s", readPreference.preference)); + var server = s.readPreferenceStrategies[readPreference.preference].pickServer(s.replState, readPreference); + if(s.debug) self.emit('pickedServer', readPreference, server); + return server; + } + + // Filter out any hidden secondaries + var secondaries = s.replState.secondaries.filter(function(server) { + if(server.lastIsMaster().hidden) return false; + return true; + }); + + // Check if we can satisfy and of the basic read Preferences + if(readPreference.equals(ReadPreference.secondary) + && secondaries.length == 0) + throw new MongoError("no secondary server available"); + + if(readPreference.equals(ReadPreference.secondaryPreferred) + && secondaries.length == 0 + && s.replState.primary == null) + throw new MongoError("no secondary or primary server available"); + + if(readPreference.equals(ReadPreference.primary) + && s.replState.primary == null) + throw new MongoError("no primary server available"); + + // Secondary + if(readPreference.equals(ReadPreference.secondary)) { + s.index = (s.index + 1) % secondaries.length; + return secondaries[s.index]; + } + + // Secondary preferred + if(readPreference.equals(ReadPreference.secondaryPreferred)) { + if(secondaries.length > 0) { + // Apply tags if present + var servers = filterByTags(readPreference, secondaries); + // If have a matching server pick one otherwise fall through to primary + if(servers.length > 0) { + s.index = (s.index + 1) % servers.length; + return servers[s.index]; + } + } + + return s.replState.primary; + } + + // Primary preferred + if(readPreference.equals(ReadPreference.primaryPreferred)) { + if(s.replState.primary) return s.replState.primary; + + if(secondaries.length > 0) { + // Apply tags if present + var servers = filterByTags(readPreference, secondaries); + // If have a matching server pick one otherwise fall through to primary + if(servers.length > 0) { + s.index = (s.index + 1) % servers.length; + return servers[s.index]; + } + + // Throw error a we have not valid secondary or primary servers + throw new MongoError("no secondary or primary server available"); + } + } + + // Return the primary + return s.replState.primary; +} + +var setHaTimer = function(self, state) { + // all haTimers are set to to repeat, so we pass norepeat false + self.s.haTimer = setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return self.s.haTimer; +} + +var haveAvailableServers = function(state) { + // console.log("!---------------------------------------------------------------") + // console.dir("state.disconnectedServers.length = " + state.disconnectedServers.length) + // console.dir("state.replState.secondaries.length = " + state.replState.secondaries.length) + // console.dir("state.replState.arbiters.length = " + state.replState.arbiters.length) + // console.dir("state.replState.primary = " + (state.replState.primary != null)) + if(state.disconnectedServers.length == 0 + && state.replState.secondaries.length == 0 + && state.replState.arbiters.length == 0 + && state.replState.primary == null) return false; + return true; +} + +var replicasetInquirer = function(self, state, norepeat) { + return function() { + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer :: " + state.replState.state) + if(state.replState.state == DESTROYED) return + // We have no connections we need to reseed the disconnected list + if(!haveAvailableServers(state)) { + // console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ replicasetInquirer 0") + // For all entries in the seedlist build a server instance + state.disconnectedServers = state.seedlist.map(function(e) { + // Clone options + var opts = cloneOptions(state.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = state.readPreferenceStrategies; + opts.emitError = true; + // Add a reserved connection for monitoring + opts.size = opts.size + 1; + opts.monitoring = true; + // Set up tags if any + if(state.tag) opts.tag = stage.tag; + // Share the auth store + opts.authProviders = state.authProviders; + // Create a new Server + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + return server; + }); + } + + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 2") + + // Process already running don't rerun + if(state.highAvailabilityProcessRunning) return; + // Started processes + state.highAvailabilityProcessRunning = true; + if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring process running %s', state.id, JSON.stringify(state.replState))); + + // Unique HA id to identify the current look running + var localHaId = state.haId++; + + // Clean out any failed connection attempts + state.connectingServers = {}; + + // Controls if we are doing a single inquiry or repeating + norepeat = typeof norepeat == 'boolean' ? norepeat : false; + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(state.replState.isPrimaryConnected() && state.replState.isSecondaryConnected() && state.disconnectHandler) { + state.disconnectHandler.execute(); + } + + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 3") + + // Emit replicasetInquirer + self.emit('ha', 'start', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + + // Let's process all the disconnected servers + while(state.disconnectedServers.length > 0) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!! ATTEMPT TO RECONNECT") + // Get the first disconnected server + var server = state.disconnectedServers.shift(); + if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring attempting to connect to %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, 'error')); + server.once('close', errorHandlerTemp(self, state, 'close')); + server.once('timeout', errorHandlerTemp(self, state, 'timeout')); + server.once('connect', connectHandler(self, state)); + + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! SERVER") + // console.log("&&&&&&&&&&&&&&&&&&&&& reconnect to server :: " + server.name) + // console.dir(server.s.options) + + // Ensure we schedule the opening of new socket + // on separate ticks of the event loop + var execute = function(_server) { + // Attempt to connect + process.nextTick(function() { + _server.connect(); + }); + } + + execute(server); + } + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 4") + + // Cleanup state (removed disconnected servers) + state.replState.clean(); + + // We need to query all servers + var servers = state.replState.getAll({includeArbiters:true}); + var serversLeft = servers.length; + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 5 :: " + serversLeft) + + // If no servers and we are not destroyed keep pinging + if(servers.length == 0 && state.replState.state == CONNECTED) { + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 6:1") + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 6:2") + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 6:3 :: " + norepeat) + // Restart ha process + if(!norepeat) setHaTimer(self, state); + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 6:4") + return; + } + + // + // ismaster for Master server + var primaryIsMaster = null; + + // Kill the server connection if it hangs + var timeoutServer = function(_server) { + return setTimeout(function() { + if(_server.isConnected()) { + _server.connections()[0].connection.destroy(); + } + }, self.s.options.connectionTimeout); + } + + // + // Inspect a specific servers ismaster + var inspectServer = function(server) { + if(state.replState.state == DESTROYED) return; + // Did we get a server + if(server && server.isConnected()) { + // Get the timeout id + var timeoutId = timeoutServer(server); + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 1:1") + // Execute ismaster + server.command('admin.$cmd', { ismaster:true }, { monitoring:true }, function(err, r) { + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ execute replicasetInquirer 1:2") + // console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ replicasetInquirer :: " + new Date().getTime()) + // if(r)console.dir(r.result) + // Clear out the timeoutServer + clearTimeout(timeoutId); + + // If the state was destroyed + if(state.replState.state == DESTROYED) return; + + // Count down the number of servers left + serversLeft = serversLeft - 1; + + // If we have an error but still outstanding server request return + if(err && serversLeft > 0) return; + + // We had an error and have no more servers to inspect, schedule a new check + if(err && serversLeft == 0) { + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunnfing + state.highAvailabilityProcessRunning = false; + // Return the replicasetInquirer + if(!norepeat) setHaTimer(self, state); + return; + } + + // Let all the read Preferences do things to the servers + var rPreferencesCount = Object.keys(state.readPreferenceStrategies).length; + + // Handle the primary + var ismaster = r.result; + if(state.logger.isDebug()) state.logger.debug(f('[%s] monitoring process ismaster %s', state.id, JSON.stringify(ismaster))); + + // Update the replicaset state + state.replState.update(ismaster, server); + + // + // Process hosts list from ismaster under two conditions + // 1. Ismaster result is from primary + // 2. There is no primary and the ismaster result is from a non-primary + if(err == null + && (ismaster.ismaster || (!state.primary)) + && Array.isArray(ismaster.hosts)) { + // Hosts to process + var hosts = ismaster.hosts; + // Add arbiters to list of hosts if we have any + if(Array.isArray(ismaster.arbiters)) { + hosts = hosts.concat(ismaster.arbiters.map(function(x) { + return {host: x, arbiter:true}; + })); + } + + if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); + // Process all the hsots + processHosts(self, state, hosts); + } else if(err == null && !Array.isArray(ismaster.hosts)) { + server.destroy(); + } + + // No read Preferences strategies + if(rPreferencesCount == 0) { + // Don't schedule a new inquiry + if(serversLeft > 0) return; + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Let's keep monitoring + if(!norepeat) setHaTimer(self, state); + return; + } + + // No servers left to query, execute read preference strategies + if(serversLeft == 0) { + // Go over all the read preferences + for(var name in state.readPreferenceStrategies) { + state.readPreferenceStrategies[name].ha(self, state.replState, function() { + rPreferencesCount = rPreferencesCount - 1; + + if(rPreferencesCount == 0) { + // Add any new servers in primary ismaster + if(err == null + && ismaster.ismaster + && Array.isArray(ismaster.hosts)) { + processHosts(self, state, ismaster.hosts); + } + + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Let's keep monitoring + if(!norepeat) setHaTimer(self, state); + return; + } + }); + } + } + }); + } + } + + // Call ismaster on all servers + for(var i = 0; i < servers.length; i++) { + inspectServer(servers[i]); + } + + // If no more initial servers and new scheduled servers to connect + if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup', self); + } + + // If all servers are accounted for and we have not sent the all event + if(state.replState.primary != null && self.lastIsMaster() + && Array.isArray(self.lastIsMaster().hosts) && !state.all) { + var length = 1 + state.replState.secondaries.length; + // If we have all secondaries + primary + if(length == self.lastIsMaster().hosts.length + 1) { + state.all = true; + self.emit('all', self); + } + } + } +} + +// Error handler for initial connect +var errorHandlerTemp = function(self, state, event) { + return function(err, server) { + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET") + // console.dir(err) + // Log the information + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s disconnected', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + // Filter out any connection servers + state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { + return server.name != _server.name; + }); + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET 1") + + // Connection is destroyed, ignore + if(state.replState.state == DESTROYED) return; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET 2") + + // Push to list of disconnected servers + addToListIfNotExist(state.disconnectedServers, server); + + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET 3") + + // End connection operation if we have no legal replicaset state + if(state.initialConnectionServers == 0 && state.replState.state == CONNECTING) { + if((state.secondaryOnlyConnectionAllowed && !state.replState.isSecondaryConnected() && !state.replState.isPrimaryConnected()) + || (!state.secondaryOnlyConnectionAllowed && !state.replState.isPrimaryConnected())) { + // console.log("----- REPLSET 0") + if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); + + if(self.listeners('error').length > 0) { + // console.log("----- REPLSET 1") + return self.emit('error', new MongoError('no valid seed servers in list')); + } + } + } + + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET 4") + + // If the number of disconnected servers is equal to + // the number of seed servers we cannot connect + if(state.disconnectedServers.length == state.seedlist.length && state.replState.state == CONNECTING) { + if(state.emitError && self.listeners('error').length > 0) { + // console.log("----- REPLSET 2") + if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); + + if(self.listeners('error').length > 0) { + // console.log("----- REPLSET 3") + self.emit('error', new MongoError('no valid seed servers in list')); + } + } + } + + // console.log("!!!!!!!!!!!!!!!!!!!! TEMP ERROR HANDLER REPLSET 5") + } +} +// TODO with arbiter +// - if connected to an arbiter, shut down all but single server connection + +// Connect handler +var connectHandler = function(self, state) { + return function(server) { + // console.log(" --------------------------- connectHandler 0") + // console.log("SERVER CONNECTED") + if(state.logger.isInfo()) state.logger.info(f('[%s] connected to %s', state.id, server.name)); + // Destroyed connection + if(state.replState.state == DESTROYED) { + server.destroy(false, false); + return; + } + + // Filter out any connection servers + state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { + return server.name != _server.name; + }); + + // Process the new server + var processNewServer = function() { + // Discover any additional servers + var ismaster = server.lastIsMaster(); + + // Are we an arbiter, restrict number of connections to + // one single connection + if(ismaster.arbiterOnly) { + server.capConnections(1); + } + + // Deal with events + var events = ['error', 'close', 'timeout', 'connect', 'message']; + // Remove any non used handlers + events.forEach(function(e) { + server.removeAllListeners(e); + }) + + // Clean up + delete state.connectingServers[server.name]; + // Update the replicaset state, destroy if not added + if(!state.replState.update(ismaster, server)) { + // Destroy the server instance + server.destroy(); + // No more candiate servers + if(state.state == CONNECTING && state.initialConnectionServers.length == 0 + && state.replState.primary == null && state.replState.secondaries.length == 0) { + return self.emit('error', new MongoError("no replicaset members found in seedlist")); + } + + return; + } + + // Add the server handling code + if(server.isConnected()) { + server.on('error', errorHandler(self, state)); + server.on('close', closeHandler(self, state)); + server.on('timeout', timeoutHandler(self, state)); + } + + // Hosts to process + var hosts = ismaster.hosts; + // Add arbiters to list of hosts if we have any + if(Array.isArray(ismaster.arbiters)) { + hosts = hosts.concat(ismaster.arbiters.map(function(x) { + return {host: x, arbiter:true}; + })); + } + + if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); + + // Add any new servers + processHosts(self, state, hosts); + + // If have the server instance already destroy it + if(state.initialConnectionServers.length == 0 && Object.keys(state.connectingServers).length == 0 + && !state.replState.isPrimaryConnected() && !state.secondaryOnlyConnectionAllowed && state.replState.state == CONNECTING) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no primary found in replicaset', state.id)); + self.emit('error', new MongoError("no primary found in replicaset")); + return self.destroy(); + } + + // If no more initial servers and new scheduled servers to connect + if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup', self); + } + } + + // console.log(" --------------------------- connectHandler 1 :: " + self.s.authInProgress) + // Save up new members to be authenticated against + if(self.s.authInProgress) { + self.s.authInProgressServers.push(server); + } + + // console.log(" --------------------------- connectHandler 2") + + // No credentials just process server + if(state.credentials.length == 0) return processNewServer(); + // Do we have credentials, let's apply them all + var count = state.credentials.length; + // console.log(" --------------------------- connectHandler 3 :: " + count) + // Apply the credentials + for(var i = 0; i < state.credentials.length; i++) { + server.auth.apply(server, state.credentials[i].concat([function(err, r) { + count = count - 1; + if(count == 0) { + // console.log(" --------------------------- connectHandler 4") + processNewServer(); + } + }])); + } + } +} + +// +// Detect if we need to add new servers +var processHosts = function(self, state, hosts) { + if(state.replState.state == DESTROYED) return; + if(Array.isArray(hosts)) { + // Check any hosts exposed by ismaster + for(var i = 0; i < hosts.length; i++) { + // Get the object + var host = hosts[i]; + var options = {}; + + // Do we have an arbiter + if(typeof host == 'object') { + host = host.host; + options.arbiter = host.arbiter; + } + + // If not found we need to create a new connection + if(!state.replState.contains(host)) { + if(state.connectingServers[host] == null && !inInitialConnectingServers(self, state, host)) { + if(state.logger.isInfo()) state.logger.info(f('[%s] scheduled server %s for connection', state.id, host)); + // Make sure we know what is trying to connect + state.connectingServers[host] = host; + // Connect the server + connectToServer(self, state, host.split(':')[0], parseInt(host.split(':')[1], 10), options); + } + } + } + } +} + +var inInitialConnectingServers = function(self, state, address) { + for(var i = 0; i < state.initialConnectionServers.length; i++) { + if(state.initialConnectionServers[i].name == address) return true; + } + return false; +} + +// Connect to a new server +var connectToServer = function(self, state, host, port, options) { + options = options || {}; + var opts = cloneOptions(state.options); + opts.host = host; + opts.port = port; + opts.reconnect = false; + opts.readPreferenceStrategies = state.readPreferenceStrategies; + if(state.tag) opts.tag = state.tag; + // Share the auth store + opts.authProviders = state.authProviders; + opts.emitError = true; + // Set the size to size + 1 and mark monitoring + opts.size = opts.size + 1; + opts.monitoring = true; + + // Do we have an arbiter set the poolSize to 1 + if(options.arbiter) { + opts.size = 1; + } + + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Server :: connectToServer :: " + opts.port) + + // Create a new server instance + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, 'error')); + server.once('close', errorHandlerTemp(self, state, 'close')); + server.once('timeout', errorHandlerTemp(self, state, 'timeout')); + server.once('connect', connectHandler(self, state)); + + // Attempt to connect + process.nextTick(function() { + server.connect(); + }); +} + +// +// Add server to the list if it does not exist +var addToListIfNotExist = function(list, server) { + var found = false; + // If the server is a null value return false + if(server == null) return found; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Check if the server already exists + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) found = true; + } + + if(!found) { + list.push(server); + } + + return found; +} + +var errorHandler = function(self, state) { + return function(err, server) { + // console.log("!!!!!!!!!!!!!!!!!!!!! err handler REPLSET") + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s errored out with %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name, JSON.stringify(err))); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + if(found && state.emitError && self.listeners('error').length > 0) self.emit('error', err, server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + // replicasetInquirer(self, self.s, true)(); + replicasetInquirer(self, self.s, self.s.highAvailabilityProcessRunning)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +var timeoutHandler = function(self, state) { + return function(err, server) { + // console.log("!!!!!!!!!!!!!!!!!!!!! timeout handler REPLSET") + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s timed out', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + // replicasetInquirer(self, self.s, true)(); + replicasetInquirer(self, self.s, self.s.highAvailabilityProcessRunning)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +var closeHandler = function(self, state) { + return function(err, server) { + // console.log("!!!!!!!!!!!!!!!!!!!!! close handler REPLSET") + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s closed', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) { + self.emit('left', state.replState.remove(server), server); + } + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + // replicasetInquirer(self, self.s, true)(); + replicasetInquirer(self, self.s, self.s.highAvailabilityProcessRunning)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +// +// Validate if a non-master or recovering error +var notMasterError = function(r) { + // Get result of any + var result = r && r.result ? r.result : r; + + // Explore if we have a not master error + if(result && (result.err == 'not master' + || result.errmsg == 'not master' || (result['$err'] && result['$err'].indexOf('not master or secondary') != -1) + || (result['$err'] && result['$err'].indexOf("not master and slaveOk=false") != -1) + || result.errmsg == 'node is recovering')) { + return true; + } + + return false; +} + +module.exports = ReplSet; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js new file mode 100644 index 0000000..f47b1e7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js @@ -0,0 +1,506 @@ +"use strict"; + +var Logger = require('../connection/logger') + , f = require('util').format + , ObjectId = require('bson').ObjectId + , MongoError = require('../error'); + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +/** + * Creates a new Replicaset State object + * @class + * @property {object} primary Primary property + * @property {array} secondaries List of secondaries + * @property {array} arbiters List of arbiters + * @return {State} A cursor instance + */ +var State = function(replSet, options) { + this.replSet = replSet; + this.options = options; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.primary = null; + // Initial state is disconnected + this.state = DISCONNECTED; + // Current electionId + this.electionId = null; + // Get a logger instance + this.logger = Logger('ReplSet', options); + // Unpacked options + this.id = options.id; + this.setName = options.setName; + this.connectingServers = options.connectingServers; + this.secondaryOnlyConnectionAllowed = options.secondaryOnlyConnectionAllowed; +} + +/** + * Is there a secondary connected + * @method + * @return {boolean} + */ +State.prototype.isSecondaryConnected = function() { + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].isConnected()) return true; + } + + return false; +} + +/** + * Is there a primary connection + * @method + * @return {boolean} + */ +State.prototype.isPrimaryConnected = function() { + return this.primary != null && this.primary.isConnected(); +} + +/** + * Is the given address the primary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isPrimary = function(address) { + if(this.primary == null) return false; + return this.primary && this.primary.equals(address); +} + +/** + * Is the given address a secondary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isSecondary = function(address) { + // Check if the server is a secondary at the moment + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].equals(address)) { + return true; + } + } + + return false; +} + +/** + * Is the given address a secondary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isPassive = function(address) { + // Check if the server is a secondary at the moment + for(var i = 0; i < this.passives.length; i++) { + if(this.passives[i].equals(address)) { + return true; + } + } + + return false; +} + +/** + * Does the replicaset contain this server + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.contains = function(address) { + if(this.primary && this.primary.equals(address)) return true; + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].equals(address)) return true; + } + + for(var i = 0; i < this.arbiters.length; i++) { + if(this.arbiters[i].equals(address)) return true; + } + + for(var i = 0; i < this.passives.length; i++) { + if(this.passives[i].equals(address)) return true; + } + + return false; +} + +/** + * Clean out all dead connections + * @method + */ +State.prototype.clean = function() { + if(this.primary != null && !this.primary.isConnected()) { + this.primary = null; + } + + // Filter out disconnected servers + this.secondaries = this.secondaries.filter(function(s) { + return s.isConnected(); + }); + + // Filter out disconnected servers + this.arbiters = this.arbiters.filter(function(s) { + return s.isConnected(); + }); +} + +/** + * Destroy state + * @method + */ +State.prototype.destroy = function() { + this.state = DESTROYED; + if(this.primary) this.primary.destroy(); + this.secondaries.forEach(function(s) { + s.destroy(); + }); + this.arbiters.forEach(function(s) { + s.destroy(); + }); +} + +/** + * Remove server from state + * @method + * @param {Server} Server to remove + * @return {string} Returns type of server removed (primary|secondary) + */ +State.prototype.remove = function(server) { + if(this.primary && this.primary.equals(server)) { + this.primary = null; + } + + var length = this.arbiters.length; + // Filter out the server from the arbiters + this.arbiters = this.arbiters.filter(function(s) { + return !s.equals(server); + }); + if(this.arbiters.length < length) return 'arbiter'; + + var length = this.passives.length; + // Filter out the server from the passives + this.passives = this.passives.filter(function(s) { + return !s.equals(server); + }); + + // We have removed a passive + if(this.passives.length < length) { + // Ensure we removed it from the list of secondaries as well if it exists + this.secondaries = this.secondaries.filter(function(s) { + return !s.equals(server); + }); + } + + // Filter out the server from the secondaries + this.secondaries = this.secondaries.filter(function(s) { + return !s.equals(server); + }); + + // Get the isMaster + var isMaster = server.lastIsMaster(); + // Return primary if the server was primary + if(isMaster.ismaster && isMaster.hosts) return 'primary'; + if(isMaster.ismaster) return 'secondary'; + if(isMaster.secondary) return 'secondary'; + if(isMaster.passive) return 'passive'; + return 'arbiter'; +} + +/** + * Get the server by name + * @method + * @param {string} address Server address + * @return {Server} + */ +State.prototype.get = function(server) { + var found = false; + // All servers to search + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + // Locate the server + for(var i = 0; i < servers.length; i++) { + if(servers[i].equals(server)) { + return servers[i]; + } + } +} + +/** + * Get all the servers in the set + * @method + * @param {boolean} [options.includeArbiters] Include Arbiters in returned server list + * @return {array} + */ +State.prototype.getAll = function(options) { + options = options || {}; + var servers = []; + if(this.primary) servers.push(this.primary); + servers = servers.concat(this.secondaries); + + // Include the arbiters + if(options.includeArbiters) { + servers = servers.concat(this.arbiters); + } + + // return ; + return servers; +} + +/** + * All raw connections + * @method + * @param {boolean} [options.includeArbiters] Include Arbiters in returned server list + * @return {array} + */ +State.prototype.getAllConnections = function(options) { + options = options || {}; + var connections = []; + if(this.primary) connections = connections.concat(this.primary.connections()); + this.secondaries.forEach(function(s) { + connections = connections.concat(s.connections()); + }) + + // Include the arbiters + if(options.includeArbiters) { + this.arbiters.forEach(function(s) { + connections = connections.concat(s.connections()); + }) + } + + return connections; +} + +/** + * Return JSON object + * @method + * @return {object} + */ +State.prototype.toJSON = function() { + return { + primary: this.primary ? this.primary.lastIsMaster().me : null + , secondaries: this.secondaries.map(function(s) { + return s.lastIsMaster().me + }) + } +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +State.prototype.lastIsMaster = function() { + if(this.primary) return this.primary.lastIsMaster(); + if(this.secondaries.length > 0) return this.secondaries[0].lastIsMaster(); + return {}; +} + +/** + * Promote server to primary + * @method + * @param {Server} server Server we wish to promote + */ +State.prototype.promotePrimary = function(server) { + var currentServer = this.get(server); + // Server does not exist in the state, add it as new primary + if(currentServer == null) { + this.primary = server; + return; + } + + // We found a server, make it primary and remove it from the secondaries + // Remove the server first + this.remove(currentServer); + // Set as primary + this.primary = currentServer; +} + +var add = function(list, server) { + // Check if the server is a secondary at the moment + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) return false; + } + + list.push(server); + return true; +} + +/** + * Add server to list of secondaries + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addSecondary = function(server) { + return add(this.secondaries, server); +} + +/** + * Add server to list of arbiters + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addArbiter = function(server) { + return add(this.arbiters, server); +} + +/** + * Add server to list of passives + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addPassive = function(server) { + return add(this.passives, server); +} + +var compareObjectIds = function(id1, id2) { + var a = new Buffer(id1.toHexString(), 'hex'); + var b = new Buffer(id2.toHexString(), 'hex'); + + if(a === b) { + return 0; + } + + if(typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +/** + * Update the state given a specific ismaster result + * @method + * @param {object} ismaster IsMaster result + * @param {Server} server IsMaster Server source + */ +State.prototype.update = function(ismaster, server) { + var self = this; + // Not in a known connection valid state + if((!ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) || !Array.isArray(ismaster.hosts)) { + // Remove the state + var result = self.remove(server); + if(self.state == CONNECTED) { + if(self.logger.isInfo()) self.logger.info(f('[%s] removing %s from set', self.id, ismaster.me)); + self.replSet.emit('left', self.remove(server), server); + } + + return false; + } + + // Set the setName if it's not set from the first server + if(self.setName == null && ismaster.setName) { + if(self.logger.isInfo()) self.logger.info(f('[%s] setting setName to %s', self.id, ismaster.setName)); + self.setName = ismaster.setName; + } + + // Check if the replicaset name matches the provided one + if(ismaster.setName && self.setName != ismaster.setName) { + if(self.logger.isError()) self.logger.error(f('[%s] server in replset %s is not part of the specified setName %s', self.id, ismaster.setName, self.setName)); + self.remove(server); + self.replSet.emit('error', new MongoError("provided setName for Replicaset Connection does not match setName found in server seedlist")); + return false; + } + + // Log information + if(self.logger.isInfo()) self.logger.info(f('[%s] updating replicaset state %s', self.id, JSON.stringify(this))); + + // It's a master set it + if(ismaster.ismaster && self.setName == ismaster.setName && !self.isPrimary(ismaster.me)) { + // Check if the electionId is not null + if(ismaster.electionId instanceof ObjectId && self.electionId instanceof ObjectId) { + if(compareObjectIds(self.electionId, ismaster.electionId) == -1) { + self.electionId = ismaster.electionId; + } else if(compareObjectIds(self.electionId, ismaster.electionId) == 0) { + self.electionId = ismaster.electionId; + } else { + return false; + } + } + + // Initial electionId + if(ismaster.electionId instanceof ObjectId && self.electionId == null) { + self.electionId = ismaster.electionId; + } + + // Promote to primary + self.promotePrimary(server); + // Log change of primary + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to primary', self.id, ismaster.me)); + // Emit primary + self.replSet.emit('joined', 'primary', this.primary); + + // We are connected + if(self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } else { + self.state = CONNECTED; + self.replSet.emit('reconnect', server); + } + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.arbiterOnly) { + if(self.addArbiter(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to arbiter', self.id, ismaster.me)); + self.replSet.emit('joined', 'arbiter', server); + return true; + }; + + return false; + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.secondary && ismaster.passive) { + if(self.addPassive(server) && self.addSecondary(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to passive', self.id, ismaster.me)); + self.replSet.emit('joined', 'passive', server); + + // If we have secondaryOnlyConnectionAllowed and just a passive it's + // still a valid connection + if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } + + return true; + }; + + return false; + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.secondary) { + if(self.addSecondary(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to secondary', self.id, ismaster.me)); + self.replSet.emit('joined', 'secondary', server); + + if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } + + return true; + }; + + return false; + } + + // Return update applied + return true; +} + +module.exports = State; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js new file mode 100644 index 0000000..65490f9 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js @@ -0,0 +1,1371 @@ + "use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , EventEmitter = require('events').EventEmitter + , Pool = require('../connection/pool') + , b = require('bson') + , crypto = require('crypto') + , Query = require('../connection/commands').Query + , MongoError = require('../error') + , ReadPreference = require('./read_preference') + , BasicCursor = require('../cursor') + , CommandResult = require('./command_result') + , getSingleProperty = require('../connection/utils').getSingleProperty + , getProperty = require('../connection/utils').getProperty + , debugOptions = require('../connection/utils').debugOptions + , BSON = require('bson').native().BSON + , PreTwoSixWireProtocolSupport = require('../wireprotocol/2_4_support') + , TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support') + , ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support') + , Session = require('./session') + , Logger = require('../connection/logger') + , MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram'); + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; +// Server instance id +var serverId = 0; +// Callbacks instance id +var callbackId = 0; + +// Single store for all callbacks +var Callbacks = function() { + // EventEmitter.call(this); + var self = this; + // Callbacks + this.callbacks = {}; + // Set the callbacks id + this.id = callbackId++; + // Set the type to server + this.type = 'server'; +} + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +// +// Flush all callbacks +Callbacks.prototype.flush = function(err) { + for(var id in this.callbacks) { + if(!isNaN(parseInt(id, 10))) { + var callback = this.callbacks[id]; + delete this.callbacks[id]; + callback(err, null); + } + } +} + +// +// Flush all callbacks +Callbacks.prototype.flushConnection = function(err, connection) { + for(var id in this.callbacks) { + if(!isNaN(parseInt(id, 10))) { + var callback = this.callbacks[id]; + + // Validate if the operation ran on the connection + if(callback.connection === connection) { + delete this.callbacks[id]; + callback(err, null); + } + } + } +} + +Callbacks.prototype.callback = function(id) { + return this.callbacks[id]; +} + +Callbacks.prototype.emit = function(id, err, value) { + var callback = this.callbacks[id]; + delete this.callbacks[id]; + callback(err, value); +} + +Callbacks.prototype.raw = function(id) { + if(this.callbacks[id] == null) return false; + return this.callbacks[id].raw == true ? true : false +} + +Callbacks.prototype.documentsReturnedIn = function(id) { + if(this.callbacks[id] == null) return false; + return typeof this.callbacks[id].documentsReturnedIn == 'string' ? this.callbacks[id].documentsReturnedIn : null; +} + +Callbacks.prototype.unregister = function(id) { + delete this.callbacks[id]; +} + +Callbacks.prototype.register = function(id, callback) { + this.callbacks[id] = bindToCurrentDomain(callback); +} + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// Supports server +var supportsServer = function(_s) { + return _s.ismaster && typeof _s.ismaster.minWireVersion == 'number'; +} + +// +// createWireProtocolHandler +var createWireProtocolHandler = function(result) { + // 3.2 wire protocol handler + if(result && result.maxWireVersion >= 4) { + return new ThreeTwoWireProtocolSupport(new TwoSixWireProtocolSupport()); + } + + // 2.6 wire protocol handler + if(result && result.maxWireVersion >= 2) { + return new TwoSixWireProtocolSupport(); + } + + // 2.4 or earlier wire protocol handler + return new PreTwoSixWireProtocolSupport(); +} + +// +// Reconnect server +var reconnectServer = function(self, state) { + // Flush out any left over callbacks + if(self && state && state.callbacks) { + state.callbacks.flush(new MongoError(f("server %s received a broken socket pipe error", self.name))); + } + + // If the current reconnect retries is 0 stop attempting to reconnect + if(state.currentReconnectRetry == 0) { + return self.destroy(true, true); + } + + // Adjust the number of retries + state.currentReconnectRetry = state.currentReconnectRetry - 1; + + // Set status to connecting + state.state = CONNECTING; + // Create a new Pool + state.pool = new Pool(state.options); + // error handler + var reconnectErrorHandler = function(err) { + // Set the state to disconnected so we can peform a proper reconnect + state.state = DISCONNECTED; + // Destroy the pool + state.pool.destroy(); + // Adjust the number of retries + state.currentReconnectRetry = state.currentReconnectRetry - 1; + // No more retries + if(state.currentReconnectRetry <= 0) { + self.state = DESTROYED; + self.emit('error', f('failed to connect to %s:%s after %s retries', state.options.host, state.options.port, state.reconnectTries)); + } else { + setTimeout(function() { + reconnectServer(self, state); + }, state.reconnectInterval); + } + } + + // + // Attempt to connect + state.pool.once('connect', function() { + // Reset retries + state.currentReconnectRetry = state.reconnectTries; + + // Remove any non used handlers + var events = ['error', 'close', 'timeout', 'parseError']; + events.forEach(function(e) { + state.pool.removeAllListeners(e); + }); + + // Set connected state + state.state = CONNECTED; + + // Add proper handlers + state.pool.once('error', reconnectErrorHandler); + state.pool.once('close', closeHandler(self, state)); + state.pool.once('timeout', timeoutHandler(self, state)); + state.pool.once('parseError', fatalErrorHandler(self, state)); + + // We need to ensure we have re-authenticated + var keys = Object.keys(state.authProviders); + if(keys.length == 0) return self.emit('reconnect', self); + + // Get all connections + var connections = state.pool.getAll(); + // Execute all providers + var count = keys.length; + // Iterate over keys + for(var i = 0; i < keys.length; i++) { + state.authProviders[keys[i]].reauthenticate(self, connections, function(err, r) { + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + return self.emit('reconnect', self); + } + }); + } + }); + + // + // Handle connection failure + state.pool.once('error', errorHandler(self, state)); + state.pool.once('close', errorHandler(self, state)); + state.pool.once('timeout', errorHandler(self, state)); + state.pool.once('parseError', errorHandler(self, state)); + + // Connect pool + state.pool.connect(); +} + +// +// Handlers +var messageHandler = function(self, state) { + return function(response, connection) { + // console.log("!----------------------- messageHandler " + self.s.pool.availableConnections.length + " :: " + connection.id) + // Release the connection back to the pool + // self.s.pool.connectionAvailable(connection); + + // Attempt to parse the message + try { + // Parse the message + response.parse({raw: state.callbacks.raw(response.responseTo), documentsReturnedIn: state.callbacks.documentsReturnedIn(response.responseTo)}); + + // Get the callback + var cb = state.callbacks.callback(response.responseTo); + + // console.dir(Object.keys(cb)) + // console.dir(response.documents) + + // If no + if(!cb.noRelease) { + self.s.pool.connectionAvailable(connection); + } + + // Log if debug enabled + if(state.logger.isDebug()) state.logger.debug(f('message [%s] received from %s', response.raw.toString('hex'), self.name)); + // Execute the registered callback + state.callbacks.emit(response.responseTo, null, response); + } catch (err) { + state.callbacks.flush(new MongoError(err)); + self.destroy(); + } + } +} + +var errorHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% errorHandler") + // console.log(err) + // Flush the connection operations + if(self.s.callbacks) { + self.s.callbacks.flushConnection(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err))), connection); + } + + // Emit error event + if(state.emitError && self.listeners('error').length > 0) self.emit('error', err, self); + + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% errorHandler 1") + // No more connections left, emit a close + if(state.pool.getAll().length == 0) { + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% errorHandler 2 :: " + state.emitError) + // Set disconnected state + state.state = DISCONNECTED; + // Notify any strategies for read Preferences about closure + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); + // Destroy all connections + self.destroy(); + // console.log("!!!!!!!!!!!!! EMIT ERROR :: " + state.emitError + " :: " + self.listeners('error').length + " :: " + state.reconnect) + // Emit error event + if(state.emitError && self.listeners('error').length > 0) self.emit('error', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + reconnectServer(self, state) + }, state.reconnectInterval); + } + } +} + +var fatalErrorHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% fatalErrorHandler") + // Flush the connection operations + if(self.s.callbacks) { + self.s.callbacks.flushConnection(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err))), connection); + } + + // // Emit error event + // if(self.listeners('error').length > 0) self.emit('error', err, self); + + // No more connections left, emit a close + if(state.pool.getAll().length == 0) { + // Set disconnected state + state.state = DISCONNECTED; + // Notify any strategies for read Preferences about closure + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); + // Emit error event + if(self.listeners('error').length > 0) self.emit('error', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } + } +} + +var timeoutHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% timeoutHandler = " + connection.port + " :: " + state.pool.getAll().length) + // console.log("----------------------- pool.write _execute 0 :: availableConnections = " + self.s.pool.availableConnections.length) + // console.log("----------------------- pool.write _execute 0 :: inUseConnections = " + self.s.pool.inUseConnections.length) + // console.log("----------------------- pool.write _execute 0 :: newConnections = " + self.s.pool.newConnections.length) + // console.log("----------------------- pool.write _execute 0 :: queue = " + self.s.pool.queue.length) + + // Flush the connection operations + if(self.s.callbacks) { + self.s.callbacks.flushConnection(new MongoError(f("server %s timed out", self.name)), connection); + } + + // // Emit error event + // self.emit('timeout', err, self); + + // No more connections left, emit a close + if(state.pool.getAll().length == 0) { + // Set disconnected state + state.state = DISCONNECTED; + // Notify any strategies for read Preferences about closure + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'timeout', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s timed out', self.name)); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s timed out", self.name))); + // Emit error event + self.emit('timeout', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } + } +} + +var closeHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% closeHandler :: " + state.pool.getAll().length) + + // // Emit error event + // self.emit('close', err, self); + + // No more connections left, emit a close + if(state.pool.getAll().length == 0) { + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% closeHandler 1 :: " + state.pool.getAll().length) + // Set state to disconnected + state.state = DISCONNECTED; + // Notify any strategies for read Preferences about closure + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'close', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s closed', self.name)); + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% closeHandler 2 :: " + state.pool.getAll().length) + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% closeHandler 3 :: " + state.pool.getAll().length) + // Emit error event + self.emit('close', err, self); + // console.log("!!!!!!!!!!!!! EMIT CLOSE :: " + state.reconnect) + // console.log("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% closeHandler 1 :: " + state.pool.getAll().length) + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } + } +} + +var connectHandler = function(self, state) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! server connect :: " + self.name) + // Apply all stored authentications + var applyAuthentications = function(callback) { + // We need to ensure we have re-authenticated + var keys = Object.keys(state.authProviders); + if(keys.length == 0) return callback(null, null); + + // Get all connections + var connections = state.pool.getAll(); + // console.log("~~~~~~~~~~~~~~~~~~~~~~~~~ connectHandler :: " + connections.length) + // Execute all providers + var count = keys.length; + // Iterate over keys + for(var i = 0; i < keys.length; i++) { + state.authProviders[keys[i]].reauthenticate(self, connections, function(err, r) { + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + return callback(null, null); + } + }); + } + } + + return function() { + // Apply any applyAuthentications + applyAuthentications(function() { + // Get the actual latency of the ismaster + var start = new Date().getTime(); + // Execute an ismaster + self.command('admin.$cmd', {ismaster:true}, function(err, r) { + if(err) { + state.state = DISCONNECTED; + return self.emit('close', err, self); + } + + // Set the latency for this instance + state.isMasterLatencyMS = new Date().getTime() - start; + + // Set the current ismaster + if(!err) { + state.ismaster = r.result; + } + + // Emit the ismaster + self.emit('ismaster', r.result, self); + + // Determine the wire protocol handler + state.wireProtocolHandler = createWireProtocolHandler(state.ismaster); + + // Set the wireProtocolHandler + state.options.wireProtocolHandler = state.wireProtocolHandler; + + // Log the ismaster if available + if(state.logger.isInfo()) state.logger.info(f('server %s connected with ismaster [%s]', self.name, JSON.stringify(r.result))); + + // Validate if we it's a server we can connect to + if(!supportsServer(state) && state.wireProtocolHandler == null) { + state.state = DISCONNECTED + return self.emit('error', new MongoError("non supported server version"), self); + } + + // Set the details + if(state.ismaster && state.ismaster.me) state.serverDetails.name = state.ismaster.me; + + // No read preference strategies just emit connect + if(state.readPreferenceStrategies == null) { + state.state = CONNECTED; + return self.emit('connect', self); + } + + // Signal connect to all readPreferences + notifyStrategies(self, self.s, 'connect', [self], function(err, result) { + state.state = CONNECTED; + return self.emit('connect', self); + }); + }); + }); + } +} + +var slaveOk = function(r) { + if(r) return r.slaveOk() + return false; +} + +// +// Execute readPreference Strategies +var notifyStrategies = function(self, state, op, params, callback) { + if(typeof callback != 'function') { + // Notify query start to any read Preference strategies + for(var name in state.readPreferenceStrategies) { + if(state.readPreferenceStrategies[name][op]) { + var strat = state.readPreferenceStrategies[name]; + strat[op].apply(strat, params); + } + } + // Finish up + return; + } + + // Execute the async callbacks + var nPreferences = Object.keys(state.readPreferenceStrategies).length; + if(nPreferences == 0) return callback(null, null); + for(var name in state.readPreferenceStrategies) { + if(state.readPreferenceStrategies[name][op]) { + var strat = state.readPreferenceStrategies[name]; + // Add a callback to params + var cParams = params.slice(0); + cParams.push(function(err, r) { + nPreferences = nPreferences - 1; + if(nPreferences == 0) { + callback(null, null); + } + }) + // Execute the readPreference + strat[op].apply(strat, cParams); + } + } +} + +var debugFields = ['reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host' + , 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout', 'checkServerIdentity' + , 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs']; + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + */ +var Server = function(options) { + var self = this; + + // Add event listener + EventEmitter.call(this); + + // BSON Parser, ensure we have a single instance + if(bsonInstance == null) { + bsonInstance = new BSON(bsonTypes); + } + + // Reconnect retries + var reconnectTries = options.reconnectTries || 30; + + // console.log(")))))))))))))))))))))))))))))))))))))))))))))))))))))") + // console.dir(options) + + // Keeps all the internal state of the server + this.s = { + // Options + options: options + // Contains all the callbacks + , callbacks: new Callbacks() + // Logger + , logger: Logger('Server', options) + // Server state + , state: DISCONNECTED + // Reconnect option + , reconnect: typeof options.reconnect == 'boolean' ? options.reconnect : true + , reconnectTries: reconnectTries + , reconnectInterval: options.reconnectInterval || 1000 + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Current state + , currentReconnectRetry: reconnectTries + // Contains the ismaster + , ismaster: null + // Contains any alternate strategies for picking + , readPreferenceStrategies: options.readPreferenceStrategies + // Auth providers + , authProviders: options.authProviders || {} + // Server instance id + , id: serverId++ + // Grouping tag used for debugging purposes + , tag: options.tag + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + // wireProtocolHandler methods + , wireProtocolHandler: options.wireProtocolHandler || new PreTwoSixWireProtocolSupport() + // Factory overrides + , Cursor: options.cursorFactory || BasicCursor + // BSON Parser, ensure we have a single instance + , bsonInstance: bsonInstance + // Pick the right bson parser + , bson: options.bson ? options.bson : bsonInstance + // Internal connection pool + , pool: null + // Is master latency + , isMasterLatencyMS: 0 + // Server details + , serverDetails: { + host: options.host + , port: options.port + , name: options.port ? f("%s:%s", options.host, options.port) : options.host + } + } + + // Create hash method + var hash = crypto.createHash('sha1'); + hash.update(f('%s:%s', this.host, this.port)); + + // Create a hash name + this.hashedName = hash.digest('hex'); + + // Reference state + var s = this.s; + + // Add bson parser to options + options.bson = s.bson; + + // Set error properties + getProperty(this, 'name', 'name', s.serverDetails, {}); + getProperty(this, 'bson', 'bson', s.options, {}); + getProperty(this, 'wireProtocolHandler', 'wireProtocolHandler', s.options, {}); + getSingleProperty(this, 'id', s.id); + + // If we do not have an inherited authorization mechanism + if(!options.authProviders) { + this.addAuthProvider('mongocr', new MongoCR()); + this.addAuthProvider('x509', new X509()); + this.addAuthProvider('plain', new Plain()); + this.addAuthProvider('gssapi', new GSSAPI()); + this.addAuthProvider('sspi', new SSPI()); + this.addAuthProvider('scram-sha-1', new ScramSHA1()); + } +} + +inherits(Server, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +Server.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Reduce the poolSize to the provided max connections value + * @method + * @param {number} maxConnections reduce the poolsize to maxConnections + */ +Server.prototype.capConnections = function(maxConnections) { + this.s.pool.capConnections(maxConnections); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.s.ismaster; +} + +/** + * Initiate server connect + * @method + */ +Server.prototype.connect = function(_options) { + var self = this; + // Set server specific settings + _options = _options || {} + // Set the promotion + if(typeof _options.promoteLongs == 'boolean') { + self.s.options.promoteLongs = _options.promoteLongs; + } + + // Destroy existing pool + if(self.s.pool) { + self.s.pool.destroy(); + self.s.pool = null; + } + + // Set the state to connection + self.s.state = CONNECTING; + // Create a new connection pool + if(!self.s.pool) { + self.s.options.messageHandler = messageHandler(self, self.s); + self.s.pool = new Pool(self.s.options); + } + + // Add all the event handlers + self.s.pool.on('timeout', timeoutHandler(self, self.s)); + self.s.pool.on('close', closeHandler(self, self.s)); + self.s.pool.on('error', errorHandler(self, self.s)); + self.s.pool.once('connect', connectHandler(self, self.s)); + self.s.pool.on('parseError', fatalErrorHandler(self, self.s)); + + // + // Handle new connections + self.s.pool.on('connection', function(connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NEW Connection :: " + connection.id + " -- server -- " + self.s.id + " -- " + self.s.options.port) + + // No auth handler used, return the connection + var keys = Object.keys(self.s.authProviders); + if(keys.length == 0) return self.s.pool.connectionAvailable(connection); + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NEW Connection 1 :: " + keys.length) + + // Get all connections + var connections = [connection]; + // Execute all providers + var count = keys.length; + + // Iterate over all auth methods + for(var i = 0; i < keys.length; i++) { + // console.log("------------------ authenticating against " + keys[i]); + // if(keys[i] == 'scram-sha-1') { + // console.dir(self.s.authProviders[keys[i]].authStore) + // } + // reauthenticate the connection + self.s.authProviders[keys[i]].reauthenticate(self, connections, function(err, r) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NEW Connection 1 auth :: ") + // console.dir(err) + // console.dir(r) + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NEW Connection 2 auth :: " + r) + // console.dir(err) + return self.s.pool.connectionAvailable(connection); + } + }); + } + }); + + // Connect the pool + self.s.pool.connect(); +} + +/** + * Destroy the server connection + * @method + */ +Server.prototype.destroy = function(emitClose, emitDestroy) { + var self = this; + if(self.s.logger.isDebug()) self.s.logger.debug(f('destroy called on server %s', self.name)); + + // Emit close + if(emitClose && self.listeners('close').length > 0) { + self.emit('close', null, self); + } + + // Emit destroy event + if(emitDestroy) self.emit('destroy', self); + // Set state as destroyed + self.s.state = DESTROYED; + // Close the pool + self.s.pool.destroy(); + // Flush out all the callbacks + if(self.s.callbacks) self.s.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + var self = this; + if(self.s.pool) return self.s.pool.isConnected(); + return false; +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + return this.s.state == DESTROYED; +} + +var executeSingleOperation = function(self, ns, cmd, queryOptions, options, onAll, callback) { + // Create a query instance + var query = new Query(self.s.bson, ns, cmd, queryOptions); + // Set slave OK + query.slaveOk = slaveOk(options.readPreference); + + // Notify query start to any read Preference strategies + if(self.s.readPreferenceStrategies != null) { + notifyStrategies(self, self.s, 'startOperation', [self, query, new Date()]); + } + + // Raw BSON response + var raw = typeof options.raw == 'boolean' ? options.raw : false; + + // Execute multiple queries + if(onAll) { + var connections = self.s.pool.getAll(); + var total = connections.length; + // We have an error + var error = null; + // Execute on all connections + for(var i = 0; i < connections.length; i++) { + // Command callback + var commandCallback = function(_connection) { + return function(err, result) { + if(err) error = err; + total = total - 1; + + // Done + if(total == 0) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, error, result, new Date()]); + if(error) return callback(MongoError.create(error)); + + // Add the connection details + result.hashedName = _connection.hashedName; + + // Execute callback, catch and rethrow if needed + try { + callback(null, new CommandResult(options.fullResult ? result : result.documents[0], connections)); + } catch(err) { + process.nextTick(function() { throw err}); + } + } + } + }; + + try { + query.incRequestId(); + connections[i].write(query.toBin()); + } catch(err) { + total = total - 1; + if(total == 0) return callback(MongoError.create(err)); + } + + // Return raw BSON docs + if(raw) { + commandCallback.raw = true; + } + + // Set the executed connection on the callback + commandCallback.connection = connections[i]; + + // Register the callback + self.s.callbacks.register(query.requestId, commandCallback(connections[i])); + } + + return; + } + + // Command callback + var commandCallback = function(err, result) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); + if(err) return callback(err); + // if(result && result.connection) { + // console.log("====== received result from connection " + result.connection.id) + // } + + if(result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || result.documents[0]['err'] + || result.documents[0]['code']) return callback(MongoError.create(result.documents[0])); + + // Add the connection details + result.hashedName = result.connection.hashedName; + + // Execute callback, catch and rethrow if needed + try { + callback(null, new CommandResult(options.fullResult ? result : result.documents[0], result.connection)); + } catch(err) { + process.nextTick(function() { throw err}); + } + }; + + try { + // Write the query out to the passed in connection or use the pool + // Passed in connections are used for authentication mechanisms + if(options.connection) { + // console.log("!!!!!!!!!!!!!!!!!!!!!! ONE") + // Add the reference to the connection to the callback so + // we can flush only the affected operations + commandCallback.connection = options.connection; + commandCallback.noRelease = true; + // Write out the command + options.connection.write(query.toBin()); + } else { + // console.log("!!!!!!!!!!!!!!!!!!!!!! TWO") + self.s.pool.write(query.toBin(), commandCallback, options); + } + + } catch(err) { + return callback(MongoError.create(err)); + } + + // Return raw BSON docs + if(raw) commandCallback.raw = true; + + // Register the callback + self.s.callbacks.register(query.requestId, commandCallback); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! execute command :: " + this.name) + // console.dir(cmd) + // console.dir(this.s.authProviders['scram-sha-1'].authStore) + // console.dir(Object.keys(options)) + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Ensure we have no options + options = options || {}; + + // Do we have a read Preference it need to be of type ReadPreference + if(options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error("readPreference must be an instance of ReadPreference"); + } + + // Debug log + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command [%s] against %s', JSON.stringify({ + ns: ns, cmd: cmd, options: debugOptions(debugFields, options) + }), self.name)); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // If we have no connection error + if(!self.s.pool.isConnected()) { + return callback(new MongoError(f("no connection available to server %s", self.name))); + } + + // Execute on all connections + var onAll = typeof options.onAll == 'boolean' ? options.onAll : false; + + // Check keys + var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys: false; + + // Serialize function + var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + + // Ignore undefined values + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + + // Raw BSON response + var raw = typeof options.raw == 'boolean' ? options.raw : false; + + // Query options + var queryOptions = { + numberToSkip: 0, numberToReturn: -1, checkKeys: checkKeys + }; + + // Set up the serialize functions and ignore undefined + if(serializeFunctions) queryOptions.serializeFunctions = serializeFunctions; + if(ignoreUndefined) queryOptions.ignoreUndefined = ignoreUndefined; + + // Single operation execution + executeSingleOperation(self, ns, cmd, queryOptions, options, onAll, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.insert(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + + // Execute write + return self.s.wireProtocolHandler.update(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.remove(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(mechanism, db) { + // console.log("=========================== SERVER.auth -- server -- " + this.s.id + " :: " + this.s.options.port) + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(self.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // If we have the default mechanism we pick mechanism based on the wire + // protocol max version. If it's >= 3 then scram-sha1 otherwise mongodb-cr + if(mechanism == 'default' && self.s.ismaster && self.s.ismaster.maxWireVersion >= 3) { + mechanism = 'scram-sha-1'; + } else if(mechanism == 'default') { + mechanism = 'mongocr'; + } + + // Get all available connections + var connections = self.s.pool.getAll(); + + // Actual arguments + var finalArguments = [self, connections, db].concat(args.slice(0)).concat([function(err, r) { + // console.log("=========================== SERVER.auth 0 :: " + self.s.id) + // console.dir(self.s.authProviders[mechanism].authStore) + // console.dir(err) + if(err) return callback(err); + if(!r) return callback(new MongoError('could not authenticate')); + callback(null, new Session({}, self)); + }]); + + // Let's invoke the auth mechanism + self.s.authProviders[mechanism].auth.apply(self.s.authProviders[mechanism], finalArguments); +} + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +Server.prototype.addReadPreferenceStrategy = function(name, strategy) { + var self = this; + if(self.s.readPreferenceStrategies == null) self.s.readPreferenceStrategies = {}; + self.s.readPreferenceStrategies[name] = strategy; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +Server.prototype.addAuthProvider = function(name, provider) { + // console.log("===== Server.prototype.addAuthProvider :: " + this.name) + var self = this; + self.s.authProviders[name] = provider; +} + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if(typeof server == 'string') return server == this.name; + + if(server && server.name) { + return server.name == this.name; + } + + return false; +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.getAll(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Server.prototype.getServer = function(options) { + return this; +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +Server.prototype.getConnection = function(options) { + return this.s.pool.get(); +} + +/** + * Get callbacks object + * @method + * @return {Callbacks} + */ +Server.prototype.getCallbacks = function() { + return this.s.callbacks; +} + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +Server.prototype.parserType = function() { + var s = this.s; + if(s.options.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +// // Command +// { +// find: ns +// , query: +// , limit: +// , fields: +// , skip: +// , hint: +// , explain: +// , snapshot: +// , batchSize: +// , returnKey: +// , maxScan: +// , min: +// , max: +// , showDiskLoc: +// , comment: +// , maxTimeMS: +// , raw: +// , readPreference: +// , tailable: +// , oplogReplay: +// , noCursorTimeout: +// , awaitdata: +// , exhaust: +// , partial: +// } + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.cursor = function(ns, cmd, cursorOptions) { + var s = this.s; + cursorOptions = cursorOptions || {}; + // Set up final cursor type + var FinalCursor = cursorOptions.cursorFactory || s.Cursor; + // Return the cursor + return new FinalCursor(s.bson, ns, cmd, cursorOptions, this, s.options); +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Server#close + * @type {Server} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Server#error + * @type {Server} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Server#timeout + * @type {Server} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Server#parseError + * @type {Server} + */ + +/** + * The server reestablished the connection + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * This is an insert result callback + * + * @callback opResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {CommandResult} command result + */ + +/** + * This is an authentication result callback + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {Session} an authenticated session + */ + +module.exports = Server; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js new file mode 100644 index 0000000..032c3c5 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js @@ -0,0 +1,93 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , EventEmitter = require('events').EventEmitter; + +/** + * Creates a new Authentication Session + * @class + * @param {object} [options] Options for the session + * @param {{Server}|{ReplSet}|{Mongos}} topology The topology instance underpinning the session + */ +var Session = function(options, topology) { + this.options = options; + this.topology = topology; + + // Add event listener + EventEmitter.call(this); +} + +inherits(Session, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {object} [options.readPreference] Specify read preference if command supports it + * @param {object} [options.connection] Specify connection object to execute command against + * @param {opResultCallback} callback A callback function + */ +Session.prototype.command = function(ns, cmd, options, callback) { + this.topology.command(ns, cmd, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.insert = function(ns, ops, options, callback) { + this.topology.insert(ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.update = function(ns, ops, options, callback) { + this.topology.update(ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.remove = function(ns, ops, options, callback) { + this.topology.remove(ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {boolean} [options.tailable=false] Tailable flag set + * @param {boolean} [options.oplogReply=false] oplogReply flag set + * @param {boolean} [options.awaitdata=false] awaitdata flag set + * @param {boolean} [options.exhaust=false] exhaust flag set + * @param {boolean} [options.partial=false] partial flag set + * @param {opResultCallback} callback A callback function + */ +Session.prototype.cursor = function(ns, cmd, options) { + return this.topology.cursor(ns, cmd, options); +} + +module.exports = Session; \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js new file mode 100644 index 0000000..4b7a1bb --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js @@ -0,0 +1,276 @@ +"use strict"; + +var Logger = require('../../connection/logger') + , EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format; + +/** + * Creates a new Ping read preference strategy instance + * @class + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) + * @return {Ping} A cursor instance + */ +var Ping = function(options) { + // Add event listener + EventEmitter.call(this); + + // Contains the ping state + this.s = { + // Contains all the ping data + pings: {} + // Set no options if none provided + , options: options || {} + // Logger + , logger: Logger('Ping', options) + // Ping interval + , pingInterval: options.pingInterval || 10000 + , acceptableLatency: options.acceptableLatency || 15 + // Debug options + , debug: typeof options.debug == 'boolean' ? options.debug : false + // Index + , index: 0 + // Current ping time + , lastPing: null + + } + + // Log the options set + if(this.s.logger.isDebug()) this.s.logger.debug(f('ping strategy interval [%s], acceptableLatency [%s]', this.s.pingInterval, this.s.acceptableLatency)); + + // If we have enabled debug + if(this.s.debug) { + // Add access to the read Preference Strategies + Object.defineProperty(this, 'data', { + enumerable: true, get: function() { return this.s.pings; } + }); + } +} + +inherits(Ping, EventEmitter); + +/** + * @ignore + */ +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tags = readPreference.tags; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) found = false; + } + + // Add to candidate list + if(found) filteredServers.push(servers[i]); + } + + // Returned filtered servers + return filteredServers; +} + +/** + * Pick a server + * @method + * @param {State} set The current replicaset state object + * @param {ReadPreference} readPreference The current readPreference object + * @param {readPreferenceResultCallback} callback The callback to return the result from the function + * @return {object} + */ +Ping.prototype.pickServer = function(set, readPreference) { + var self = this; + // Only get primary and secondaries as seeds + var seeds = {}; + var servers = []; + if(set.primary) { + servers.push(set.primary); + } + + for(var i = 0; i < set.secondaries.length; i++) { + servers.push(set.secondaries[i]); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Transform the list + var serverList = []; + // for(var name in seeds) { + for(var i = 0; i < servers.length; i++) { + serverList.push({name: servers[i].name, time: self.s.pings[servers[i].name] || 0}); + } + + // Sort by time + serverList.sort(function(a, b) { + return a.time > b.time; + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = serverList.length > 0 ? serverList[0].time : 0; + + // Filter by latency + serverList = serverList.filter(function(s) { + return s.time <= lowest + self.s.acceptableLatency; + }); + + // No servers, default to primary + if(serverList.length == 0 && set.primary) { + if(self.s.logger.isInfo()) self.s.logger.info(f('picked primary server [%s]', set.primary.name)); + return set.primary; + } else if(serverList.length == 0) { + return null + } + + // We picked first server + if(self.s.logger.isInfo()) self.s.logger.info(f('picked server [%s] with ping latency [%s]', serverList[0].name, serverList[0].time)); + + // Add to the index + self.s.index = self.s.index + 1; + // Select the index + self.s.index = self.s.index % serverList.length; + // Return the first server of the sorted and filtered list + return set.get(serverList[self.s.index].name); +} + +/** + * Start of an operation + * @method + * @param {Server} server The server the operation is running against + * @param {object} query The operation running + * @param {Date} date The start time of the operation + * @return {object} + */ +Ping.prototype.startOperation = function(server, query, date) { +} + +/** + * End of an operation + * @method + * @param {Server} server The server the operation is running against + * @param {error} err An error from the operation + * @param {object} result The result from the operation + * @param {Date} date The start time of the operation + * @return {object} + */ +Ping.prototype.endOperation = function(server, err, result, date) { +} + +/** + * High availability process running + * @method + * @param {State} set The current replicaset state object + * @param {resultCallback} callback The callback to return the result from the function + * @return {object} + */ +Ping.prototype.ha = function(topology, state, callback) { + var self = this; + var servers = state.getAll(); + var count = servers.length; + + // No servers return + if(servers.length == 0) return callback(null, null); + + // Return if we have not yet reached the ping interval + if(self.s.lastPing != null) { + var diff = new Date().getTime() - self.s.lastPing.getTime(); + if(diff < self.s.pingInterval) return callback(null, null); + } + + // Execute operation + var operation = function(_server) { + var start = new Date(); + // Execute ping against server + _server.command('system.$cmd', {ismaster:1}, function(err, r) { + count = count - 1; + var time = new Date().getTime() - start.getTime(); + self.s.pings[_server.name] = time; + // Log info for debug + if(self.s.logger.isDebug()) self.s.logger.debug(f('ha latency for server [%s] is [%s] ms', _server.name, time)); + // We are done with all the servers + if(count == 0) { + // Emit ping event + topology.emit('ping', err, r ? r.result : null); + // Update the last ping time + self.s.lastPing = new Date(); + // Return + callback(null, null); + } + }); + } + + // Let's ping all servers + while(servers.length > 0) { + operation(servers.shift()); + } +} + +var removeServer = function(self, server) { + delete self.s.pings[server.name]; +} + +/** + * Server connection closed + * @method + * @param {Server} server The server that closed + */ +Ping.prototype.close = function(server) { + removeServer(this, server); +} + +/** + * Server connection errored out + * @method + * @param {Server} server The server that errored out + */ +Ping.prototype.error = function(server) { + removeServer(this, server); +} + +/** + * Server connection timeout + * @method + * @param {Server} server The server that timed out + */ +Ping.prototype.timeout = function(server) { + removeServer(this, server); +} + +/** + * Server connection happened + * @method + * @param {Server} server The server that connected + * @param {resultCallback} callback The callback to return the result from the function + */ +Ping.prototype.connect = function(server, callback) { + var self = this; + // Get the command start date + var start = new Date(); + // Execute ping against server + server.command('system.$cmd', {ismaster:1}, function(err, r) { + var time = new Date().getTime() - start.getTime(); + self.s.pings[server.name] = time; + // Log info for debug + if(self.s.logger.isDebug()) self.s.logger.debug(f('connect latency for server [%s] is [%s] ms', server.name, time)); + // Set last ping + self.s.lastPing = new Date(); + // Done, return + callback(null, null); + }); +} + +/** + * This is a result from a readPreference strategy + * + * @callback readPreferenceResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {Server} server The server picked by the strategy + */ + +module.exports = Ping; \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js new file mode 100644 index 0000000..af062cb --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js @@ -0,0 +1,589 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +// Write concern fields +var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync']; + +var WireProtocol = function() {} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var legacy = typeof options.legacy == 'boolean' ? options.legacy : false; + ops = Array.isArray(ops) ? ops :[ops]; + + // If we have more than a 1000 ops fails + if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000")); + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callbacks, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(pool && pool.isConnected()) pool.write(killCursor.toBin(), callback, {immediateRelease:true}); + // Set cursor to 0 + cursorId = Long.ZERO; + // Return to caller + if(callback) callback(null, null); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, pool, callbacks, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId == 'number' + ? Long.fromNumber(r.cursorId) + : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Register a callback + callbacks.register(getMore.requestId, queryCallback); + // Write out the getMore command + pool.write(getMore.toBin(), queryCallback); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Does the cmd have a readPreference + if(cmd.readPreference) { + readPreference = cmd.readPreference; + } + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + if(cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Set up the serialize and ignoreUndefined fields + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; + if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; + if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Does the cmd have a readPreference + if(cmd.readPreference) { + readPreference = cmd.readPreference; + } + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) delete cmd['readConcern']; + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + finalCmd = { + '$query': finalCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +var hasWriteConcern = function(writeConcern) { + if(writeConcern.w + || writeConcern.wtimeout + || writeConcern.j == true + || writeConcern.fsync == true + || Object.keys(writeConcern).length == 0) { + return true; + } + return false; +} + +var cloneWriteConcern = function(writeConcern) { + var wc = {}; + if(writeConcern.w != null) wc.w = writeConcern.w; + if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout; + if(writeConcern.j != null) wc.j = writeConcern.j; + if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync; + return wc; +} + +// +// Aggregate up all the results +// +var aggregateWriteOperationResults = function(opType, ops, results, connection) { + var finalResult = { ok: 1, n: 0 } + + // Map all the results coming back + for(var i = 0; i < results.length; i++) { + var result = results[i]; + var op = ops[i]; + + if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) { + finalResult.upserted = []; + } + + // Push the upserted document to the list of upserted values + if(result.upserted) { + finalResult.upserted.push({index: i, _id: result.upserted}); + } + + // We have an upsert where we passed in a _id + if(result.updatedExisting == false && result.n == 1 && result.upserted == null) { + finalResult.upserted.push({index: i, _id: op.q._id}); + } + + // We have an insert command + if(result.ok == 1 && opType == 'insert' && result.err == null) { + finalResult.n = finalResult.n + 1; + } + + // We have a command error + if(result != null && result.ok == 0 || result.err || result.errmsg) { + if(result.ok == 0) finalResult.ok = 0; + finalResult.code = result.code; + finalResult.errmsg = result.errmsg || result.err || result.errMsg; + + // Check if we have a write error + if(result.code == 11000 + || result.code == 11001 + || result.code == 12582 + || result.code == 16544 + || result.code == 16538 + || result.code == 16542 + || result.code == 14 + || result.code == 13511) { + if(finalResult.writeErrors == null) finalResult.writeErrors = []; + finalResult.writeErrors.push({ + index: i + , code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + }); + } else { + finalResult.writeConcernError = { + code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + } + } + } else if(typeof result.n == 'number') { + finalResult.n += result.n; + } else { + finalResult.n += 1; + } + + // Result as expected + if(result != null && result.lastOp) finalResult.lastOp = result.lastOp; + } + + // Return finalResult aggregated results + return new CommandResult(finalResult, connection); +} + +// +// Execute all inserts in an ordered manner +// +var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + var _ops = ops.slice(0); + // Bind to current domain + callback = bindToCurrentDomain(callback); + // Collect all the getLastErrors + var getLastErrors = []; + + // Execute an operation + var executeOp = function(list, _callback) { + // No more items in the list + if(list.length == 0) { + return process.nextTick(function() { + _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); + }); + } + + // Get the first operation + var doc = list.shift(); + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options); + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + + // Get the db name + var db = ns.split('.').shift(); + + try { + // Add binary message to list of commands to execute + var commands = [op.toBin()]; + + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var i = 0; i < writeConcernFields.length; i++) { + if(writeConcern[writeConcernFields[i]] != null) { + getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]]; + } + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Add getLastError command to list of ops to execute + commands.push(getLastErrorOp.toBin()); + + // getLastError callback + var getLastErrorCallback = function(err, result) { + if(err) return callback(err); + // Get the document + var doc = result.documents[0]; + // Save the getLastError document + getLastErrors.push(doc); + + // If we have an error terminate + if(doc.ok == 0 || doc.err || doc.errmsg) { + return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection)); + } + + // Execute the next op in the list + executeOp(list, callback); + } + + // Register the callback + callbacks.register(getLastErrorOp.requestId, getLastErrorCallback); + // Write both commands out at the same time + pool.write(commands, getLastErrorCallback); + } else { + // Write both commands out at the same time + pool.write(commands, callback, {immediateRelease:true}); + } + } catch(err) { + if(typeof err == 'string') err = new MongoError(err); + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors.push({ ok: 1, errmsg: err.message, code: 14 }); + // Return due to an error + process.nextTick(function() { + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); + }); + } + } + + // Execute the operations + executeOp(_ops, callback); +} + +var executeUnordered = function(opType, command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + // Bind to current domain + callback = bindToCurrentDomain(callback); + // Total operations to write + var totalOps = ops.length; + // Collect all the getLastErrors + var getLastErrors = []; + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + // Driver level error + var error; + + // Execute all the operations + for(var i = 0; i < ops.length; i++) { + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options); + // Get db name + var db = ns.split('.').shift(); + + try { + // Add binary message to list of commands to execute + var commands = [op.toBin()]; + + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var j = 0; j < writeConcernFields.length; j++) { + if(writeConcern[writeConcernFields[j]] != null) + getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]]; + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Add getLastError command to list of ops to execute + commands.push(getLastErrorOp.toBin()); + + // Give the result from getLastError the right index + var callbackOp = function(_index) { + return function(err, result) { + if(err) error = err; + // Update the number of operations executed + totalOps = totalOps - 1; + // Save the getLastError document + if(!err) getLastErrors[_index] = result.documents[0]; + // Check if we are done + if(totalOps == 0) { + process.nextTick(function() { + if(error) return callback(error); + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, result.connection)); + }); + } + } + } + + // Register the callback + callbacks.register(getLastErrorOp.requestId, callbackOp(i)); + // Write both commands out at the same time + pool.write(commands, callbackOp(i)); + } else { + // Write both commands out at the same time + pool.write(commands, callback, {immediateRelease:true}); + } + } catch(err) { + if(typeof err == 'string') err = new MongoError(err); + // Update the number of operations executed + totalOps = totalOps - 1; + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors[i] = { ok: 1, errmsg: err.message, code: 14 }; + // Check if we are done + if(totalOps == 0) { + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, null)); + } + } + } + + // Empty w:0 return + if(writeConcern + && writeConcern.w == 0 && callback) { + callback(null, null); + } +} + +module.exports = WireProtocol; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js new file mode 100644 index 0000000..1dace34 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js @@ -0,0 +1,329 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +var WireProtocol = function() {} + +// +// Execute a write operation +var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern || {}; + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + // Did we specify a write concern + if(writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + // Options object + var opts = {}; + if(type == 'insert') opts.checkKeys = true; + // Ensure we support serialization of functions + if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; + if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; + // Execute command + topology.command(f("%s.$cmd", d), writeCommand, opts, callback); +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'update', 'updates', ns, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callbacks, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(pool && pool.isConnected()) pool.write(killCursor.toBin(), callback, {immediateRelease:true}); + // Set cursor to 0 + cursorId = Long.ZERO; + // Return to caller + if(callback) callback(null, null); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, pool, callbacks, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId == 'number' + ? Long.fromNumber(r.cursorId) + : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Register a callback + callbacks.register(getMore.requestId, queryCallback); + // Write out the getMore command + pool.write(getMore.toBin(), callback); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Does the cmd have a readPreference + if(cmd.readPreference) { + readPreference = cmd.readPreference; + } + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + if(cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + , serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') { + query.tailable = cmd.tailable; + } + + if(typeof cmd.oplogReplay == 'boolean') { + query.oplogReplay = cmd.oplogReplay; + } + + if(typeof cmd.noCursorTimeout == 'boolean') { + query.noCursorTimeout = cmd.noCursorTimeout; + } + + if(typeof cmd.awaitData == 'boolean') { + query.awaitData = cmd.awaitData; + } + + if(typeof cmd.exhaust == 'boolean') { + query.exhaust = cmd.exhaust; + } + + if(typeof cmd.partial == 'boolean') { + query.partial = cmd.partial; + } + + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Does the cmd have a readPreference + if(cmd.readPreference) { + readPreference = cmd.readPreference; + } + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) delete cmd['readConcern']; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + finalCmd = { + '$query': finalCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +module.exports = WireProtocol; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js new file mode 100644 index 0000000..aa1618d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js @@ -0,0 +1,520 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +var WireProtocol = function(legacyWireProtocol) { + this.legacyWireProtocol = legacyWireProtocol; +} + +// +// Execute a write operation +var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern; + + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + // Did we specify a write concern + if(writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + // Do we have bypassDocumentValidation set, then enable it on the write command + if(typeof options.bypassDocumentValidation == 'boolean') { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Options object + var opts = {}; + if(type == 'insert') opts.checkKeys = true; + // Ensure we support serialization of functions + if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; + if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; + // Execute command + topology.command(f("%s.$cmd", d), writeCommand, opts, callback); +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'update', 'updates', ns, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, pool, callbacks, callback) { + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + // Create getMore command + var killcursorCmd = { + killCursors: parts.join('.'), + cursors: [cursorId] + } + + // Build Query object + var query = new Query(bson, commandns, killcursorCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + }); + + // Set query flags + query.slaveOk = true; + + // Execute the kill cursor command + if(pool && pool.isConnected()) { + pool.write(query.toBin(), callback); + } + + // Kill cursor callback + var killCursorCallback = function(err, r) { + if(err) { + if(typeof callback != 'function') return; + return callback(err); + } + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + if(typeof callback != 'function') return; + return callback(new MongoError("cursor killed or timed out"), null); + } + + if(!Array.isArray(r.documents) || r.documents.length == 0) { + if(typeof callback != 'function') return; + return callback(new MongoError(f('invalid killCursors result returned for cursor id %s', cursorState.cursorId))); + } + + // Return the result + if(typeof callback == 'function') { + callback(null, r.documents[0]); + } + } + + // Register a callback + callbacks.register(query.requestId, killCursorCallback); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, pool, callbacks, options, callback) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + + // Check if we have an maxTimeMS set + var maxTimeMS = typeof cursorState.cmd.maxTimeMS == 'number' ? cursorState.cmd.maxTimeMS : 3000; + + // Create getMore command + var getMoreCmd = { + getMore: cursorState.cursorId, + collection: parts.join('.'), + batchSize: Math.abs(batchSize) + } + + if(cursorState.cmd.tailable + && typeof cursorState.cmd.maxAwaitTimeMS == 'number') { + getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; + } + + // Build Query object + var query = new Query(bson, commandns, getMoreCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + }); + + // Set query flags + query.slaveOk = true; + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Raw, return all the extracted documents + if(raw) { + cursorState.documents = r.documents; + cursorState.cursorId = r.cursorId; + return callback(null, r.documents); + } + + // We have an error detected + if(r.documents[0].ok == 0) { + return callback(MongoError.create(r.documents[0])); + } + + // Ensure we have a Long valid cursor id + var cursorId = typeof r.documents[0].cursor.id == 'number' + ? Long.fromNumber(r.documents[0].cursor.id) + : r.documents[0].cursor.id; + + // Set all the values + cursorState.documents = r.documents[0].cursor.nextBatch; + cursorState.cursorId = cursorId; + + // Return the result + callback(null, r.documents[0]); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Add the result field needed + queryCallback.documentsReturnedIn = 'nextBatch'; + + // Register a callback + callbacks.register(query.requestId, queryCallback); + // Write out the getMore command + pool.write(query.toBin(), queryCallback); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + if(cmd.exhaust) { + return this.legacyWireProtocol.command(bson, ns, cmd, cursorState, topology, options); + } + + // Create the find command + var query = executeFindCommand(bson, ns, cmd, cursorState, topology, options) + // Mark the cmd as virtual + cmd.virtual = false; + // Signal the documents are in the firstBatch value + query.documentsReturnedIn = 'firstBatch'; + // Return the query + return query; + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// // Command +// { +// find: ns +// , query: +// , limit: +// , fields: +// , skip: +// , hint: +// , explain: +// , snapshot: +// , batchSize: +// , returnKey: +// , maxScan: +// , min: +// , max: +// , showDiskLoc: +// , comment: +// , maxTimeMS: +// , raw: +// , readPreference: +// , tailable: +// , oplogReplay: +// , noCursorTimeout: +// , awaitdata: +// , exhaust: +// , partial: +// } + +// FIND/GETMORE SPEC +// { +// “find”: , +// “filter”: { ... }, +// “sort”: { ... }, +// “projection”: { ... }, +// “hint”: { ... }, +// “skip”: , +// “limit”: , +// “batchSize”: , +// “singleBatch”: , +// “comment”: , +// “maxScan”: , +// “maxTimeMS”: , +// “max”: { ... }, +// “min”: { ... }, +// “returnKey”: , +// “showRecordId”: , +// “snapshot”: , +// “tailable”: , +// “oplogReplay”: , +// “noCursorTimeout”: , +// “awaitData”: , +// “partial”: , +// “$readPreference”: { ... } +// } + +// +// Execute a find command +var executeFindCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Does the cmd have a readPreference + if(cmd.readPreference) { + readPreference = cmd.readPreference; + } + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + + // Build actual find command + var findCmd = { + find: parts.join('.') + }; + + // I we provided a filter + if(cmd.query) findCmd.filter = cmd.query; + + // Sort value + var sortValue = cmd.sort; + + // Handle issue of sort being an Array + if(Array.isArray(sortValue)) { + var sortObject = {}; + + if(sortValue.length > 0 && !Array.isArray(sortValue[0])) { + var sortDirection = sortValue[1]; + // Translate the sort order text + if(sortDirection == 'asc') { + sortDirection = 1; + } else if(sortDirection == 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[0]] = sortDirection; + } else { + for(var i = 0; i < sortValue.length; i++) { + var sortDirection = sortValue[i][1]; + // Translate the sort order text + if(sortDirection == 'asc') { + sortDirection = 1; + } else if(sortDirection == 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[i][0]] = sortDirection; + } + } + + sortValue = sortObject; + }; + + // Add sort to command + if(cmd.sort) findCmd.sort = sortValue; + // Add a projection to the command + if(cmd.fields) findCmd.projection = cmd.fields; + // Add a hint to the command + if(cmd.hint) findCmd.hint = cmd.hint; + // Add a skip + if(cmd.skip) findCmd.skip = cmd.skip; + // Add a limit + if(cmd.limit) findCmd.limit = cmd.limit; + // Add a batchSize + if(typeof cmd.batchSize == 'number') findCmd.batchSize = Math.abs(cmd.batchSize); + + // Check if we wish to have a singleBatch + if(cmd.limit < 0) { + findCmd.limit = Math.abs(cmd.limit); + findCmd.singleBatch = true; + } + + // If we have comment set + if(cmd.comment) findCmd.comment = cmd.comment; + + // If we have maxScan + if(cmd.maxScan) findCmd.maxScan = cmd.maxScan; + + // If we have maxTimeMS set + if(cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; + + // If we have min + if(cmd.min) findCmd.min = cmd.min; + + // If we have max + if(cmd.max) findCmd.max = cmd.max; + + // If we have returnKey set + if(cmd.returnKey) findCmd.returnKey = cmd.returnKey; + + // If we have showDiskLoc set + if(cmd.showDiskLoc) findCmd.showRecordId = cmd.showDiskLoc; + + // If we have snapshot set + if(cmd.snapshot) findCmd.snapshot = cmd.snapshot; + + // If we have tailable set + if(cmd.tailable) findCmd.tailable = cmd.tailable; + + // If we have oplogReplay set + if(cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; + + // If we have noCursorTimeout set + if(cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; + + // If we have awaitData set + if(cmd.awaitData) findCmd.awaitData = cmd.awaitData; + if(cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; + + // If we have partial set + if(cmd.partial) findCmd.partial = cmd.partial; + + // If we have explain, we need to rewrite the find command + // to wrap it in the explain command + if(cmd.explain) { + findCmd = { + explain: findCmd + } + } + + // Did we provide a readConcern + if(cmd.readConcern) findCmd.readConcern = cmd.readConcern; + + // Set up the serialize and ignoreUndefined fields + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + findCmd = { + '$query': findCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, commandns, findCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' + && readPreference + && readPreference.preference != 'primary') { + finalCmd = { + '$query': finalCmd, + '$readPreference': readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +module.exports = WireProtocol; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js new file mode 100644 index 0000000..9c665ee --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js @@ -0,0 +1,357 @@ +"use strict"; + +var MongoError = require('../error'); + +// Wire command operation ids +var OP_UPDATE = 2001; +var OP_INSERT = 2002; +var OP_DELETE = 2006; + +var Insert = function(requestId, ismaster, bson, ns, documents, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + if(!Array.isArray(documents) || documents.length == 0) throw new MongoError("documents array must contain at least one document to insert"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new MongoError("namespace cannot contain a null character"); + } + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.documents = documents; + this.ismaster = ismaster; + + // Ensure empty options + options = options || {}; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.continueOnError = typeof options.continueOnError == 'boolean' ? options.continueOnError : false; + // Set flags + this.flags = this.continueOnError ? 1 : 0; +} + +// To Binary +Insert.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // Flags + + Buffer.byteLength(this.ns) + 1 // namespace + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize all the documents + for(var i = 0; i < this.documents.length; i++) { + var buffer = this.bson.serialize(this.documents[i] + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + + // Document is larger than maxBsonObjectSize, terminate serialization + if(buffer.length > this.ismaster.maxBsonObjectSize) { + throw new MongoError("Document exceeds maximum allowed bson size of " + this.ismaster.maxBsonObjectSize + " bytes"); + } + + // Add to total length of wire protocol message + totalLength = totalLength + buffer.length; + // Add to buffer + buffers.push(buffer); + } + + // Command is larger than maxMessageSizeBytes terminate serialization + if(totalLength > this.ismaster.maxMessageSizeBytes) { + throw new MongoError("Command exceeds maximum message size of " + this.ismaster.maxMessageSizeBytes + " bytes"); + } + + // Add all the metadata + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_INSERT >> 24) & 0xff; + header[index + 2] = (OP_INSERT >> 16) & 0xff; + header[index + 1] = (OP_INSERT >> 8) & 0xff; + header[index] = (OP_INSERT) & 0xff; + index = index + 4; + + // Flags + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Return the buffers + return buffers; +} + +var Update = function(requestId, ismaster, bson, ns, update, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.upsert = typeof update[0].upsert == 'boolean' ? update[0].upsert : false; + this.multi = typeof update[0].multi == 'boolean' ? update[0].multi : false; + this.q = update[0].q; + this.u = update[0].u; + + // Create flag value + this.flags = this.upsert ? 1 : 0; + this.flags = this.multi ? this.flags | 2 : this.flags; +} + +// To Binary +Update.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // ZERO + + Buffer.byteLength(this.ns) + 1 // namespace + + 4 // Flags + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize the selector + var selector = this.bson.serialize(this.q + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(selector); + totalLength = totalLength + selector.length; + + // Serialize the update + var update = this.bson.serialize(this.u + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(update); + totalLength = totalLength + update.length; + + // Index in header buffer + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_UPDATE >> 24) & 0xff; + header[index + 2] = (OP_UPDATE >> 16) & 0xff; + header[index + 1] = (OP_UPDATE >> 8) & 0xff; + header[index] = (OP_UPDATE) & 0xff; + index = index + 4; + + // Write ZERO + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Flags + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +var Remove = function(requestId, ismaster, bson, ns, remove, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.limit = typeof remove[0].limit == 'number' ? remove[0].limit : 1; + this.q = remove[0].q; + + // Create flag value + this.flags = this.limit == 1 ? 1 : 0; +} + +// To Binary +Remove.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // ZERO + + Buffer.byteLength(this.ns) + 1 // namespace + + 4 // Flags + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize the selector + var selector = this.bson.serialize(this.q + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(selector); + totalLength = totalLength + selector.length; + + // Index in header buffer + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_DELETE >> 24) & 0xff; + header[index + 2] = (OP_DELETE >> 16) & 0xff; + header[index + 1] = (OP_DELETE >> 8) & 0xff; + header[index] = (OP_DELETE) & 0xff; + index = index + 4; + + // Write ZERO + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write ZERO + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +module.exports = { + Insert: Insert + , Update: Update + , Remove: Remove +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.npmignore b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.npmignore new file mode 100644 index 0000000..e920c16 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.npmignore @@ -0,0 +1,33 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +node_modules + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.travis.yml b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.travis.yml new file mode 100644 index 0000000..38de5c6 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "4.2.1" +sudo: false diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/LICENSE b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/LICENSE @@ -0,0 +1,201 @@ + 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/README.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/README.md new file mode 100644 index 0000000..c0323f0 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/README.md @@ -0,0 +1,2 @@ +# require_optional +Work around the problem that we do not have a optionalPeerDependencies concept in node.js making it a hassle to optionally include native modules diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js new file mode 100644 index 0000000..9754581 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/index.js @@ -0,0 +1,109 @@ +var path = require('path'), + fs = require('fs'), + f = require('util').format, + resolveFrom = require('resolve-from'), + semver = require('semver'); + +var exists = fs.existsSync || path.existsSync; + +var find_package_json = function(location) { + var found = false; + + while(!found) { + if (exists(location + '/package.json')) { + found = location; + } else if (location !== '/') { + location = path.dirname(location); + } else { + return false; + } + } + + return location; +} + +var require_optional = function(name, options) { + options = options || {}; + options.strict = typeof options.strict == 'boolean' ? options.strict : true; + + // Current location + var location = __dirname; + // Check if we have a parent + if(module.parent) { + location = module.parent.filename; + } + + // Locate this module's package.json file + var location = find_package_json(location); + if(!location) { + throw new Error('package.json can not be located'); + } + + // Read the package.json file + var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Is the name defined by interal file references + var parts = name.split(/\//); + + // Optional dependencies exist + if(!object.peerOptionalDependencies) { + throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in package.json', parts[0])); + } else if(object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]]) { + throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in package.json', parts[0])); + } + + // Unpack the expected version + var expectedVersions = object.peerOptionalDependencies[parts[0]]; + // The resolved package + var moduleEntry = undefined; + // Module file + var moduleEntryFile = name; + + try { + // Validate if it's possible to read the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + // Attempt to resolve in top level package + try { + // Get the module entry file + moduleEntryFile = resolveFrom(process.cwd(), name); + if(moduleEntryFile == null) return undefined; + // Attempt to resolve the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + if(err.code === 'MODULE_NOT_FOUND') return undefined; + } + } + + // Resolve the location of the module's package.json file + var location = find_package_json(require.resolve(moduleEntryFile)); + if(!location) { + throw new Error('package.json can not be located'); + } + + // Read the module file + var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Get the version + var version = dependentOnModule.version; + // Validate if the found module satisfies the version id + if(semver.satisfies(version, expectedVersions) == false + && options.strict) { + var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); + error.code = 'OPTIONAL_MODULE_NOT_FOUND'; + throw error; + } + + // Satifies the module requirement + return moduleEntry; +} + +require_optional.exists = function(name) { + try { + var m = require_optional(name); + if(m === undefined) return false; + return true; + } catch(err) { + return false; + } +} + +module.exports = require_optional; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver new file mode 120000 index 0000000..317eb29 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/index.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/index.js new file mode 100644 index 0000000..434159f --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/index.js @@ -0,0 +1,23 @@ +'use strict'; +var path = require('path'); +var Module = require('module'); + +module.exports = function (fromDir, moduleId) { + if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { + throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); + } + + fromDir = path.resolve(fromDir); + + var fromFile = path.join(fromDir, 'noop.js'); + + try { + return Module._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: Module._nodeModulePaths(fromDir) + }); + } catch (err) { + return null; + } +}; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/license b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/package.json new file mode 100644 index 0000000..37202ce --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/package.json @@ -0,0 +1,64 @@ +{ + "name": "resolve-from", + "version": "2.0.0", + "description": "Resolve the path of a module like require.resolve() but from a given path", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/resolve-from.git" + }, + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "require", + "resolve", + "path", + "module", + "from", + "like", + "path" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "gitHead": "583e0f8df06e1bc4d1c96d8d4f2484c745f522c3", + "bugs": { + "url": "https://github.com/sindresorhus/resolve-from/issues" + }, + "homepage": "https://github.com/sindresorhus/resolve-from", + "_id": "resolve-from@2.0.0", + "_shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", + "_from": "resolve-from@>=2.0.0 <3.0.0", + "_npmVersion": "2.14.7", + "_nodeVersion": "4.2.1", + "_npmUser": { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + }, + "dist": { + "shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", + "tarball": "http://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz" + }, + "maintainers": [ + { + "name": "sindresorhus", + "email": "sindresorhus@gmail.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/readme.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/readme.md new file mode 100644 index 0000000..bb4ca91 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/resolve-from/readme.md @@ -0,0 +1,58 @@ +# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) + +> Resolve the path of a module like [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve) but from a given path + +Unlike `require.resolve()` it returns `null` instead of throwing when the module can't be found. + + +## Install + +``` +$ npm install --save resolve-from +``` + + +## Usage + +```js +const resolveFrom = require('resolve-from'); + +// there's a file at `./foo/bar.js` + +resolveFrom('foo', './bar'); +//=> '/Users/sindresorhus/dev/test/foo/bar.js' +``` + + +## API + +### resolveFrom(fromDir, moduleId) + +#### fromDir + +Type: `string` + +Directory to resolve from. + +#### moduleId + +Type: `string` + +What you would use in `require()`. + + +## Tip + +Create a partial using a bound function if you want to require from the same `fromDir` multiple times: + +```js +const resolveFromFoo = resolveFrom.bind(null, 'foo'); + +resolveFromFoo('./bar'); +resolveFromFoo('./baz'); +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.npmignore b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.npmignore new file mode 100644 index 0000000..534108e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.npmignore @@ -0,0 +1,4 @@ +node_modules/ +coverage/ +.nyc_output/ +nyc_output/ diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.travis.yml b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.travis.yml new file mode 100644 index 0000000..991d04b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - 'iojs' diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/LICENSE b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/README.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/README.md new file mode 100644 index 0000000..0b14a7e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/README.md @@ -0,0 +1,327 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Usage + + $ npm install semver + + semver.valid('1.2.3') // '1.2.3' + semver.valid('a.b.c') // null + semver.clean(' =v1.2.3 ') // '1.2.3' + semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true + semver.gt('1.2.3', '9.8.7') // false + semver.lt('1.2.3', '9.8.7') // true + +As a command-line utility: + + $ semver -h + + Usage: semver [ [...]] [-r | -i | --preid | -l | -rv] + Test if version(s) satisfy the supplied range(s), and sort them. + + Multiple versions or ranges may be supplied, unless increment + option is specified. In that case, only a single version may + be used, and it is incremented by the specified level + + Program exits successfully if any valid version satisfies + all supplied ranges, and prints all satisfying versions. + + If no versions are valid, or ranges are not satisfied, + then exits failure. + + Versions are printed in ascending order, so supplying + multiple versions to the utility will just sort them. + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +> semver.inc('1.2.3', 'prerelease', 'beta') +'1.2.4-beta.0' +``` + +command-line example: + +```shell +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```shell +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero digit in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9']['0'-'9']+ +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `loose` boolean argument that, if +true, will be more forgiving about not-quite-valid semver strings. +The resulting output will always be 100% strict, of course. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/bin/semver b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/bin/semver new file mode 100755 index 0000000..c5f2e85 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/bin/semver @@ -0,0 +1,133 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + , versions = [] + , range = [] + , gt = [] + , lt = [] + , eq = [] + , inc = null + , version = require("../package.json").version + , loose = false + , identifier = undefined + , semver = require("../semver") + , reverse = false + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var i = a.indexOf('=') + if (i !== -1) { + a = a.slice(0, i) + argv.unshift(a.slice(i + 1)) + } + switch (a) { + case "-rv": case "-rev": case "--rev": case "--reverse": + reverse = true + break + case "-l": case "--loose": + loose = true + break + case "-v": case "--version": + versions.push(argv.shift()) + break + case "-i": case "--inc": case "--increment": + switch (argv[0]) { + case "major": case "minor": case "patch": case "prerelease": + case "premajor": case "preminor": case "prepatch": + inc = argv.shift() + break + default: + inc = "patch" + break + } + break + case "--preid": + identifier = argv.shift() + break + case "-r": case "--range": + range.push(argv.shift()) + break + case "-h": case "--help": case "-?": + return help() + default: + versions.push(a) + break + } + } + + versions = versions.filter(function (v) { + return semver.valid(v, loose) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) + return failInc() + + for (var i = 0, l = range.length; i < l ; i ++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], loose) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error("--inc can only be used on a single version with no range") + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? "rcompare" : "compare" + versions.sort(function (a, b) { + return semver[compare](a, b, loose) + }).map(function (v) { + return semver.clean(v, loose) + }).map(function (v) { + return inc ? semver.inc(v, inc, loose, identifier) : v + }).forEach(function (v,i,_) { console.log(v) }) +} + +function help () { + console.log(["SemVer " + version + ,"" + ,"A JavaScript implementation of the http://semver.org/ specification" + ,"Copyright Isaac Z. Schlueter" + ,"" + ,"Usage: semver [options] [ [...]]" + ,"Prints valid versions sorted by SemVer precedence" + ,"" + ,"Options:" + ,"-r --range " + ," Print versions that match the specified range." + ,"" + ,"-i --increment []" + ," Increment a version by the specified level. Level can" + ," be one of: major, minor, patch, premajor, preminor," + ," prepatch, or prerelease. Default level is 'patch'." + ," Only one version may be specified." + ,"" + ,"--preid " + ," Identifier to be used to prefix premajor, preminor," + ," prepatch or prerelease version increments." + ,"" + ,"-l --loose" + ," Interpret versions and ranges loosely" + ,"" + ,"Program exits successfully if any valid version satisfies" + ,"all supplied ranges, and prints all satisfying versions." + ,"" + ,"If no satisfying versions are found, then exits failure." + ,"" + ,"Versions are printed in ascending order, so supplying" + ,"multiple versions to the utility will just sort them." + ].join("\n")) +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/package.json new file mode 100644 index 0000000..f153fd8 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/package.json @@ -0,0 +1,51 @@ +{ + "name": "semver", + "version": "5.1.0", + "description": "The semantic version parser used by npm.", + "main": "semver.js", + "scripts": { + "test": "tap test/*.js" + }, + "devDependencies": { + "tap": "^2.0.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "./bin/semver" + }, + "gitHead": "8e33a30e62e40e4983d1c5f55e794331b861aadc", + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "homepage": "https://github.com/npm/node-semver#readme", + "_id": "semver@5.1.0", + "_shasum": "85f2cf8550465c4df000cf7d86f6b054106ab9e5", + "_from": "semver@>=5.1.0 <6.0.0", + "_npmVersion": "3.3.2", + "_nodeVersion": "4.0.0", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "dist": { + "shasum": "85f2cf8550465c4df000cf7d86f6b054106ab9e5", + "tarball": "http://registry.npmjs.org/semver/-/semver-5.1.0.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "isaacs@npmjs.com" + }, + { + "name": "othiym23", + "email": "ogd@aoaioxxysz.net" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/semver/-/semver-5.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/range.bnf b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/range.bnf new file mode 100644 index 0000000..000df92 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9']['0'-'9']+ +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/semver.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/semver.js new file mode 100644 index 0000000..71795f6 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/semver.js @@ -0,0 +1,1188 @@ +exports = module.exports = SemVer; + +// The debug function is excluded entirely from the minified version. +/* nomin */ var debug; +/* nomin */ if (typeof process === 'object' && + /* nomin */ process.env && + /* nomin */ process.env.NODE_DEBUG && + /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ debug = function() { + /* nomin */ var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ args.unshift('SEMVER'); + /* nomin */ console.log.apply(console, args); + /* nomin */ }; +/* nomin */ else + /* nomin */ debug = function() {}; + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; + +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; + +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; + + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; + +src[FULL] = '^' + FULLPLAIN + '$'; + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; + +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; + +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; + +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; + +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; + +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; + +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; + + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; + +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; + +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) + re[i] = new RegExp(src[i]); +} + +exports.parse = parse; +function parse(version, loose) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + if (version.length > MAX_LENGTH) + return null; + + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; + + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } +} + +exports.valid = valid; +function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; +} + + +exports.clean = clean; +function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; +} + +exports.SemVer = SemVer; + +function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + if (!(this instanceof SemVer)) + return new SemVer(version, loose); + + debug('SemVer', version, loose); + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + + if (!m) + throw new TypeError('Invalid Version: ' + version); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') + + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num + } + return id; + }); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} + +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; + +SemVer.prototype.toString = function() { + return this.version; +}; + +SemVer.prototype.compare = function(other) { + debug('SemVer.compare', this.version, this.loose, other); + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); +}; + +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; + + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); +}; + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + this.raw = this.version; + return this; +}; + +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } +} + +exports.compareIdentifiers = compareIdentifiers; + +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} + +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} + +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} + +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} + +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} + +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(b); +} + +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} + +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} + +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} + +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} + +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} + +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} + +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} + +exports.Comparator = Comparator; +function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) + return comp; + else + comp = comp.value; + } + + if (!(this instanceof Comparator)) + return new Comparator(comp, loose); + + debug('comparator', comp, loose); + this.loose = loose; + this.parse(comp); + + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; + + debug('comp', this); +} + +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) + throw new TypeError('Invalid comparator: ' + comp); + + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.loose); +}; + +Comparator.prototype.toString = function() { + return this.value; +}; + +Comparator.prototype.test = function(version) { + debug('Comparator.test', version, this.loose); + + if (this.semver === ANY) + return true; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + return cmp(version, this.operator, this.semver, this.loose); +}; + + +exports.Range = Range; +function Range(range, loose) { + if ((range instanceof Range) && range.loose === loose) + return range; + + if (!(this instanceof Range)) + return new Range(range, loose); + + this.loose = loose; + + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function() { + return this.range; +}; + +Range.prototype.parseRange = function(range) { + var loose = this.loose; + range = range.trim(); + debug('range', range, loose); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, loose); + }); + + return set; +}; + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, loose) { + return new Range(range, loose).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, loose) { + debug('comp', comp); + comp = replaceCarets(comp, loose); + debug('caret', comp); + comp = replaceTildes(comp, loose); + debug('tildes', comp); + comp = replaceXRanges(comp, loose); + debug('xrange', comp); + comp = replaceStars(comp, loose); + debug('stars', comp); + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, loose); + }).join(' '); +} + +function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0- <1.3.0- + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + + debug('tilde return', ret); + return ret; + }); +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, loose); + }).join(' '); +} + +function replaceCaret(comp, loose) { + debug('caret', comp, loose); + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + + debug('caret return', ret); + return ret; + }); +} + +function replaceXRanges(comp, loose) { + debug('replaceXRanges', comp, loose); + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, loose); + }).join(' '); +} + +function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) + gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) + M = +M + 1 + else + m = +m + 1 + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + + return ret; + }); +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, loose) { + debug('replaceStars', comp, loose); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; + + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; + + return (from + ' ' + to).trim(); +} + + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) + return true; + } + return false; +}; + +function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } + + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) + continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false; + } + + return true; +} + +exports.satisfies = satisfies; +function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, loose) { + return versions.filter(function(version) { + return satisfies(version, range, loose); + }).sort(function(a, b) { + return rcompare(a, b, loose); + })[0] || null; +} + +exports.validRange = validRange; +function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, loose) { + return outside(version, range, '<', loose); +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, loose) { + return outside(version, range, '>', loose); +} + +exports.outside = outside; +function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, loose)) { + return false; + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/big-numbers.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/big-numbers.js new file mode 100644 index 0000000..c051864 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/big-numbers.js @@ -0,0 +1,31 @@ +var test = require('tap').test +var semver = require('../') + +test('long version is too long', function (t) { + var v = '1.2.' + new Array(256).join('1') + t.throws(function () { + new semver.SemVer(v) + }) + t.equal(semver.valid(v, false), null) + t.equal(semver.valid(v, true), null) + t.equal(semver.inc(v, 'patch'), null) + t.end() +}) + +test('big number is like too long version', function (t) { + var v = '1.2.' + new Array(100).join('1') + t.throws(function () { + new semver.SemVer(v) + }) + t.equal(semver.valid(v, false), null) + t.equal(semver.valid(v, true), null) + t.equal(semver.inc(v, 'patch'), null) + t.end() +}) + +test('parsing null does not throw', function (t) { + t.equal(semver.parse(null), null) + t.equal(semver.parse({}), null) + t.equal(semver.parse(new semver.SemVer('1.2.3')).version, '1.2.3') + t.end() +}) diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/clean.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/clean.js new file mode 100644 index 0000000..9e268de --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/clean.js @@ -0,0 +1,29 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var clean = semver.clean; + +test('\nclean tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.2.3', '1.2.3'], + [' 1.2.3 ', '1.2.3'], + [' 1.2.3-4 ', '1.2.3-4'], + [' 1.2.3-pre ', '1.2.3-pre'], + [' =v1.2.3 ', '1.2.3'], + ['v1.2.3', '1.2.3'], + [' v1.2.3 ', '1.2.3'], + ['\t1.2.3', '1.2.3'], + ['>1.2.3', null], + ['~1.2.3', null], + ['<=1.2.3', null], + ['1.2.x', null] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var msg = 'clean(' + range + ') = ' + version; + t.equal(clean(range), version, msg); + }); + t.end(); +}); diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/gtr.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/gtr.js new file mode 100644 index 0000000..bbb8789 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/gtr.js @@ -0,0 +1,173 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var gtr = semver.gtr; + +test('\ngtr tests', function(t) { + // [range, version, loose] + // Version should be greater than range + [ + ['~1.2.2', '1.3.0'], + ['~0.6.1-1', '0.7.1-1'], + ['1.0.0 - 2.0.0', '2.0.1'], + ['1.0.0', '1.0.1-beta1'], + ['1.0.0', '2.0.0'], + ['<=2.0.0', '2.1.1'], + ['<=2.0.0', '3.2.9'], + ['<2.0.0', '2.0.0'], + ['0.1.20 || 1.2.4', '1.2.5'], + ['2.x.x', '3.0.0'], + ['1.2.x', '1.3.0'], + ['1.2.x || 2.x', '3.0.0'], + ['2.*.*', '5.0.1'], + ['1.2.*', '1.3.3'], + ['1.2.* || 2.*', '4.0.0'], + ['2', '3.0.0'], + ['2.3', '2.4.2'], + ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.5.5'], + ['~>3.2.1', '3.3.0'], // >=3.2.1 <3.3.0 + ['~1', '2.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '2.2.4'], + ['~> 1', '3.2.3'], + ['~1.0', '1.1.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '1.1.0'], + ['<1.2', '1.2.0'], + ['< 1.2', '1.2.1'], + ['1', '2.0.0beta', true], + ['~v0.5.4-pre', '0.6.0'], + ['~v0.5.4-pre', '0.6.1-pre'], + ['=0.7.x', '0.8.0'], + ['=0.7.x', '0.8.0-asdf'], + ['<0.7.x', '0.7.0'], + ['~1.2.2', '1.3.0'], + ['1.0.0 - 2.0.0', '2.2.3'], + ['1.0.0', '1.0.1'], + ['<=2.0.0', '3.0.0'], + ['<=2.0.0', '2.9999.9999'], + ['<=2.0.0', '2.2.9'], + ['<2.0.0', '2.9999.9999'], + ['<2.0.0', '2.2.9'], + ['2.x.x', '3.1.3'], + ['1.2.x', '1.3.3'], + ['1.2.x || 2.x', '3.1.3'], + ['2.*.*', '3.1.3'], + ['1.2.*', '1.3.3'], + ['1.2.* || 2.*', '3.1.3'], + ['2', '3.1.2'], + ['2.3', '2.4.1'], + ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 + ['~>3.2.1', '3.3.2'], // >=3.2.1 <3.3.0 + ['~1', '2.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '2.2.3'], + ['~1.0', '1.1.0'], // >=1.0.0 <1.1.0 + ['<1', '1.0.0'], + ['1', '2.0.0beta', true], + ['<1', '1.0.0beta', true], + ['< 1', '1.0.0beta', true], + ['=0.7.x', '0.8.2'], + ['<0.7.x', '0.7.2'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'gtr(' + version + ', ' + range + ', ' + loose + ')'; + t.ok(gtr(version, range, loose), msg); + }); + t.end(); +}); + +test('\nnegative gtr tests', function(t) { + // [range, version, loose] + // Version should NOT be greater than range + [ + ['~0.6.1-1', '0.6.1-1'], + ['1.0.0 - 2.0.0', '1.2.3'], + ['1.0.0 - 2.0.0', '0.9.9'], + ['1.0.0', '1.0.0'], + ['>=*', '0.2.4'], + ['', '1.0.0', true], + ['*', '1.2.3'], + ['*', 'v1.2.3-foo'], + ['>=1.0.0', '1.0.0'], + ['>=1.0.0', '1.0.1'], + ['>=1.0.0', '1.1.0'], + ['>1.0.0', '1.0.1'], + ['>1.0.0', '1.1.0'], + ['<=2.0.0', '2.0.0'], + ['<=2.0.0', '1.9999.9999'], + ['<=2.0.0', '0.2.9'], + ['<2.0.0', '1.9999.9999'], + ['<2.0.0', '0.2.9'], + ['>= 1.0.0', '1.0.0'], + ['>= 1.0.0', '1.0.1'], + ['>= 1.0.0', '1.1.0'], + ['> 1.0.0', '1.0.1'], + ['> 1.0.0', '1.1.0'], + ['<= 2.0.0', '2.0.0'], + ['<= 2.0.0', '1.9999.9999'], + ['<= 2.0.0', '0.2.9'], + ['< 2.0.0', '1.9999.9999'], + ['<\t2.0.0', '0.2.9'], + ['>=0.1.97', 'v0.1.97'], + ['>=0.1.97', '0.1.97'], + ['0.1.20 || 1.2.4', '1.2.4'], + ['0.1.20 || >1.2.4', '1.2.4'], + ['0.1.20 || 1.2.4', '1.2.3'], + ['0.1.20 || 1.2.4', '0.1.20'], + ['>=0.2.3 || <0.0.1', '0.0.0'], + ['>=0.2.3 || <0.0.1', '0.2.3'], + ['>=0.2.3 || <0.0.1', '0.2.4'], + ['||', '1.3.4'], + ['2.x.x', '2.1.3'], + ['1.2.x', '1.2.3'], + ['1.2.x || 2.x', '2.1.3'], + ['1.2.x || 2.x', '1.2.3'], + ['x', '1.2.3'], + ['2.*.*', '2.1.3'], + ['1.2.*', '1.2.3'], + ['1.2.* || 2.*', '2.1.3'], + ['1.2.* || 2.*', '1.2.3'], + ['1.2.* || 2.*', '1.2.3'], + ['*', '1.2.3'], + ['2', '2.1.2'], + ['2.3', '2.3.1'], + ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.4.5'], + ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0 + ['~1', '1.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '1.2.3'], + ['~> 1', '1.2.3'], + ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '1.0.2'], + ['>=1', '1.0.0'], + ['>= 1', '1.0.0'], + ['<1.2', '1.1.1'], + ['< 1.2', '1.1.1'], + ['1', '1.0.0beta', true], + ['~v0.5.4-pre', '0.5.5'], + ['~v0.5.4-pre', '0.5.4'], + ['=0.7.x', '0.7.2'], + ['>=0.7.x', '0.7.2'], + ['=0.7.x', '0.7.0-asdf'], + ['>=0.7.x', '0.7.0-asdf'], + ['<=0.7.x', '0.6.2'], + ['>0.2.3 >0.2.4 <=0.2.5', '0.2.5'], + ['>=0.2.3 <=0.2.4', '0.2.4'], + ['1.0.0 - 2.0.0', '2.0.0'], + ['^1', '0.0.0-0'], + ['^3.0.0', '2.0.0'], + ['^1.0.0 || ~2.0.1', '2.0.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '3.2.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '1.0.0beta', true], + ['^0.1.0 || ~3.0.1 || 5.0.0', '5.0.0-0', true], + ['^0.1.0 || ~3.0.1 || >4 <=5.0.0', '3.5.0'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = '!gtr(' + version + ', ' + range + ', ' + loose + ')'; + t.notOk(gtr(version, range, loose), msg); + }); + t.end(); +}); diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/index.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/index.js new file mode 100644 index 0000000..47c3f5f --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/index.js @@ -0,0 +1,698 @@ +'use strict'; + +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var eq = semver.eq; +var gt = semver.gt; +var lt = semver.lt; +var neq = semver.neq; +var cmp = semver.cmp; +var gte = semver.gte; +var lte = semver.lte; +var satisfies = semver.satisfies; +var validRange = semver.validRange; +var inc = semver.inc; +var diff = semver.diff; +var replaceStars = semver.replaceStars; +var toComparators = semver.toComparators; +var SemVer = semver.SemVer; +var Range = semver.Range; + +test('\ncomparison tests', function(t) { + // [version1, version2] + // version1 should be greater than version2 + [['0.0.0', '0.0.0-foo'], + ['0.0.1', '0.0.0'], + ['1.0.0', '0.9.9'], + ['0.10.0', '0.9.0'], + ['0.99.0', '0.10.0'], + ['2.0.0', '1.2.3'], + ['v0.0.0', '0.0.0-foo', true], + ['v0.0.1', '0.0.0', true], + ['v1.0.0', '0.9.9', true], + ['v0.10.0', '0.9.0', true], + ['v0.99.0', '0.10.0', true], + ['v2.0.0', '1.2.3', true], + ['0.0.0', 'v0.0.0-foo', true], + ['0.0.1', 'v0.0.0', true], + ['1.0.0', 'v0.9.9', true], + ['0.10.0', 'v0.9.0', true], + ['0.99.0', 'v0.10.0', true], + ['2.0.0', 'v1.2.3', true], + ['1.2.3', '1.2.3-asdf'], + ['1.2.3', '1.2.3-4'], + ['1.2.3', '1.2.3-4-foo'], + ['1.2.3-5-foo', '1.2.3-5'], + ['1.2.3-5', '1.2.3-4'], + ['1.2.3-5-foo', '1.2.3-5-Foo'], + ['3.0.0', '2.7.2+asdf'], + ['1.2.3-a.10', '1.2.3-a.5'], + ['1.2.3-a.b', '1.2.3-a.5'], + ['1.2.3-a.b', '1.2.3-a'], + ['1.2.3-a.b.c.10.d.5', '1.2.3-a.b.c.5.d.100'], + ['1.2.3-r2', '1.2.3-r100'], + ['1.2.3-r100', '1.2.3-R2'] + ].forEach(function(v) { + var v0 = v[0]; + var v1 = v[1]; + var loose = v[2]; + t.ok(gt(v0, v1, loose), "gt('" + v0 + "', '" + v1 + "')"); + t.ok(lt(v1, v0, loose), "lt('" + v1 + "', '" + v0 + "')"); + t.ok(!gt(v1, v0, loose), "!gt('" + v1 + "', '" + v0 + "')"); + t.ok(!lt(v0, v1, loose), "!lt('" + v0 + "', '" + v1 + "')"); + t.ok(eq(v0, v0, loose), "eq('" + v0 + "', '" + v0 + "')"); + t.ok(eq(v1, v1, loose), "eq('" + v1 + "', '" + v1 + "')"); + t.ok(neq(v0, v1, loose), "neq('" + v0 + "', '" + v1 + "')"); + t.ok(cmp(v1, '==', v1, loose), "cmp('" + v1 + "' == '" + v1 + "')"); + t.ok(cmp(v0, '>=', v1, loose), "cmp('" + v0 + "' >= '" + v1 + "')"); + t.ok(cmp(v1, '<=', v0, loose), "cmp('" + v1 + "' <= '" + v0 + "')"); + t.ok(cmp(v0, '!=', v1, loose), "cmp('" + v0 + "' != '" + v1 + "')"); + }); + t.end(); +}); + +test('\nequality tests', function(t) { + // [version1, version2] + // version1 should be equivalent to version2 + [['1.2.3', 'v1.2.3', true], + ['1.2.3', '=1.2.3', true], + ['1.2.3', 'v 1.2.3', true], + ['1.2.3', '= 1.2.3', true], + ['1.2.3', ' v1.2.3', true], + ['1.2.3', ' =1.2.3', true], + ['1.2.3', ' v 1.2.3', true], + ['1.2.3', ' = 1.2.3', true], + ['1.2.3-0', 'v1.2.3-0', true], + ['1.2.3-0', '=1.2.3-0', true], + ['1.2.3-0', 'v 1.2.3-0', true], + ['1.2.3-0', '= 1.2.3-0', true], + ['1.2.3-0', ' v1.2.3-0', true], + ['1.2.3-0', ' =1.2.3-0', true], + ['1.2.3-0', ' v 1.2.3-0', true], + ['1.2.3-0', ' = 1.2.3-0', true], + ['1.2.3-1', 'v1.2.3-1', true], + ['1.2.3-1', '=1.2.3-1', true], + ['1.2.3-1', 'v 1.2.3-1', true], + ['1.2.3-1', '= 1.2.3-1', true], + ['1.2.3-1', ' v1.2.3-1', true], + ['1.2.3-1', ' =1.2.3-1', true], + ['1.2.3-1', ' v 1.2.3-1', true], + ['1.2.3-1', ' = 1.2.3-1', true], + ['1.2.3-beta', 'v1.2.3-beta', true], + ['1.2.3-beta', '=1.2.3-beta', true], + ['1.2.3-beta', 'v 1.2.3-beta', true], + ['1.2.3-beta', '= 1.2.3-beta', true], + ['1.2.3-beta', ' v1.2.3-beta', true], + ['1.2.3-beta', ' =1.2.3-beta', true], + ['1.2.3-beta', ' v 1.2.3-beta', true], + ['1.2.3-beta', ' = 1.2.3-beta', true], + ['1.2.3-beta+build', ' = 1.2.3-beta+otherbuild', true], + ['1.2.3+build', ' = 1.2.3+otherbuild', true], + ['1.2.3-beta+build', '1.2.3-beta+otherbuild'], + ['1.2.3+build', '1.2.3+otherbuild'], + [' v1.2.3+build', '1.2.3+otherbuild'] + ].forEach(function(v) { + var v0 = v[0]; + var v1 = v[1]; + var loose = v[2]; + t.ok(eq(v0, v1, loose), "eq('" + v0 + "', '" + v1 + "')"); + t.ok(!neq(v0, v1, loose), "!neq('" + v0 + "', '" + v1 + "')"); + t.ok(cmp(v0, '==', v1, loose), 'cmp(' + v0 + '==' + v1 + ')'); + t.ok(!cmp(v0, '!=', v1, loose), '!cmp(' + v0 + '!=' + v1 + ')'); + t.ok(!cmp(v0, '===', v1, loose), '!cmp(' + v0 + '===' + v1 + ')'); + t.ok(cmp(v0, '!==', v1, loose), 'cmp(' + v0 + '!==' + v1 + ')'); + t.ok(!gt(v0, v1, loose), "!gt('" + v0 + "', '" + v1 + "')"); + t.ok(gte(v0, v1, loose), "gte('" + v0 + "', '" + v1 + "')"); + t.ok(!lt(v0, v1, loose), "!lt('" + v0 + "', '" + v1 + "')"); + t.ok(lte(v0, v1, loose), "lte('" + v0 + "', '" + v1 + "')"); + }); + t.end(); +}); + + +test('\nrange tests', function(t) { + // [range, version] + // version should be included by range + [['1.0.0 - 2.0.0', '1.2.3'], + ['^1.2.3+build', '1.2.3'], + ['^1.2.3+build', '1.3.0'], + ['1.2.3-pre+asdf - 2.4.3-pre+asdf', '1.2.3'], + ['1.2.3pre+asdf - 2.4.3-pre+asdf', '1.2.3', true], + ['1.2.3-pre+asdf - 2.4.3pre+asdf', '1.2.3', true], + ['1.2.3pre+asdf - 2.4.3pre+asdf', '1.2.3', true], + ['1.2.3-pre+asdf - 2.4.3-pre+asdf', '1.2.3-pre.2'], + ['1.2.3-pre+asdf - 2.4.3-pre+asdf', '2.4.3-alpha'], + ['1.2.3+asdf - 2.4.3+asdf', '1.2.3'], + ['1.0.0', '1.0.0'], + ['>=*', '0.2.4'], + ['', '1.0.0'], + ['*', '1.2.3'], + ['*', 'v1.2.3', true], + ['>=1.0.0', '1.0.0'], + ['>=1.0.0', '1.0.1'], + ['>=1.0.0', '1.1.0'], + ['>1.0.0', '1.0.1'], + ['>1.0.0', '1.1.0'], + ['<=2.0.0', '2.0.0'], + ['<=2.0.0', '1.9999.9999'], + ['<=2.0.0', '0.2.9'], + ['<2.0.0', '1.9999.9999'], + ['<2.0.0', '0.2.9'], + ['>= 1.0.0', '1.0.0'], + ['>= 1.0.0', '1.0.1'], + ['>= 1.0.0', '1.1.0'], + ['> 1.0.0', '1.0.1'], + ['> 1.0.0', '1.1.0'], + ['<= 2.0.0', '2.0.0'], + ['<= 2.0.0', '1.9999.9999'], + ['<= 2.0.0', '0.2.9'], + ['< 2.0.0', '1.9999.9999'], + ['<\t2.0.0', '0.2.9'], + ['>=0.1.97', 'v0.1.97', true], + ['>=0.1.97', '0.1.97'], + ['0.1.20 || 1.2.4', '1.2.4'], + ['>=0.2.3 || <0.0.1', '0.0.0'], + ['>=0.2.3 || <0.0.1', '0.2.3'], + ['>=0.2.3 || <0.0.1', '0.2.4'], + ['||', '1.3.4'], + ['2.x.x', '2.1.3'], + ['1.2.x', '1.2.3'], + ['1.2.x || 2.x', '2.1.3'], + ['1.2.x || 2.x', '1.2.3'], + ['x', '1.2.3'], + ['2.*.*', '2.1.3'], + ['1.2.*', '1.2.3'], + ['1.2.* || 2.*', '2.1.3'], + ['1.2.* || 2.*', '1.2.3'], + ['*', '1.2.3'], + ['2', '2.1.2'], + ['2.3', '2.3.1'], + ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.4.5'], + ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0, + ['~1', '1.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '1.2.3'], + ['~> 1', '1.2.3'], + ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0, + ['~ 1.0', '1.0.2'], + ['~ 1.0.3', '1.0.12'], + ['>=1', '1.0.0'], + ['>= 1', '1.0.0'], + ['<1.2', '1.1.1'], + ['< 1.2', '1.1.1'], + ['~v0.5.4-pre', '0.5.5'], + ['~v0.5.4-pre', '0.5.4'], + ['=0.7.x', '0.7.2'], + ['<=0.7.x', '0.7.2'], + ['>=0.7.x', '0.7.2'], + ['<=0.7.x', '0.6.2'], + ['~1.2.1 >=1.2.3', '1.2.3'], + ['~1.2.1 =1.2.3', '1.2.3'], + ['~1.2.1 1.2.3', '1.2.3'], + ['~1.2.1 >=1.2.3 1.2.3', '1.2.3'], + ['~1.2.1 1.2.3 >=1.2.3', '1.2.3'], + ['~1.2.1 1.2.3', '1.2.3'], + ['>=1.2.1 1.2.3', '1.2.3'], + ['1.2.3 >=1.2.1', '1.2.3'], + ['>=1.2.3 >=1.2.1', '1.2.3'], + ['>=1.2.1 >=1.2.3', '1.2.3'], + ['>=1.2', '1.2.8'], + ['^1.2.3', '1.8.1'], + ['^0.1.2', '0.1.2'], + ['^0.1', '0.1.2'], + ['^1.2', '1.4.2'], + ['^1.2 ^1', '1.4.2'], + ['^1.2.3-alpha', '1.2.3-pre'], + ['^1.2.0-alpha', '1.2.0-pre'], + ['^0.0.1-alpha', '0.0.1-beta'] + ].forEach(function(v) { + var range = v[0]; + var ver = v[1]; + var loose = v[2]; + t.ok(satisfies(ver, range, loose), range + ' satisfied by ' + ver); + }); + t.end(); +}); + +test('\nnegative range tests', function(t) { + // [range, version] + // version should not be included by range + [['1.0.0 - 2.0.0', '2.2.3'], + ['1.2.3+asdf - 2.4.3+asdf', '1.2.3-pre.2'], + ['1.2.3+asdf - 2.4.3+asdf', '2.4.3-alpha'], + ['^1.2.3+build', '2.0.0'], + ['^1.2.3+build', '1.2.0'], + ['^1.2.3', '1.2.3-pre'], + ['^1.2', '1.2.0-pre'], + ['>1.2', '1.3.0-beta'], + ['<=1.2.3', '1.2.3-beta'], + ['^1.2.3', '1.2.3-beta'], + ['=0.7.x', '0.7.0-asdf'], + ['>=0.7.x', '0.7.0-asdf'], + ['1', '1.0.0beta', true], + ['<1', '1.0.0beta', true], + ['< 1', '1.0.0beta', true], + ['1.0.0', '1.0.1'], + ['>=1.0.0', '0.0.0'], + ['>=1.0.0', '0.0.1'], + ['>=1.0.0', '0.1.0'], + ['>1.0.0', '0.0.1'], + ['>1.0.0', '0.1.0'], + ['<=2.0.0', '3.0.0'], + ['<=2.0.0', '2.9999.9999'], + ['<=2.0.0', '2.2.9'], + ['<2.0.0', '2.9999.9999'], + ['<2.0.0', '2.2.9'], + ['>=0.1.97', 'v0.1.93', true], + ['>=0.1.97', '0.1.93'], + ['0.1.20 || 1.2.4', '1.2.3'], + ['>=0.2.3 || <0.0.1', '0.0.3'], + ['>=0.2.3 || <0.0.1', '0.2.2'], + ['2.x.x', '1.1.3'], + ['2.x.x', '3.1.3'], + ['1.2.x', '1.3.3'], + ['1.2.x || 2.x', '3.1.3'], + ['1.2.x || 2.x', '1.1.3'], + ['2.*.*', '1.1.3'], + ['2.*.*', '3.1.3'], + ['1.2.*', '1.3.3'], + ['1.2.* || 2.*', '3.1.3'], + ['1.2.* || 2.*', '1.1.3'], + ['2', '1.1.2'], + ['2.3', '2.4.1'], + ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.3.9'], + ['~>3.2.1', '3.3.2'], // >=3.2.1 <3.3.0 + ['~>3.2.1', '3.2.0'], // >=3.2.1 <3.3.0 + ['~1', '0.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '2.2.3'], + ['~1.0', '1.1.0'], // >=1.0.0 <1.1.0 + ['<1', '1.0.0'], + ['>=1.2', '1.1.1'], + ['1', '2.0.0beta', true], + ['~v0.5.4-beta', '0.5.4-alpha'], + ['=0.7.x', '0.8.2'], + ['>=0.7.x', '0.6.2'], + ['<0.7.x', '0.7.2'], + ['<1.2.3', '1.2.3-beta'], + ['=1.2.3', '1.2.3-beta'], + ['>1.2', '1.2.8'], + ['^1.2.3', '2.0.0-alpha'], + ['^1.2.3', '1.2.2'], + ['^1.2', '1.1.9'], + ['*', 'v1.2.3-foo', true], + // invalid ranges never satisfied! + ['blerg', '1.2.3'], + ['git+https://user:password0123@github.com/foo', '123.0.0', true], + ['^1.2.3', '2.0.0-pre'] + ].forEach(function(v) { + var range = v[0]; + var ver = v[1]; + var loose = v[2]; + var found = satisfies(ver, range, loose); + t.ok(!found, ver + ' not satisfied by ' + range); + }); + t.end(); +}); + +test('\nincrement versions test', function(t) { +// [version, inc, result, identifier] +// inc(version, inc) -> result + [['1.2.3', 'major', '2.0.0'], + ['1.2.3', 'minor', '1.3.0'], + ['1.2.3', 'patch', '1.2.4'], + ['1.2.3tag', 'major', '2.0.0', true], + ['1.2.3-tag', 'major', '2.0.0'], + ['1.2.3', 'fake', null], + ['1.2.0-0', 'patch', '1.2.0'], + ['fake', 'major', null], + ['1.2.3-4', 'major', '2.0.0'], + ['1.2.3-4', 'minor', '1.3.0'], + ['1.2.3-4', 'patch', '1.2.3'], + ['1.2.3-alpha.0.beta', 'major', '2.0.0'], + ['1.2.3-alpha.0.beta', 'minor', '1.3.0'], + ['1.2.3-alpha.0.beta', 'patch', '1.2.3'], + ['1.2.4', 'prerelease', '1.2.5-0'], + ['1.2.3-0', 'prerelease', '1.2.3-1'], + ['1.2.3-alpha.0', 'prerelease', '1.2.3-alpha.1'], + ['1.2.3-alpha.1', 'prerelease', '1.2.3-alpha.2'], + ['1.2.3-alpha.2', 'prerelease', '1.2.3-alpha.3'], + ['1.2.3-alpha.0.beta', 'prerelease', '1.2.3-alpha.1.beta'], + ['1.2.3-alpha.1.beta', 'prerelease', '1.2.3-alpha.2.beta'], + ['1.2.3-alpha.2.beta', 'prerelease', '1.2.3-alpha.3.beta'], + ['1.2.3-alpha.10.0.beta', 'prerelease', '1.2.3-alpha.10.1.beta'], + ['1.2.3-alpha.10.1.beta', 'prerelease', '1.2.3-alpha.10.2.beta'], + ['1.2.3-alpha.10.2.beta', 'prerelease', '1.2.3-alpha.10.3.beta'], + ['1.2.3-alpha.10.beta.0', 'prerelease', '1.2.3-alpha.10.beta.1'], + ['1.2.3-alpha.10.beta.1', 'prerelease', '1.2.3-alpha.10.beta.2'], + ['1.2.3-alpha.10.beta.2', 'prerelease', '1.2.3-alpha.10.beta.3'], + ['1.2.3-alpha.9.beta', 'prerelease', '1.2.3-alpha.10.beta'], + ['1.2.3-alpha.10.beta', 'prerelease', '1.2.3-alpha.11.beta'], + ['1.2.3-alpha.11.beta', 'prerelease', '1.2.3-alpha.12.beta'], + ['1.2.0', 'prepatch', '1.2.1-0'], + ['1.2.0-1', 'prepatch', '1.2.1-0'], + ['1.2.0', 'preminor', '1.3.0-0'], + ['1.2.3-1', 'preminor', '1.3.0-0'], + ['1.2.0', 'premajor', '2.0.0-0'], + ['1.2.3-1', 'premajor', '2.0.0-0'], + ['1.2.0-1', 'minor', '1.2.0'], + ['1.0.0-1', 'major', '1.0.0'], + + ['1.2.3', 'major', '2.0.0', false, 'dev'], + ['1.2.3', 'minor', '1.3.0', false, 'dev'], + ['1.2.3', 'patch', '1.2.4', false, 'dev'], + ['1.2.3tag', 'major', '2.0.0', true, 'dev'], + ['1.2.3-tag', 'major', '2.0.0', false, 'dev'], + ['1.2.3', 'fake', null, false, 'dev'], + ['1.2.0-0', 'patch', '1.2.0', false, 'dev'], + ['fake', 'major', null, false, 'dev'], + ['1.2.3-4', 'major', '2.0.0', false, 'dev'], + ['1.2.3-4', 'minor', '1.3.0', false, 'dev'], + ['1.2.3-4', 'patch', '1.2.3', false, 'dev'], + ['1.2.3-alpha.0.beta', 'major', '2.0.0', false, 'dev'], + ['1.2.3-alpha.0.beta', 'minor', '1.3.0', false, 'dev'], + ['1.2.3-alpha.0.beta', 'patch', '1.2.3', false, 'dev'], + ['1.2.4', 'prerelease', '1.2.5-dev.0', false, 'dev'], + ['1.2.3-0', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.0', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.0', 'prerelease', '1.2.3-alpha.1', false, 'alpha'], + ['1.2.3-alpha.0.beta', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.0.beta', 'prerelease', '1.2.3-alpha.1.beta', false, 'alpha'], + ['1.2.3-alpha.10.0.beta', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.10.0.beta', 'prerelease', '1.2.3-alpha.10.1.beta', false, 'alpha'], + ['1.2.3-alpha.10.1.beta', 'prerelease', '1.2.3-alpha.10.2.beta', false, 'alpha'], + ['1.2.3-alpha.10.2.beta', 'prerelease', '1.2.3-alpha.10.3.beta', false, 'alpha'], + ['1.2.3-alpha.10.beta.0', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.10.beta.0', 'prerelease', '1.2.3-alpha.10.beta.1', false, 'alpha'], + ['1.2.3-alpha.10.beta.1', 'prerelease', '1.2.3-alpha.10.beta.2', false, 'alpha'], + ['1.2.3-alpha.10.beta.2', 'prerelease', '1.2.3-alpha.10.beta.3', false, 'alpha'], + ['1.2.3-alpha.9.beta', 'prerelease', '1.2.3-dev.0', false, 'dev'], + ['1.2.3-alpha.9.beta', 'prerelease', '1.2.3-alpha.10.beta', false, 'alpha'], + ['1.2.3-alpha.10.beta', 'prerelease', '1.2.3-alpha.11.beta', false, 'alpha'], + ['1.2.3-alpha.11.beta', 'prerelease', '1.2.3-alpha.12.beta', false, 'alpha'], + ['1.2.0', 'prepatch', '1.2.1-dev.0', false, 'dev'], + ['1.2.0-1', 'prepatch', '1.2.1-dev.0', false, 'dev'], + ['1.2.0', 'preminor', '1.3.0-dev.0', false, 'dev'], + ['1.2.3-1', 'preminor', '1.3.0-dev.0', false, 'dev'], + ['1.2.0', 'premajor', '2.0.0-dev.0', false, 'dev'], + ['1.2.3-1', 'premajor', '2.0.0-dev.0', false, 'dev'], + ['1.2.0-1', 'minor', '1.2.0', false, 'dev'], + ['1.0.0-1', 'major', '1.0.0', false, 'dev'], + ['1.2.3-dev.bar', 'prerelease', '1.2.3-dev.0', false, 'dev'] + + ].forEach(function(v) { + var pre = v[0]; + var what = v[1]; + var wanted = v[2]; + var loose = v[3]; + var id = v[4]; + var found = inc(pre, what, loose, id); + var cmd = 'inc(' + pre + ', ' + what + ', ' + id + ')'; + t.equal(found, wanted, cmd + ' === ' + wanted); + + var parsed = semver.parse(pre, loose); + if (wanted) { + parsed.inc(what, id); + t.equal(parsed.version, wanted, cmd + ' object version updated'); + t.equal(parsed.raw, wanted, cmd + ' object raw field updated'); + } else if (parsed) { + t.throws(function () { + parsed.inc(what, id) + }) + } else { + t.equal(parsed, null) + } + }); + + t.end(); +}); + +test('\ndiff versions test', function(t) { +// [version1, version2, result] +// diff(version1, version2) -> result + [['1.2.3', '0.2.3', 'major'], + ['1.4.5', '0.2.3', 'major'], + ['1.2.3', '2.0.0-pre', 'premajor'], + ['1.2.3', '1.3.3', 'minor'], + ['1.0.1', '1.1.0-pre', 'preminor'], + ['1.2.3', '1.2.4', 'patch'], + ['1.2.3', '1.2.4-pre', 'prepatch'], + ['0.0.1', '0.0.1-pre', 'prerelease'], + ['0.0.1', '0.0.1-pre-2', 'prerelease'], + ['1.1.0', '1.1.0-pre', 'prerelease'], + ['1.1.0-pre-1', '1.1.0-pre-2', 'prerelease'], + ['1.0.0', '1.0.0', null] + + ].forEach(function(v) { + var version1 = v[0]; + var version2 = v[1]; + var wanted = v[2]; + var found = diff(version1, version2); + var cmd = 'diff(' + version1 + ', ' + version2 + ')'; + t.equal(found, wanted, cmd + ' === ' + wanted); + }); + + t.end(); +}); + +test('\nvalid range test', function(t) { + // [range, result] + // validRange(range) -> result + // translate ranges into their canonical form + [['1.0.0 - 2.0.0', '>=1.0.0 <=2.0.0'], + ['1.0.0', '1.0.0'], + ['>=*', '*'], + ['', '*'], + ['*', '*'], + ['*', '*'], + ['>=1.0.0', '>=1.0.0'], + ['>1.0.0', '>1.0.0'], + ['<=2.0.0', '<=2.0.0'], + ['1', '>=1.0.0 <2.0.0'], + ['<=2.0.0', '<=2.0.0'], + ['<=2.0.0', '<=2.0.0'], + ['<2.0.0', '<2.0.0'], + ['<2.0.0', '<2.0.0'], + ['>= 1.0.0', '>=1.0.0'], + ['>= 1.0.0', '>=1.0.0'], + ['>= 1.0.0', '>=1.0.0'], + ['> 1.0.0', '>1.0.0'], + ['> 1.0.0', '>1.0.0'], + ['<= 2.0.0', '<=2.0.0'], + ['<= 2.0.0', '<=2.0.0'], + ['<= 2.0.0', '<=2.0.0'], + ['< 2.0.0', '<2.0.0'], + ['< 2.0.0', '<2.0.0'], + ['>=0.1.97', '>=0.1.97'], + ['>=0.1.97', '>=0.1.97'], + ['0.1.20 || 1.2.4', '0.1.20||1.2.4'], + ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1'], + ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1'], + ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1'], + ['||', '||'], + ['2.x.x', '>=2.0.0 <3.0.0'], + ['1.2.x', '>=1.2.0 <1.3.0'], + ['1.2.x || 2.x', '>=1.2.0 <1.3.0||>=2.0.0 <3.0.0'], + ['1.2.x || 2.x', '>=1.2.0 <1.3.0||>=2.0.0 <3.0.0'], + ['x', '*'], + ['2.*.*', '>=2.0.0 <3.0.0'], + ['1.2.*', '>=1.2.0 <1.3.0'], + ['1.2.* || 2.*', '>=1.2.0 <1.3.0||>=2.0.0 <3.0.0'], + ['*', '*'], + ['2', '>=2.0.0 <3.0.0'], + ['2.3', '>=2.3.0 <2.4.0'], + ['~2.4', '>=2.4.0 <2.5.0'], + ['~2.4', '>=2.4.0 <2.5.0'], + ['~>3.2.1', '>=3.2.1 <3.3.0'], + ['~1', '>=1.0.0 <2.0.0'], + ['~>1', '>=1.0.0 <2.0.0'], + ['~> 1', '>=1.0.0 <2.0.0'], + ['~1.0', '>=1.0.0 <1.1.0'], + ['~ 1.0', '>=1.0.0 <1.1.0'], + ['^0', '>=0.0.0 <1.0.0'], + ['^ 1', '>=1.0.0 <2.0.0'], + ['^0.1', '>=0.1.0 <0.2.0'], + ['^1.0', '>=1.0.0 <2.0.0'], + ['^1.2', '>=1.2.0 <2.0.0'], + ['^0.0.1', '>=0.0.1 <0.0.2'], + ['^0.0.1-beta', '>=0.0.1-beta <0.0.2'], + ['^0.1.2', '>=0.1.2 <0.2.0'], + ['^1.2.3', '>=1.2.3 <2.0.0'], + ['^1.2.3-beta.4', '>=1.2.3-beta.4 <2.0.0'], + ['<1', '<1.0.0'], + ['< 1', '<1.0.0'], + ['>=1', '>=1.0.0'], + ['>= 1', '>=1.0.0'], + ['<1.2', '<1.2.0'], + ['< 1.2', '<1.2.0'], + ['1', '>=1.0.0 <2.0.0'], + ['>01.02.03', '>1.2.3', true], + ['>01.02.03', null], + ['~1.2.3beta', '>=1.2.3-beta <1.3.0', true], + ['~1.2.3beta', null], + ['^ 1.2 ^ 1', '>=1.2.0 <2.0.0 >=1.0.0 <2.0.0'] + ].forEach(function(v) { + var pre = v[0]; + var wanted = v[1]; + var loose = v[2]; + var found = validRange(pre, loose); + + t.equal(found, wanted, 'validRange(' + pre + ') === ' + wanted); + }); + + t.end(); +}); + +test('\ncomparators test', function(t) { + // [range, comparators] + // turn range into a set of individual comparators + [['1.0.0 - 2.0.0', [['>=1.0.0', '<=2.0.0']]], + ['1.0.0', [['1.0.0']]], + ['>=*', [['']]], + ['', [['']]], + ['*', [['']]], + ['*', [['']]], + ['>=1.0.0', [['>=1.0.0']]], + ['>=1.0.0', [['>=1.0.0']]], + ['>=1.0.0', [['>=1.0.0']]], + ['>1.0.0', [['>1.0.0']]], + ['>1.0.0', [['>1.0.0']]], + ['<=2.0.0', [['<=2.0.0']]], + ['1', [['>=1.0.0', '<2.0.0']]], + ['<=2.0.0', [['<=2.0.0']]], + ['<=2.0.0', [['<=2.0.0']]], + ['<2.0.0', [['<2.0.0']]], + ['<2.0.0', [['<2.0.0']]], + ['>= 1.0.0', [['>=1.0.0']]], + ['>= 1.0.0', [['>=1.0.0']]], + ['>= 1.0.0', [['>=1.0.0']]], + ['> 1.0.0', [['>1.0.0']]], + ['> 1.0.0', [['>1.0.0']]], + ['<= 2.0.0', [['<=2.0.0']]], + ['<= 2.0.0', [['<=2.0.0']]], + ['<= 2.0.0', [['<=2.0.0']]], + ['< 2.0.0', [['<2.0.0']]], + ['<\t2.0.0', [['<2.0.0']]], + ['>=0.1.97', [['>=0.1.97']]], + ['>=0.1.97', [['>=0.1.97']]], + ['0.1.20 || 1.2.4', [['0.1.20'], ['1.2.4']]], + ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1']]], + ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1']]], + ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1']]], + ['||', [[''], ['']]], + ['2.x.x', [['>=2.0.0', '<3.0.0']]], + ['1.2.x', [['>=1.2.0', '<1.3.0']]], + ['1.2.x || 2.x', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['1.2.x || 2.x', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['x', [['']]], + ['2.*.*', [['>=2.0.0', '<3.0.0']]], + ['1.2.*', [['>=1.2.0', '<1.3.0']]], + ['1.2.* || 2.*', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['1.2.* || 2.*', [['>=1.2.0', '<1.3.0'], ['>=2.0.0', '<3.0.0']]], + ['*', [['']]], + ['2', [['>=2.0.0', '<3.0.0']]], + ['2.3', [['>=2.3.0', '<2.4.0']]], + ['~2.4', [['>=2.4.0', '<2.5.0']]], + ['~2.4', [['>=2.4.0', '<2.5.0']]], + ['~>3.2.1', [['>=3.2.1', '<3.3.0']]], + ['~1', [['>=1.0.0', '<2.0.0']]], + ['~>1', [['>=1.0.0', '<2.0.0']]], + ['~> 1', [['>=1.0.0', '<2.0.0']]], + ['~1.0', [['>=1.0.0', '<1.1.0']]], + ['~ 1.0', [['>=1.0.0', '<1.1.0']]], + ['~ 1.0.3', [['>=1.0.3', '<1.1.0']]], + ['~> 1.0.3', [['>=1.0.3', '<1.1.0']]], + ['<1', [['<1.0.0']]], + ['< 1', [['<1.0.0']]], + ['>=1', [['>=1.0.0']]], + ['>= 1', [['>=1.0.0']]], + ['<1.2', [['<1.2.0']]], + ['< 1.2', [['<1.2.0']]], + ['1', [['>=1.0.0', '<2.0.0']]], + ['1 2', [['>=1.0.0', '<2.0.0', '>=2.0.0', '<3.0.0']]], + ['1.2 - 3.4.5', [['>=1.2.0', '<=3.4.5']]], + ['1.2.3 - 3.4', [['>=1.2.3', '<3.5.0']]], + ['1.2.3 - 3', [['>=1.2.3', '<4.0.0']]], + ['>*', [['<0.0.0']]], + ['<*', [['<0.0.0']]] + ].forEach(function(v) { + var pre = v[0]; + var wanted = v[1]; + var found = toComparators(v[0]); + var jw = JSON.stringify(wanted); + t.equivalent(found, wanted, 'toComparators(' + pre + ') === ' + jw); + }); + + t.end(); +}); + +test('\ninvalid version numbers', function(t) { + ['1.2.3.4', + 'NOT VALID', + 1.2, + null, + 'Infinity.NaN.Infinity' + ].forEach(function(v) { + t.throws(function() { + new SemVer(v); + }, {name:'TypeError', message:'Invalid Version: ' + v}); + }); + + t.end(); +}); + +test('\nstrict vs loose version numbers', function(t) { + [['=1.2.3', '1.2.3'], + ['01.02.03', '1.2.3'], + ['1.2.3-beta.01', '1.2.3-beta.1'], + [' =1.2.3', '1.2.3'], + ['1.2.3foo', '1.2.3-foo'] + ].forEach(function(v) { + var loose = v[0]; + var strict = v[1]; + t.throws(function() { + new SemVer(loose); + }); + var lv = new SemVer(loose, true); + t.equal(lv.version, strict); + t.ok(eq(loose, strict, true)); + t.throws(function() { + eq(loose, strict); + }); + t.throws(function() { + new SemVer(strict).compare(loose); + }); + }); + t.end(); +}); + +test('\nstrict vs loose ranges', function(t) { + [['>=01.02.03', '>=1.2.3'], + ['~1.02.03beta', '>=1.2.3-beta <1.3.0'] + ].forEach(function(v) { + var loose = v[0]; + var comps = v[1]; + t.throws(function() { + new Range(loose); + }); + t.equal(new Range(loose, true).range, comps); + }); + t.end(); +}); + +test('\nmax satisfying', function(t) { + [[['1.2.3', '1.2.4'], '1.2', '1.2.4'], + [['1.2.4', '1.2.3'], '1.2', '1.2.4'], + [['1.2.3', '1.2.4', '1.2.5', '1.2.6'], '~1.2.3', '1.2.6'], + [['1.1.0', '1.2.0', '1.2.1', '1.3.0', '2.0.0b1', '2.0.0b2', '2.0.0b3', '2.0.0', '2.1.0'], '~2.0.0', '2.0.0', true] + ].forEach(function(v) { + var versions = v[0]; + var range = v[1]; + var expect = v[2]; + var loose = v[3]; + var actual = semver.maxSatisfying(versions, range, loose); + t.equal(actual, expect); + }); + t.end(); +}); diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/ltr.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/ltr.js new file mode 100644 index 0000000..0f7167d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/ltr.js @@ -0,0 +1,181 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); +var ltr = semver.ltr; + +test('\nltr tests', function(t) { + // [range, version, loose] + // Version should be less than range + [ + ['~1.2.2', '1.2.1'], + ['~0.6.1-1', '0.6.1-0'], + ['1.0.0 - 2.0.0', '0.0.1'], + ['1.0.0-beta.2', '1.0.0-beta.1'], + ['1.0.0', '0.0.0'], + ['>=2.0.0', '1.1.1'], + ['>=2.0.0', '1.2.9'], + ['>2.0.0', '2.0.0'], + ['0.1.20 || 1.2.4', '0.1.5'], + ['2.x.x', '1.0.0'], + ['1.2.x', '1.1.0'], + ['1.2.x || 2.x', '1.0.0'], + ['2.*.*', '1.0.1'], + ['1.2.*', '1.1.3'], + ['1.2.* || 2.*', '1.1.9999'], + ['2', '1.0.0'], + ['2.3', '2.2.2'], + ['~2.4', '2.3.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.3.5'], + ['~>3.2.1', '3.2.0'], // >=3.2.1 <3.3.0 + ['~1', '0.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '0.2.4'], + ['~> 1', '0.2.3'], + ['~1.0', '0.1.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '0.1.0'], + ['>1.2', '1.2.0'], + ['> 1.2', '1.2.1'], + ['1', '0.0.0beta', true], + ['~v0.5.4-pre', '0.5.4-alpha'], + ['~v0.5.4-pre', '0.5.4-alpha'], + ['=0.7.x', '0.6.0'], + ['=0.7.x', '0.6.0-asdf'], + ['>=0.7.x', '0.6.0'], + ['~1.2.2', '1.2.1'], + ['1.0.0 - 2.0.0', '0.2.3'], + ['1.0.0', '0.0.1'], + ['>=2.0.0', '1.0.0'], + ['>=2.0.0', '1.9999.9999'], + ['>=2.0.0', '1.2.9'], + ['>2.0.0', '2.0.0'], + ['>2.0.0', '1.2.9'], + ['2.x.x', '1.1.3'], + ['1.2.x', '1.1.3'], + ['1.2.x || 2.x', '1.1.3'], + ['2.*.*', '1.1.3'], + ['1.2.*', '1.1.3'], + ['1.2.* || 2.*', '1.1.3'], + ['2', '1.9999.9999'], + ['2.3', '2.2.1'], + ['~2.4', '2.3.0'], // >=2.4.0 <2.5.0 + ['~>3.2.1', '2.3.2'], // >=3.2.1 <3.3.0 + ['~1', '0.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '0.2.3'], + ['~1.0', '0.0.0'], // >=1.0.0 <1.1.0 + ['>1', '1.0.0'], + ['2', '1.0.0beta', true], + ['>1', '1.0.0beta', true], + ['> 1', '1.0.0beta', true], + ['=0.7.x', '0.6.2'], + ['=0.7.x', '0.7.0-asdf'], + ['^1', '1.0.0-0'], + ['>=0.7.x', '0.7.0-asdf'], + ['1', '1.0.0beta', true], + ['>=0.7.x', '0.6.2'], + ['>1.2.3', '1.3.0-alpha'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'ltr(' + version + ', ' + range + ', ' + loose + ')'; + t.ok(ltr(version, range, loose), msg); + }); + t.end(); +}); + +test('\nnegative ltr tests', function(t) { + // [range, version, loose] + // Version should NOT be less than range + [ + ['~ 1.0', '1.1.0'], + ['~0.6.1-1', '0.6.1-1'], + ['1.0.0 - 2.0.0', '1.2.3'], + ['1.0.0 - 2.0.0', '2.9.9'], + ['1.0.0', '1.0.0'], + ['>=*', '0.2.4'], + ['', '1.0.0', true], + ['*', '1.2.3'], + ['>=1.0.0', '1.0.0'], + ['>=1.0.0', '1.0.1'], + ['>=1.0.0', '1.1.0'], + ['>1.0.0', '1.0.1'], + ['>1.0.0', '1.1.0'], + ['<=2.0.0', '2.0.0'], + ['<=2.0.0', '1.9999.9999'], + ['<=2.0.0', '0.2.9'], + ['<2.0.0', '1.9999.9999'], + ['<2.0.0', '0.2.9'], + ['>= 1.0.0', '1.0.0'], + ['>= 1.0.0', '1.0.1'], + ['>= 1.0.0', '1.1.0'], + ['> 1.0.0', '1.0.1'], + ['> 1.0.0', '1.1.0'], + ['<= 2.0.0', '2.0.0'], + ['<= 2.0.0', '1.9999.9999'], + ['<= 2.0.0', '0.2.9'], + ['< 2.0.0', '1.9999.9999'], + ['<\t2.0.0', '0.2.9'], + ['>=0.1.97', 'v0.1.97'], + ['>=0.1.97', '0.1.97'], + ['0.1.20 || 1.2.4', '1.2.4'], + ['0.1.20 || >1.2.4', '1.2.4'], + ['0.1.20 || 1.2.4', '1.2.3'], + ['0.1.20 || 1.2.4', '0.1.20'], + ['>=0.2.3 || <0.0.1', '0.0.0'], + ['>=0.2.3 || <0.0.1', '0.2.3'], + ['>=0.2.3 || <0.0.1', '0.2.4'], + ['||', '1.3.4'], + ['2.x.x', '2.1.3'], + ['1.2.x', '1.2.3'], + ['1.2.x || 2.x', '2.1.3'], + ['1.2.x || 2.x', '1.2.3'], + ['x', '1.2.3'], + ['2.*.*', '2.1.3'], + ['1.2.*', '1.2.3'], + ['1.2.* || 2.*', '2.1.3'], + ['1.2.* || 2.*', '1.2.3'], + ['1.2.* || 2.*', '1.2.3'], + ['*', '1.2.3'], + ['2', '2.1.2'], + ['2.3', '2.3.1'], + ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 + ['~2.4', '2.4.5'], + ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0 + ['~1', '1.2.3'], // >=1.0.0 <2.0.0 + ['~>1', '1.2.3'], + ['~> 1', '1.2.3'], + ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0 + ['~ 1.0', '1.0.2'], + ['>=1', '1.0.0'], + ['>= 1', '1.0.0'], + ['<1.2', '1.1.1'], + ['< 1.2', '1.1.1'], + ['~v0.5.4-pre', '0.5.5'], + ['~v0.5.4-pre', '0.5.4'], + ['=0.7.x', '0.7.2'], + ['>=0.7.x', '0.7.2'], + ['<=0.7.x', '0.6.2'], + ['>0.2.3 >0.2.4 <=0.2.5', '0.2.5'], + ['>=0.2.3 <=0.2.4', '0.2.4'], + ['1.0.0 - 2.0.0', '2.0.0'], + ['^3.0.0', '4.0.0'], + ['^1.0.0 || ~2.0.1', '2.0.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '3.2.0'], + ['^0.1.0 || ~3.0.1 || 5.0.0', '1.0.0beta', true], + ['^0.1.0 || ~3.0.1 || 5.0.0', '5.0.0-0', true], + ['^0.1.0 || ~3.0.1 || >4 <=5.0.0', '3.5.0'], + ['^1.0.0alpha', '1.0.0beta', true], + ['~1.0.0alpha', '1.0.0beta', true], + ['^1.0.0-alpha', '1.0.0beta', true], + ['~1.0.0-alpha', '1.0.0beta', true], + ['^1.0.0-alpha', '1.0.0-beta'], + ['~1.0.0-alpha', '1.0.0-beta'], + ['=0.1.0', '1.0.0'] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = '!ltr(' + version + ', ' + range + ', ' + loose + ')'; + t.notOk(ltr(version, range, loose), msg); + }); + t.end(); +}); diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/major-minor-patch.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/major-minor-patch.js new file mode 100644 index 0000000..e9d4039 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/node_modules/semver/test/major-minor-patch.js @@ -0,0 +1,72 @@ +var tap = require('tap'); +var test = tap.test; +var semver = require('../semver.js'); + +test('\nmajor tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.2.3', 1], + [' 1.2.3 ', 1], + [' 2.2.3-4 ', 2], + [' 3.2.3-pre ', 3], + ['v5.2.3', 5], + [' v8.2.3 ', 8], + ['\t13.2.3', 13], + ['=21.2.3', 21, true], + ['v=34.2.3', 34, true] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'major(' + range + ') = ' + version; + t.equal(semver.major(range, loose), version, msg); + }); + t.end(); +}); + +test('\nminor tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.1.3', 1], + [' 1.1.3 ', 1], + [' 1.2.3-4 ', 2], + [' 1.3.3-pre ', 3], + ['v1.5.3', 5], + [' v1.8.3 ', 8], + ['\t1.13.3', 13], + ['=1.21.3', 21, true], + ['v=1.34.3', 34, true] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'minor(' + range + ') = ' + version; + t.equal(semver.minor(range, loose), version, msg); + }); + t.end(); +}); + +test('\npatch tests', function(t) { + // [range, version] + // Version should be detectable despite extra characters + [ + ['1.2.1', 1], + [' 1.2.1 ', 1], + [' 1.2.2-4 ', 2], + [' 1.2.3-pre ', 3], + ['v1.2.5', 5], + [' v1.2.8 ', 8], + ['\t1.2.13', 13], + ['=1.2.21', 21, true], + ['v=1.2.34', 34, true] + ].forEach(function(tuple) { + var range = tuple[0]; + var version = tuple[1]; + var loose = tuple[2] || false; + var msg = 'patch(' + range + ') = ' + version; + t.equal(semver.patch(range, loose), version, msg); + }); + t.end(); +}); diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/package.json new file mode 100644 index 0000000..e42e683 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/package.json @@ -0,0 +1,69 @@ +{ + "name": "require_optional", + "version": "1.0.0", + "description": "Allows you declare optionalPeerDependencies that can be satisfied by the top level module but ignored if they are not.", + "main": "index.js", + "scripts": { + "test": "mocha" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/christkv/require_optional.git" + }, + "keywords": [ + "optional", + "require", + "optionalPeerDependencies" + ], + "author": { + "name": "Christian Kvalheim Amor" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/christkv/require_optional/issues" + }, + "homepage": "https://github.com/christkv/require_optional", + "dependencies": { + "semver": "^5.1.0", + "resolve-from": "^2.0.0" + }, + "devDependencies": { + "bson": "0.4.21", + "co": "4.6.0", + "es6-promise": "^3.0.2", + "mocha": "^2.4.5" + }, + "peerOptionalDependencies": { + "co": ">=5.6.0", + "es6-promise": "^3.0.2", + "es6-promise2": "^4.0.2", + "bson": "0.4.21" + }, + "gitHead": "8eac964c8e31166a8fb483d0d56025b185cee03f", + "_id": "require_optional@1.0.0", + "_shasum": "52a86137a849728eb60a55533617f8f914f59abf", + "_from": "require_optional@>=1.0.0 <1.1.0", + "_npmVersion": "2.14.12", + "_nodeVersion": "4.2.4", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "52a86137a849728eb60a55533617f8f914f59abf", + "tarball": "http://registry.npmjs.org/require_optional/-/require_optional-1.0.0.tgz" + }, + "_npmOperationalInternal": { + "host": "packages-5-east.internal.npmjs.com", + "tmp": "tmp/require_optional-1.0.0.tgz_1454503936164_0.7571216486394405" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/test/require_optional_tests.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/test/require_optional_tests.js new file mode 100644 index 0000000..181d834 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/node_modules/require_optional/test/require_optional_tests.js @@ -0,0 +1,42 @@ +var assert = require('assert'), + require_optional = require('../'); + +describe('Require Optional', function() { + describe('top level require', function() { + it('should correctly require co library', function() { + var promise = require_optional('es6-promise'); + assert.ok(promise); + }); + + it('should fail to require es6-promise library', function() { + try { + require_optional('co'); + } catch(e) { + assert.equal('OPTIONAL_MODULE_NOT_FOUND', e.code); + return; + } + + assert.ok(false); + }); + + it('should ignore optional library not defined', function() { + assert.equal(undefined, require_optional('es6-promise2')); + }); + }); + + describe('internal module file require', function() { + it('should correctly require co library', function() { + var Long = require_optional('bson/lib/bson/long.js'); + assert.ok(Long); + }); + }); + + describe('top level resolve', function() { + it('should correctly use exists method', function() { + assert.equal(false, require_optional.exists('co')); + assert.equal(true, require_optional.exists('es6-promise')); + assert.equal(true, require_optional.exists('bson/lib/bson/long.js')); + assert.equal(false, require_optional.exists('es6-promise2')); + }); + }); +}); diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/package.json new file mode 100644 index 0000000..39a9835 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/package.json @@ -0,0 +1,75 @@ +{ + "name": "mongodb-core", + "version": "1.3.1", + "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", + "main": "index.js", + "scripts": { + "test": "node test/runner.js -t functional", + "coverage": "nyc node test/runner.js -t functional && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls" + }, + "repository": { + "type": "git", + "url": "git://github.com/christkv/mongodb-core.git" + }, + "keywords": [ + "mongodb", + "core" + ], + "dependencies": { + "bson": "~0.4.21", + "require_optional": "~1.0.0" + }, + "devDependencies": { + "co": "4.5.4", + "coveralls": "^2.11.6", + "es6-promise": "^3.0.2", + "gleak": "0.5.0", + "integra": "0.1.8", + "jsdoc": "3.3.0-alpha8", + "mkdirp": "0.5.0", + "mongodb-topology-manager": "1.0.x", + "mongodb-version-manager": "^1.x", + "nyc": "^5.5.0", + "optimist": "latest", + "rimraf": "2.2.6", + "semver": "4.1.0" + }, + "peerOptionalDependencies": { + "kerberos": "~0.0" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/christkv/mongodb-core/issues" + }, + "homepage": "https://github.com/christkv/mongodb-core", + "gitHead": "c1308710fb5f091ddbf6c9e18cfa292d7e951dd5", + "_id": "mongodb-core@1.3.1", + "_shasum": "c504b45e42300741ebf0b4b1d12d3c1073994588", + "_from": "mongodb-core@1.3.1", + "_npmVersion": "2.14.12", + "_nodeVersion": "4.2.4", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "c504b45e42300741ebf0b4b1d12d3c1073994588", + "tarball": "http://registry.npmjs.org/mongodb-core/-/mongodb-core-1.3.1.tgz" + }, + "_npmOperationalInternal": { + "host": "packages-5-east.internal.npmjs.com", + "tmp": "tmp/mongodb-core-1.3.1.tgz_1454648311034_0.9954264361876994" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-1.3.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat new file mode 100644 index 0000000..25ccf0b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat @@ -0,0 +1,11000 @@ +1 2 +2 1 +3 0 +4 0 +5 1 +6 0 +7 0 +8 0 +9 0 +10 1 +11 0 +12 0 +13 0 +14 1 +15 0 +16 0 +17 0 +18 1 +19 0 +20 0 +21 0 +22 1 +23 0 +24 0 +25 0 +26 0 +27 1 +28 0 +29 0 +30 0 +31 1 +32 0 +33 0 +34 0 +35 0 +36 0 +37 1 +38 0 +39 0 +40 0 +41 0 +42 0 +43 1 +44 0 +45 0 +46 0 +47 0 +48 0 +49 0 +50 0 +51 0 +52 0 +53 0 +54 0 +55 0 +56 0 +57 0 +58 0 +59 1 +60 0 +61 2 +62 0 +63 0 +64 1 +65 0 +66 0 +67 0 +68 1 +69 0 +70 0 +71 0 +72 0 +73 1 +74 0 +75 0 +76 0 +77 0 +78 0 +79 1 +80 0 +81 0 +82 0 +83 0 +84 0 +85 0 +86 1 +87 0 +88 0 +89 0 +90 0 +91 0 +92 0 +93 1 +94 0 +95 0 +96 0 +97 0 +98 0 +99 0 +100 0 +101 1 +102 0 +103 0 +104 0 +105 0 +106 0 +107 0 +108 1 +109 0 +110 0 +111 0 +112 0 +113 0 +114 0 +115 1 +116 0 +117 0 +118 0 +119 1 +120 0 +121 0 +122 0 +123 0 +124 0 +125 0 +126 1 +127 0 +128 1 +129 0 +130 0 +131 0 +132 1 +133 1 +134 0 +135 0 +136 0 +137 1 +138 0 +139 0 +140 0 +141 0 +142 0 +143 0 +144 1 +145 0 +146 0 +147 0 +148 0 +149 0 +150 0 +151 0 +152 0 +153 1 +154 0 +155 0 +156 0 +157 0 +158 0 +159 0 +160 0 +161 0 +162 0 +163 0 +164 0 +165 0 +166 0 +167 0 +168 0 +169 0 +170 1 +171 0 +172 0 +173 0 +174 0 +175 0 +176 0 +177 0 +178 1 +179 0 +180 0 +181 0 +182 0 +183 0 +184 0 +185 0 +186 1 +187 0 +188 0 +189 0 +190 0 +191 0 +192 1 +193 0 +194 0 +195 0 +196 1 +197 0 +198 0 +199 0 +200 1 +201 0 +202 0 +203 0 +204 0 +205 0 +206 0 +207 1 +208 0 +209 0 +210 0 +211 0 +212 0 +213 0 +214 0 +215 1 +216 0 +217 0 +218 0 +219 0 +220 0 +221 0 +222 0 +223 1 +224 0 +225 0 +226 0 +227 0 +228 0 +229 0 +230 1 +231 0 +232 0 +233 0 +234 0 +235 0 +236 0 +237 1 +238 0 +239 0 +240 0 +241 0 +242 0 +243 0 +244 0 +245 1 +246 0 +247 0 +248 0 +249 0 +250 0 +251 0 +252 0 +253 0 +254 1 +255 0 +256 0 +257 0 +258 0 +259 1 +260 0 +261 0 +262 0 +263 0 +264 0 +265 1 +266 0 +267 0 +268 0 +269 0 +270 0 +271 0 +272 1 +273 0 +274 0 +275 0 +276 0 +277 0 +278 0 +279 0 +280 0 +281 1 +282 0 +283 1 +284 0 +285 0 +286 1 +287 0 +288 0 +289 0 +290 0 +291 1 +292 0 +293 0 +294 0 +295 0 +296 1 +297 0 +298 0 +299 0 +300 0 +301 0 +302 0 +303 1 +304 0 +305 0 +306 0 +307 0 +308 0 +309 1 +310 0 +311 0 +312 0 +313 0 +314 0 +315 0 +316 1 +317 0 +318 0 +319 0 +320 0 +321 0 +322 0 +323 0 +324 0 +325 1 +326 0 +327 0 +328 0 +329 0 +330 0 +331 0 +332 0 +333 0 +334 1 +335 0 +336 0 +337 0 +338 0 +339 0 +340 0 +341 0 +342 0 +343 1 +344 0 +345 0 +346 0 +347 0 +348 0 +349 0 +350 0 +351 0 +352 1 +353 0 +354 0 +355 0 +356 0 +357 0 +358 0 +359 0 +360 0 +361 1 +362 0 +363 0 +364 0 +365 0 +366 0 +367 0 +368 0 +369 1 +370 0 +371 0 +372 0 +373 0 +374 0 +375 0 +376 0 +377 1 +378 0 +379 0 +380 0 +381 0 +382 0 +383 0 +384 0 +385 1 +386 0 +387 0 +388 0 +389 0 +390 1 +391 0 +392 0 +393 0 +394 0 +395 0 +396 0 +397 0 +398 0 +399 0 +400 0 +401 0 +402 1 +403 0 +404 0 +405 0 +406 0 +407 0 +408 0 +409 0 +410 1 +411 0 +412 0 +413 0 +414 0 +415 0 +416 0 +417 0 +418 0 +419 1 +420 0 +421 0 +422 0 +423 0 +424 0 +425 0 +426 0 +427 1 +428 0 +429 0 +430 0 +431 0 +432 0 +433 0 +434 0 +435 1 +436 0 +437 0 +438 0 +439 0 +440 0 +441 0 +442 0 +443 1 +444 0 +445 0 +446 0 +447 0 +448 0 +449 0 +450 1 +451 0 +452 0 +453 0 +454 0 +455 0 +456 1 +457 0 +458 0 +459 0 +460 0 +461 0 +462 0 +463 0 +464 1 +465 0 +466 0 +467 0 +468 0 +469 0 +470 0 +471 0 +472 0 +473 1 +474 0 +475 0 +476 0 +477 0 +478 0 +479 0 +480 0 +481 1 +482 0 +483 0 +484 0 +485 0 +486 0 +487 0 +488 0 +489 0 +490 1 +491 0 +492 0 +493 0 +494 0 +495 0 +496 0 +497 0 +498 0 +499 0 +500 0 +501 0 +502 0 +503 0 +504 1 +505 0 +506 0 +507 0 +508 0 +509 0 +510 0 +511 0 +512 1 +513 0 +514 0 +515 0 +516 0 +517 0 +518 0 +519 4 +520 0 +521 1 +522 0 +523 0 +524 0 +525 1 +526 0 +527 0 +528 0 +529 0 +530 1 +531 0 +532 0 +533 0 +534 1 +535 0 +536 0 +537 0 +538 0 +539 1 +540 0 +541 0 +542 0 +543 0 +544 0 +545 1 +546 0 +547 0 +548 0 +549 0 +550 0 +551 1 +552 0 +553 0 +554 0 +555 0 +556 0 +557 0 +558 0 +559 1 +560 0 +561 0 +562 0 +563 0 +564 0 +565 0 +566 0 +567 1 +568 0 +569 0 +570 0 +571 0 +572 0 +573 0 +574 0 +575 0 +576 1 +577 0 +578 0 +579 0 +580 0 +581 0 +582 0 +583 0 +584 0 +585 0 +586 0 +587 0 +588 0 +589 0 +590 0 +591 0 +592 0 +593 1 +594 0 +595 0 +596 0 +597 0 +598 0 +599 0 +600 0 +601 0 +602 1 +603 0 +604 0 +605 0 +606 0 +607 0 +608 0 +609 0 +610 0 +611 1 +612 0 +613 0 +614 0 +615 0 +616 0 +617 0 +618 0 +619 0 +620 1 +621 0 +622 0 +623 0 +624 0 +625 0 +626 0 +627 0 +628 0 +629 1 +630 0 +631 0 +632 0 +633 0 +634 0 +635 0 +636 0 +637 0 +638 0 +639 1 +640 0 +641 0 +642 0 +643 0 +644 0 +645 0 +646 1 +647 0 +648 0 +649 0 +650 0 +651 0 +652 1 +653 1 +654 0 +655 0 +656 1 +657 0 +658 1 +659 0 +660 0 +661 0 +662 0 +663 0 +664 1 +665 0 +666 0 +667 0 +668 0 +669 0 +670 0 +671 0 +672 0 +673 0 +674 0 +675 0 +676 0 +677 1 +678 0 +679 0 +680 0 +681 0 +682 0 +683 0 +684 0 +685 0 +686 1 +687 0 +688 0 +689 0 +690 0 +691 0 +692 0 +693 0 +694 0 +695 1 +696 0 +697 0 +698 0 +699 0 +700 0 +701 0 +702 0 +703 1 +704 0 +705 0 +706 0 +707 0 +708 0 +709 0 +710 0 +711 0 +712 1 +713 0 +714 0 +715 0 +716 0 +717 0 +718 0 +719 0 +720 1 +721 0 +722 0 +723 0 +724 0 +725 0 +726 0 +727 0 +728 1 +729 0 +730 0 +731 0 +732 0 +733 0 +734 0 +735 0 +736 0 +737 1 +738 0 +739 0 +740 0 +741 0 +742 0 +743 0 +744 0 +745 1 +746 0 +747 0 +748 0 +749 0 +750 0 +751 0 +752 0 +753 1 +754 0 +755 0 +756 0 +757 0 +758 0 +759 0 +760 0 +761 1 +762 0 +763 0 +764 0 +765 0 +766 0 +767 0 +768 1 +769 0 +770 0 +771 0 +772 0 +773 0 +774 0 +775 0 +776 0 +777 1 +778 0 +779 0 +780 0 +781 0 +782 0 +783 0 +784 0 +785 0 +786 1 +787 0 +788 0 +789 0 +790 0 +791 0 +792 1 +793 0 +794 0 +795 0 +796 0 +797 0 +798 0 +799 0 +800 0 +801 1 +802 0 +803 0 +804 0 +805 0 +806 0 +807 0 +808 0 +809 0 +810 0 +811 0 +812 0 +813 0 +814 0 +815 0 +816 0 +817 0 +818 0 +819 0 +820 1 +821 0 +822 0 +823 0 +824 0 +825 0 +826 0 +827 0 +828 0 +829 1 +830 0 +831 0 +832 0 +833 0 +834 0 +835 0 +836 0 +837 1 +838 0 +839 0 +840 0 +841 0 +842 0 +843 0 +844 0 +845 0 +846 1 +847 0 +848 0 +849 0 +850 0 +851 0 +852 0 +853 0 +854 0 +855 2 +856 0 +857 0 +858 0 +859 0 +860 0 +861 0 +862 1 +863 0 +864 0 +865 0 +866 0 +867 0 +868 0 +869 0 +870 0 +871 1 +872 0 +873 0 +874 0 +875 0 +876 0 +877 0 +878 1 +879 0 +880 0 +881 0 +882 0 +883 0 +884 0 +885 0 +886 0 +887 0 +888 0 +889 0 +890 0 +891 0 +892 0 +893 0 +894 0 +895 0 +896 1 +897 0 +898 0 +899 0 +900 0 +901 0 +902 0 +903 0 +904 0 +905 0 +906 1 +907 0 +908 0 +909 0 +910 0 +911 0 +912 0 +913 0 +914 0 +915 1 +916 0 +917 0 +918 0 +919 0 +920 0 +921 0 +922 1 +923 0 +924 0 +925 0 +926 0 +927 0 +928 0 +929 0 +930 1 +931 0 +932 0 +933 0 +934 0 +935 0 +936 0 +937 0 +938 0 +939 1 +940 0 +941 0 +942 0 +943 0 +944 0 +945 0 +946 0 +947 0 +948 0 +949 1 +950 0 +951 0 +952 0 +953 0 +954 0 +955 0 +956 0 +957 0 +958 1 +959 0 +960 0 +961 0 +962 0 +963 0 +964 0 +965 0 +966 0 +967 0 +968 1 +969 0 +970 0 +971 0 +972 0 +973 0 +974 0 +975 0 +976 0 +977 0 +978 1 +979 0 +980 0 +981 0 +982 0 +983 0 +984 0 +985 0 +986 0 +987 0 +988 1 +989 0 +990 0 +991 0 +992 0 +993 0 +994 0 +995 0 +996 0 +997 1 +998 0 +999 0 +1000 0 +1001 0 +1002 0 +1003 0 +1004 0 +1005 1 +1006 0 +1007 0 +1008 0 +1009 0 +1010 0 +1011 0 +1012 1 +1013 0 +1014 0 +1015 0 +1016 0 +1017 0 +1018 0 +1019 0 +1020 0 +1021 0 +1022 0 +1023 0 +1024 0 +1025 0 +1026 0 +1027 0 +1028 0 +1029 0 +1030 0 +1031 1 +1032 0 +1033 0 +1034 0 +1035 0 +1036 0 +1037 0 +1038 0 +1039 0 +1040 0 +1041 0 +1042 1 +1043 0 +1044 0 +1045 0 +1046 0 +1047 0 +1048 0 +1049 0 +1050 1 +1051 0 +1052 0 +1053 0 +1054 0 +1055 0 +1056 0 +1057 1 +1058 0 +1059 0 +1060 0 +1061 0 +1062 0 +1063 0 +1064 0 +1065 0 +1066 0 +1067 1 +1068 0 +1069 0 +1070 0 +1071 0 +1072 0 +1073 0 +1074 0 +1075 0 +1076 0 +1077 1 +1078 0 +1079 0 +1080 0 +1081 0 +1082 0 +1083 0 +1084 0 +1085 0 +1086 0 +1087 1 +1088 0 +1089 0 +1090 0 +1091 0 +1092 0 +1093 0 +1094 1 +1095 0 +1096 0 +1097 0 +1098 0 +1099 0 +1100 0 +1101 0 +1102 1 +1103 0 +1104 0 +1105 0 +1106 0 +1107 0 +1108 0 +1109 0 +1110 0 +1111 1 +1112 0 +1113 0 +1114 0 +1115 0 +1116 0 +1117 0 +1118 0 +1119 0 +1120 1 +1121 0 +1122 0 +1123 0 +1124 0 +1125 0 +1126 0 +1127 0 +1128 0 +1129 0 +1130 1 +1131 0 +1132 0 +1133 0 +1134 0 +1135 0 +1136 0 +1137 0 +1138 0 +1139 0 +1140 1 +1141 0 +1142 0 +1143 0 +1144 0 +1145 0 +1146 0 +1147 0 +1148 0 +1149 0 +1150 0 +1151 1 +1152 0 +1153 0 +1154 0 +1155 0 +1156 0 +1157 0 +1158 0 +1159 0 +1160 1 +1161 0 +1162 0 +1163 0 +1164 0 +1165 0 +1166 0 +1167 1 +1168 0 +1169 0 +1170 0 +1171 0 +1172 0 +1173 0 +1174 0 +1175 0 +1176 1 +1177 0 +1178 0 +1179 0 +1180 0 +1181 0 +1182 1 +1183 0 +1184 0 +1185 0 +1186 0 +1187 0 +1188 0 +1189 0 +1190 1 +1191 0 +1192 0 +1193 0 +1194 0 +1195 0 +1196 0 +1197 0 +1198 1 +1199 0 +1200 0 +1201 0 +1202 0 +1203 0 +1204 0 +1205 0 +1206 1 +1207 0 +1208 0 +1209 0 +1210 0 +1211 0 +1212 0 +1213 0 +1214 0 +1215 0 +1216 1 +1217 0 +1218 0 +1219 0 +1220 0 +1221 0 +1222 0 +1223 0 +1224 0 +1225 0 +1226 1 +1227 0 +1228 0 +1229 0 +1230 0 +1231 0 +1232 0 +1233 0 +1234 0 +1235 0 +1236 0 +1237 0 +1238 0 +1239 1 +1240 0 +1241 0 +1242 0 +1243 0 +1244 0 +1245 0 +1246 0 +1247 0 +1248 1 +1249 0 +1250 0 +1251 0 +1252 0 +1253 0 +1254 0 +1255 0 +1256 0 +1257 1 +1258 0 +1259 0 +1260 0 +1261 0 +1262 0 +1263 0 +1264 0 +1265 0 +1266 1 +1267 0 +1268 0 +1269 0 +1270 0 +1271 0 +1272 0 +1273 0 +1274 0 +1275 1 +1276 0 +1277 0 +1278 0 +1279 0 +1280 0 +1281 0 +1282 0 +1283 0 +1284 0 +1285 0 +1286 0 +1287 0 +1288 0 +1289 0 +1290 0 +1291 0 +1292 0 +1293 1 +1294 0 +1295 0 +1296 0 +1297 0 +1298 0 +1299 0 +1300 0 +1301 0 +1302 0 +1303 0 +1304 0 +1305 0 +1306 0 +1307 0 +1308 0 +1309 0 +1310 1 +1311 0 +1312 0 +1313 0 +1314 0 +1315 0 +1316 0 +1317 0 +1318 1 +1319 0 +1320 0 +1321 0 +1322 0 +1323 0 +1324 0 +1325 0 +1326 0 +1327 1 +1328 0 +1329 0 +1330 0 +1331 0 +1332 0 +1333 0 +1334 0 +1335 0 +1336 1 +1337 0 +1338 0 +1339 0 +1340 0 +1341 0 +1342 0 +1343 0 +1344 0 +1345 0 +1346 1 +1347 0 +1348 0 +1349 0 +1350 0 +1351 0 +1352 0 +1353 0 +1354 0 +1355 0 +1356 1 +1357 0 +1358 0 +1359 0 +1360 0 +1361 0 +1362 0 +1363 0 +1364 0 +1365 1 +1366 0 +1367 0 +1368 0 +1369 0 +1370 0 +1371 0 +1372 0 +1373 1 +1374 0 +1375 0 +1376 0 +1377 0 +1378 0 +1379 0 +1380 0 +1381 0 +1382 0 +1383 1 +1384 0 +1385 0 +1386 0 +1387 0 +1388 0 +1389 0 +1390 0 +1391 0 +1392 1 +1393 0 +1394 0 +1395 0 +1396 0 +1397 0 +1398 0 +1399 0 +1400 1 +1401 0 +1402 0 +1403 0 +1404 0 +1405 0 +1406 0 +1407 0 +1408 0 +1409 0 +1410 1 +1411 0 +1412 0 +1413 0 +1414 0 +1415 0 +1416 0 +1417 0 +1418 0 +1419 0 +1420 1 +1421 0 +1422 0 +1423 0 +1424 0 +1425 0 +1426 0 +1427 0 +1428 0 +1429 0 +1430 0 +1431 1 +1432 0 +1433 0 +1434 0 +1435 0 +1436 0 +1437 0 +1438 0 +1439 0 +1440 0 +1441 1 +1442 0 +1443 0 +1444 0 +1445 0 +1446 0 +1447 2 +1448 0 +1449 0 +1450 0 +1451 0 +1452 0 +1453 0 +1454 0 +1455 1 +1456 0 +1457 0 +1458 0 +1459 0 +1460 0 +1461 0 +1462 0 +1463 0 +1464 0 +1465 1 +1466 0 +1467 0 +1468 0 +1469 0 +1470 0 +1471 0 +1472 0 +1473 0 +1474 0 +1475 1 +1476 0 +1477 0 +1478 0 +1479 0 +1480 0 +1481 0 +1482 0 +1483 0 +1484 0 +1485 1 +1486 0 +1487 0 +1488 0 +1489 0 +1490 0 +1491 0 +1492 0 +1493 0 +1494 1 +1495 0 +1496 0 +1497 0 +1498 0 +1499 0 +1500 0 +1501 0 +1502 0 +1503 1 +1504 0 +1505 0 +1506 0 +1507 0 +1508 0 +1509 0 +1510 0 +1511 0 +1512 0 +1513 0 +1514 0 +1515 0 +1516 0 +1517 0 +1518 0 +1519 0 +1520 1 +1521 0 +1522 0 +1523 0 +1524 0 +1525 0 +1526 0 +1527 0 +1528 0 +1529 1 +1530 0 +1531 0 +1532 0 +1533 0 +1534 0 +1535 0 +1536 0 +1537 0 +1538 0 +1539 1 +1540 0 +1541 0 +1542 0 +1543 0 +1544 0 +1545 0 +1546 0 +1547 0 +1548 1 +1549 0 +1550 0 +1551 0 +1552 0 +1553 0 +1554 0 +1555 0 +1556 0 +1557 1 +1558 0 +1559 0 +1560 0 +1561 0 +1562 0 +1563 0 +1564 0 +1565 0 +1566 0 +1567 1 +1568 0 +1569 0 +1570 0 +1571 0 +1572 0 +1573 0 +1574 0 +1575 1 +1576 0 +1577 0 +1578 0 +1579 0 +1580 0 +1581 0 +1582 0 +1583 0 +1584 1 +1585 0 +1586 0 +1587 0 +1588 0 +1589 0 +1590 0 +1591 0 +1592 0 +1593 1 +1594 0 +1595 0 +1596 0 +1597 0 +1598 0 +1599 0 +1600 0 +1601 0 +1602 1 +1603 0 +1604 0 +1605 0 +1606 0 +1607 0 +1608 0 +1609 0 +1610 0 +1611 1 +1612 0 +1613 0 +1614 0 +1615 0 +1616 0 +1617 0 +1618 0 +1619 0 +1620 0 +1621 1 +1622 0 +1623 0 +1624 0 +1625 0 +1626 0 +1627 0 +1628 0 +1629 0 +1630 0 +1631 1 +1632 0 +1633 0 +1634 0 +1635 0 +1636 0 +1637 0 +1638 0 +1639 0 +1640 1 +1641 0 +1642 0 +1643 0 +1644 0 +1645 0 +1646 0 +1647 0 +1648 0 +1649 0 +1650 1 +1651 0 +1652 0 +1653 0 +1654 0 +1655 0 +1656 0 +1657 0 +1658 0 +1659 0 +1660 1 +1661 0 +1662 0 +1663 0 +1664 0 +1665 0 +1666 0 +1667 0 +1668 0 +1669 0 +1670 1 +1671 0 +1672 0 +1673 0 +1674 0 +1675 0 +1676 0 +1677 0 +1678 0 +1679 0 +1680 1 +1681 0 +1682 0 +1683 0 +1684 0 +1685 0 +1686 0 +1687 0 +1688 0 +1689 0 +1690 1 +1691 0 +1692 0 +1693 0 +1694 0 +1695 0 +1696 0 +1697 0 +1698 0 +1699 0 +1700 0 +1701 1 +1702 0 +1703 0 +1704 0 +1705 0 +1706 0 +1707 0 +1708 1 +1709 0 +1710 0 +1711 0 +1712 0 +1713 0 +1714 0 +1715 0 +1716 1 +1717 0 +1718 0 +1719 0 +1720 0 +1721 0 +1722 0 +1723 0 +1724 0 +1725 0 +1726 0 +1727 0 +1728 0 +1729 0 +1730 0 +1731 0 +1732 0 +1733 0 +1734 1 +1735 0 +1736 0 +1737 0 +1738 0 +1739 0 +1740 0 +1741 0 +1742 0 +1743 1 +1744 0 +1745 0 +1746 0 +1747 0 +1748 0 +1749 0 +1750 0 +1751 0 +1752 0 +1753 1 +1754 0 +1755 0 +1756 0 +1757 0 +1758 0 +1759 0 +1760 0 +1761 0 +1762 0 +1763 1 +1764 0 +1765 0 +1766 0 +1767 0 +1768 0 +1769 0 +1770 0 +1771 0 +1772 0 +1773 1 +1774 0 +1775 0 +1776 0 +1777 0 +1778 0 +1779 0 +1780 0 +1781 0 +1782 0 +1783 1 +1784 0 +1785 0 +1786 0 +1787 0 +1788 0 +1789 0 +1790 0 +1791 0 +1792 0 +1793 1 +1794 0 +1795 0 +1796 0 +1797 0 +1798 0 +1799 0 +1800 0 +1801 0 +1802 0 +1803 1 +1804 0 +1805 0 +1806 0 +1807 0 +1808 0 +1809 0 +1810 0 +1811 0 +1812 0 +1813 1 +1814 0 +1815 0 +1816 0 +1817 0 +1818 0 +1819 0 +1820 0 +1821 0 +1822 1 +1823 0 +1824 0 +1825 0 +1826 0 +1827 0 +1828 0 +1829 1 +1830 0 +1831 0 +1832 0 +1833 0 +1834 0 +1835 0 +1836 0 +1837 0 +1838 0 +1839 1 +1840 0 +1841 0 +1842 0 +1843 0 +1844 0 +1845 0 +1846 0 +1847 0 +1848 0 +1849 1 +1850 0 +1851 0 +1852 0 +1853 0 +1854 0 +1855 0 +1856 0 +1857 0 +1858 0 +1859 1 +1860 0 +1861 0 +1862 0 +1863 0 +1864 0 +1865 0 +1866 0 +1867 0 +1868 0 +1869 1 +1870 0 +1871 0 +1872 0 +1873 0 +1874 0 +1875 0 +1876 0 +1877 0 +1878 0 +1879 1 +1880 0 +1881 0 +1882 0 +1883 0 +1884 0 +1885 0 +1886 0 +1887 0 +1888 0 +1889 1 +1890 0 +1891 0 +1892 0 +1893 0 +1894 0 +1895 0 +1896 0 +1897 0 +1898 0 +1899 0 +1900 0 +1901 0 +1902 0 +1903 0 +1904 0 +1905 0 +1906 0 +1907 0 +1908 0 +1909 0 +1910 1 +1911 0 +1912 0 +1913 0 +1914 0 +1915 0 +1916 0 +1917 0 +1918 0 +1919 0 +1920 0 +1921 0 +1922 0 +1923 0 +1924 0 +1925 0 +1926 0 +1927 0 +1928 0 +1929 0 +1930 1 +1931 0 +1932 0 +1933 0 +1934 0 +1935 0 +1936 0 +1937 0 +1938 0 +1939 1 +1940 0 +1941 0 +1942 0 +1943 0 +1944 0 +1945 0 +1946 0 +1947 0 +1948 0 +1949 1 +1950 0 +1951 0 +1952 0 +1953 0 +1954 0 +1955 0 +1956 0 +1957 0 +1958 1 +1959 0 +1960 0 +1961 0 +1962 0 +1963 0 +1964 0 +1965 0 +1966 0 +1967 0 +1968 1 +1969 0 +1970 0 +1971 0 +1972 0 +1973 0 +1974 0 +1975 0 +1976 0 +1977 0 +1978 1 +1979 0 +1980 0 +1981 0 +1982 0 +1983 0 +1984 0 +1985 0 +1986 0 +1987 0 +1988 1 +1989 0 +1990 0 +1991 0 +1992 0 +1993 0 +1994 0 +1995 0 +1996 1 +1997 0 +1998 0 +1999 0 +2000 0 +2001 0 +2002 0 +2003 0 +2004 1 +2005 0 +2006 0 +2007 0 +2008 0 +2009 0 +2010 0 +2011 0 +2012 0 +2013 0 +2014 1 +2015 0 +2016 0 +2017 0 +2018 0 +2019 0 +2020 0 +2021 0 +2022 0 +2023 0 +2024 1 +2025 0 +2026 0 +2027 0 +2028 0 +2029 0 +2030 0 +2031 0 +2032 0 +2033 1 +2034 0 +2035 0 +2036 0 +2037 0 +2038 0 +2039 0 +2040 0 +2041 2 +2042 0 +2043 0 +2044 0 +2045 0 +2046 0 +2047 0 +2048 0 +2049 1 +2050 0 +2051 0 +2052 0 +2053 0 +2054 0 +2055 0 +2056 0 +2057 0 +2058 0 +2059 0 +2060 0 +2061 0 +2062 0 +2063 0 +2064 0 +2065 0 +2066 0 +2067 1 +2068 0 +2069 0 +2070 0 +2071 0 +2072 0 +2073 0 +2074 0 +2075 0 +2076 1 +2077 0 +2078 0 +2079 0 +2080 0 +2081 0 +2082 0 +2083 0 +2084 0 +2085 0 +2086 1 +2087 0 +2088 0 +2089 0 +2090 0 +2091 0 +2092 0 +2093 0 +2094 0 +2095 0 +2096 1 +2097 0 +2098 0 +2099 0 +2100 0 +2101 0 +2102 0 +2103 0 +2104 0 +2105 1 +2106 0 +2107 0 +2108 0 +2109 0 +2110 0 +2111 0 +2112 0 +2113 0 +2114 0 +2115 0 +2116 1 +2117 0 +2118 0 +2119 0 +2120 0 +2121 0 +2122 0 +2123 0 +2124 0 +2125 1 +2126 0 +2127 0 +2128 0 +2129 0 +2130 0 +2131 0 +2132 0 +2133 1 +2134 0 +2135 0 +2136 0 +2137 0 +2138 0 +2139 0 +2140 0 +2141 1 +2142 0 +2143 0 +2144 0 +2145 0 +2146 0 +2147 0 +2148 0 +2149 0 +2150 1 +2151 0 +2152 0 +2153 0 +2154 0 +2155 0 +2156 0 +2157 0 +2158 0 +2159 1 +2160 0 +2161 0 +2162 0 +2163 0 +2164 0 +2165 0 +2166 0 +2167 0 +2168 0 +2169 1 +2170 0 +2171 0 +2172 0 +2173 0 +2174 0 +2175 0 +2176 0 +2177 1 +2178 0 +2179 0 +2180 0 +2181 0 +2182 0 +2183 0 +2184 0 +2185 0 +2186 0 +2187 1 +2188 0 +2189 0 +2190 0 +2191 0 +2192 0 +2193 0 +2194 0 +2195 0 +2196 1 +2197 0 +2198 0 +2199 0 +2200 0 +2201 0 +2202 0 +2203 0 +2204 1 +2205 0 +2206 0 +2207 0 +2208 0 +2209 0 +2210 0 +2211 0 +2212 0 +2213 0 +2214 1 +2215 0 +2216 0 +2217 0 +2218 0 +2219 0 +2220 0 +2221 0 +2222 0 +2223 0 +2224 1 +2225 0 +2226 0 +2227 0 +2228 0 +2229 0 +2230 0 +2231 0 +2232 0 +2233 1 +2234 0 +2235 0 +2236 0 +2237 0 +2238 0 +2239 0 +2240 0 +2241 0 +2242 1 +2243 0 +2244 0 +2245 0 +2246 0 +2247 0 +2248 0 +2249 0 +2250 1 +2251 0 +2252 0 +2253 0 +2254 0 +2255 0 +2256 0 +2257 0 +2258 0 +2259 0 +2260 1 +2261 0 +2262 0 +2263 0 +2264 0 +2265 0 +2266 0 +2267 0 +2268 0 +2269 0 +2270 1 +2271 0 +2272 0 +2273 0 +2274 0 +2275 0 +2276 0 +2277 0 +2278 0 +2279 0 +2280 1 +2281 0 +2282 0 +2283 0 +2284 0 +2285 0 +2286 0 +2287 0 +2288 0 +2289 0 +2290 1 +2291 0 +2292 0 +2293 0 +2294 0 +2295 0 +2296 0 +2297 0 +2298 1 +2299 0 +2300 0 +2301 0 +2302 0 +2303 0 +2304 0 +2305 0 +2306 1 +2307 0 +2308 0 +2309 0 +2310 0 +2311 0 +2312 0 +2313 0 +2314 0 +2315 1 +2316 0 +2317 0 +2318 0 +2319 0 +2320 0 +2321 0 +2322 0 +2323 0 +2324 0 +2325 1 +2326 0 +2327 0 +2328 0 +2329 0 +2330 0 +2331 0 +2332 0 +2333 0 +2334 0 +2335 1 +2336 0 +2337 0 +2338 0 +2339 0 +2340 0 +2341 0 +2342 0 +2343 0 +2344 0 +2345 1 +2346 0 +2347 0 +2348 0 +2349 0 +2350 0 +2351 0 +2352 0 +2353 1 +2354 0 +2355 0 +2356 0 +2357 0 +2358 0 +2359 0 +2360 0 +2361 1 +2362 0 +2363 0 +2364 0 +2365 0 +2366 0 +2367 0 +2368 0 +2369 0 +2370 0 +2371 1 +2372 0 +2373 0 +2374 0 +2375 0 +2376 0 +2377 0 +2378 0 +2379 0 +2380 0 +2381 1 +2382 0 +2383 0 +2384 0 +2385 0 +2386 0 +2387 0 +2388 0 +2389 0 +2390 1 +2391 0 +2392 0 +2393 0 +2394 0 +2395 0 +2396 0 +2397 0 +2398 0 +2399 0 +2400 0 +2401 0 +2402 0 +2403 0 +2404 0 +2405 0 +2406 0 +2407 0 +2408 0 +2409 0 +2410 0 +2411 1 +2412 0 +2413 0 +2414 0 +2415 0 +2416 0 +2417 0 +2418 0 +2419 0 +2420 0 +2421 1 +2422 0 +2423 0 +2424 0 +2425 0 +2426 0 +2427 0 +2428 0 +2429 0 +2430 0 +2431 0 +2432 0 +2433 0 +2434 0 +2435 0 +2436 0 +2437 0 +2438 0 +2439 0 +2440 1 +2441 0 +2442 0 +2443 0 +2444 0 +2445 0 +2446 0 +2447 0 +2448 0 +2449 0 +2450 0 +2451 1 +2452 0 +2453 0 +2454 0 +2455 0 +2456 0 +2457 0 +2458 0 +2459 0 +2460 0 +2461 1 +2462 0 +2463 0 +2464 0 +2465 0 +2466 0 +2467 0 +2468 0 +2469 1 +2470 0 +2471 0 +2472 0 +2473 0 +2474 0 +2475 0 +2476 0 +2477 1 +2478 0 +2479 0 +2480 0 +2481 0 +2482 0 +2483 0 +2484 0 +2485 0 +2486 1 +2487 0 +2488 0 +2489 0 +2490 0 +2491 0 +2492 0 +2493 0 +2494 0 +2495 0 +2496 1 +2497 0 +2498 0 +2499 0 +2500 0 +2501 0 +2502 0 +2503 0 +2504 0 +2505 0 +2506 1 +2507 0 +2508 0 +2509 0 +2510 0 +2511 0 +2512 0 +2513 0 +2514 0 +2515 0 +2516 1 +2517 0 +2518 0 +2519 0 +2520 0 +2521 0 +2522 0 +2523 0 +2524 0 +2525 0 +2526 0 +2527 1 +2528 0 +2529 0 +2530 0 +2531 0 +2532 0 +2533 0 +2534 0 +2535 0 +2536 0 +2537 1 +2538 0 +2539 0 +2540 0 +2541 0 +2542 0 +2543 0 +2544 0 +2545 0 +2546 0 +2547 0 +2548 0 +2549 0 +2550 0 +2551 0 +2552 0 +2553 0 +2554 0 +2555 0 +2556 0 +2557 1 +2558 0 +2559 0 +2560 0 +2561 0 +2562 0 +2563 0 +2564 0 +2565 0 +2566 1 +2567 0 +2568 0 +2569 0 +2570 0 +2571 0 +2572 0 +2573 0 +2574 0 +2575 1 +2576 0 +2577 0 +2578 0 +2579 0 +2580 0 +2581 0 +2582 0 +2583 0 +2584 1 +2585 0 +2586 0 +2587 0 +2588 0 +2589 0 +2590 0 +2591 0 +2592 0 +2593 0 +2594 0 +2595 1 +2596 0 +2597 0 +2598 0 +2599 0 +2600 0 +2601 0 +2602 0 +2603 0 +2604 0 +2605 1 +2606 0 +2607 0 +2608 0 +2609 0 +2610 0 +2611 0 +2612 0 +2613 0 +2614 0 +2615 0 +2616 0 +2617 0 +2618 0 +2619 0 +2620 0 +2621 0 +2622 0 +2623 0 +2624 0 +2625 1 +2626 0 +2627 0 +2628 0 +2629 0 +2630 0 +2631 0 +2632 0 +2633 0 +2634 0 +2635 1 +2636 0 +2637 0 +2638 0 +2639 1 +2640 0 +2641 0 +2642 0 +2643 1 +2644 0 +2645 0 +2646 0 +2647 0 +2648 0 +2649 0 +2650 0 +2651 0 +2652 0 +2653 1 +2654 0 +2655 0 +2656 0 +2657 0 +2658 0 +2659 0 +2660 0 +2661 0 +2662 0 +2663 1 +2664 0 +2665 0 +2666 0 +2667 0 +2668 0 +2669 0 +2670 0 +2671 1 +2672 0 +2673 0 +2674 0 +2675 0 +2676 0 +2677 0 +2678 0 +2679 1 +2680 0 +2681 0 +2682 0 +2683 0 +2684 0 +2685 0 +2686 0 +2687 0 +2688 0 +2689 1 +2690 0 +2691 0 +2692 0 +2693 0 +2694 0 +2695 0 +2696 0 +2697 0 +2698 0 +2699 1 +2700 0 +2701 0 +2702 0 +2703 0 +2704 0 +2705 0 +2706 0 +2707 0 +2708 0 +2709 1 +2710 0 +2711 0 +2712 0 +2713 0 +2714 0 +2715 0 +2716 1 +2717 0 +2718 0 +2719 0 +2720 0 +2721 0 +2722 0 +2723 0 +2724 1 +2725 0 +2726 0 +2727 0 +2728 0 +2729 0 +2730 0 +2731 0 +2732 0 +2733 0 +2734 1 +2735 0 +2736 0 +2737 0 +2738 0 +2739 0 +2740 0 +2741 0 +2742 0 +2743 0 +2744 1 +2745 0 +2746 0 +2747 0 +2748 0 +2749 0 +2750 0 +2751 0 +2752 0 +2753 1 +2754 0 +2755 0 +2756 0 +2757 0 +2758 0 +2759 0 +2760 0 +2761 0 +2762 0 +2763 1 +2764 0 +2765 0 +2766 0 +2767 0 +2768 0 +2769 0 +2770 0 +2771 0 +2772 0 +2773 1 +2774 0 +2775 0 +2776 0 +2777 0 +2778 0 +2779 0 +2780 0 +2781 0 +2782 0 +2783 1 +2784 0 +2785 0 +2786 0 +2787 0 +2788 0 +2789 0 +2790 0 +2791 0 +2792 1 +2793 0 +2794 0 +2795 0 +2796 0 +2797 0 +2798 0 +2799 0 +2800 0 +2801 0 +2802 0 +2803 0 +2804 0 +2805 0 +2806 0 +2807 0 +2808 0 +2809 0 +2810 0 +2811 0 +2812 0 +2813 0 +2814 0 +2815 0 +2816 0 +2817 0 +2818 0 +2819 0 +2820 0 +2821 1 +2822 0 +2823 0 +2824 0 +2825 0 +2826 0 +2827 0 +2828 0 +2829 0 +2830 0 +2831 1 +2832 0 +2833 0 +2834 0 +2835 0 +2836 0 +2837 0 +2838 0 +2839 0 +2840 0 +2841 1 +2842 0 +2843 0 +2844 0 +2845 0 +2846 0 +2847 0 +2848 0 +2849 0 +2850 0 +2851 1 +2852 0 +2853 0 +2854 0 +2855 0 +2856 0 +2857 0 +2858 0 +2859 0 +2860 0 +2861 1 +2862 0 +2863 0 +2864 0 +2865 0 +2866 0 +2867 0 +2868 0 +2869 0 +2870 0 +2871 1 +2872 0 +2873 0 +2874 0 +2875 0 +2876 0 +2877 0 +2878 0 +2879 0 +2880 1 +2881 0 +2882 0 +2883 0 +2884 0 +2885 0 +2886 0 +2887 0 +2888 1 +2889 0 +2890 0 +2891 0 +2892 0 +2893 0 +2894 0 +2895 0 +2896 0 +2897 1 +2898 0 +2899 0 +2900 0 +2901 0 +2902 0 +2903 0 +2904 0 +2905 0 +2906 1 +2907 0 +2908 0 +2909 0 +2910 0 +2911 0 +2912 0 +2913 0 +2914 1 +2915 0 +2916 0 +2917 0 +2918 0 +2919 0 +2920 0 +2921 0 +2922 1 +2923 0 +2924 0 +2925 0 +2926 0 +2927 0 +2928 0 +2929 0 +2930 0 +2931 0 +2932 0 +2933 0 +2934 0 +2935 0 +2936 0 +2937 0 +2938 1 +2939 0 +2940 0 +2941 0 +2942 0 +2943 0 +2944 0 +2945 0 +2946 0 +2947 0 +2948 0 +2949 1 +2950 0 +2951 0 +2952 0 +2953 0 +2954 0 +2955 0 +2956 0 +2957 0 +2958 0 +2959 1 +2960 0 +2961 0 +2962 0 +2963 0 +2964 0 +2965 0 +2966 0 +2967 0 +2968 1 +2969 0 +2970 0 +2971 0 +2972 0 +2973 0 +2974 0 +2975 0 +2976 0 +2977 1 +2978 0 +2979 0 +2980 0 +2981 0 +2982 0 +2983 0 +2984 0 +2985 0 +2986 0 +2987 1 +2988 0 +2989 0 +2990 0 +2991 0 +2992 0 +2993 0 +2994 0 +2995 0 +2996 0 +2997 1 +2998 0 +2999 0 +3000 0 +3001 0 +3002 0 +3003 0 +3004 0 +3005 0 +3006 0 +3007 0 +3008 0 +3009 0 +3010 0 +3011 0 +3012 0 +3013 0 +3014 0 +3015 1 +3016 0 +3017 0 +3018 0 +3019 0 +3020 0 +3021 0 +3022 0 +3023 0 +3024 0 +3025 1 +3026 0 +3027 0 +3028 0 +3029 0 +3030 0 +3031 0 +3032 0 +3033 0 +3034 1 +3035 0 +3036 0 +3037 0 +3038 0 +3039 0 +3040 0 +3041 0 +3042 1 +3043 0 +3044 0 +3045 0 +3046 0 +3047 0 +3048 0 +3049 0 +3050 0 +3051 0 +3052 1 +3053 0 +3054 0 +3055 0 +3056 0 +3057 0 +3058 0 +3059 0 +3060 0 +3061 0 +3062 1 +3063 0 +3064 0 +3065 0 +3066 0 +3067 0 +3068 0 +3069 0 +3070 0 +3071 0 +3072 1 +3073 0 +3074 0 +3075 0 +3076 0 +3077 0 +3078 0 +3079 0 +3080 0 +3081 0 +3082 1 +3083 0 +3084 0 +3085 0 +3086 0 +3087 0 +3088 0 +3089 0 +3090 0 +3091 0 +3092 1 +3093 0 +3094 0 +3095 0 +3096 0 +3097 0 +3098 0 +3099 0 +3100 0 +3101 0 +3102 1 +3103 0 +3104 0 +3105 0 +3106 0 +3107 0 +3108 0 +3109 0 +3110 0 +3111 0 +3112 1 +3113 0 +3114 0 +3115 0 +3116 0 +3117 0 +3118 0 +3119 0 +3120 1 +3121 0 +3122 0 +3123 0 +3124 0 +3125 0 +3126 0 +3127 0 +3128 0 +3129 1 +3130 0 +3131 0 +3132 0 +3133 0 +3134 0 +3135 0 +3136 0 +3137 0 +3138 0 +3139 1 +3140 0 +3141 0 +3142 0 +3143 0 +3144 0 +3145 0 +3146 0 +3147 0 +3148 0 +3149 1 +3150 0 +3151 0 +3152 0 +3153 0 +3154 0 +3155 0 +3156 0 +3157 1 +3158 0 +3159 0 +3160 0 +3161 0 +3162 0 +3163 0 +3164 0 +3165 1 +3166 0 +3167 0 +3168 0 +3169 0 +3170 0 +3171 0 +3172 0 +3173 0 +3174 0 +3175 1 +3176 0 +3177 0 +3178 0 +3179 0 +3180 0 +3181 0 +3182 0 +3183 0 +3184 0 +3185 1 +3186 0 +3187 0 +3188 0 +3189 0 +3190 0 +3191 0 +3192 0 +3193 0 +3194 0 +3195 0 +3196 1 +3197 0 +3198 0 +3199 0 +3200 0 +3201 0 +3202 0 +3203 0 +3204 0 +3205 0 +3206 0 +3207 1 +3208 0 +3209 0 +3210 0 +3211 0 +3212 0 +3213 0 +3214 0 +3215 1 +3216 0 +3217 0 +3218 0 +3219 0 +3220 0 +3221 0 +3222 0 +3223 1 +3224 0 +3225 0 +3226 0 +3227 0 +3228 0 +3229 0 +3230 0 +3231 0 +3232 1 +3233 0 +3234 1 +3235 0 +3236 0 +3237 0 +3238 0 +3239 1 +3240 0 +3241 0 +3242 0 +3243 0 +3244 0 +3245 0 +3246 0 +3247 0 +3248 1 +3249 0 +3250 0 +3251 0 +3252 0 +3253 0 +3254 0 +3255 0 +3256 0 +3257 0 +3258 1 +3259 0 +3260 0 +3261 0 +3262 0 +3263 0 +3264 0 +3265 0 +3266 0 +3267 0 +3268 0 +3269 1 +3270 0 +3271 0 +3272 0 +3273 0 +3274 0 +3275 0 +3276 0 +3277 0 +3278 1 +3279 0 +3280 0 +3281 0 +3282 0 +3283 0 +3284 0 +3285 0 +3286 0 +3287 1 +3288 0 +3289 0 +3290 0 +3291 0 +3292 0 +3293 0 +3294 0 +3295 0 +3296 0 +3297 1 +3298 0 +3299 0 +3300 0 +3301 0 +3302 0 +3303 0 +3304 0 +3305 0 +3306 0 +3307 1 +3308 0 +3309 0 +3310 0 +3311 0 +3312 0 +3313 0 +3314 0 +3315 0 +3316 0 +3317 1 +3318 0 +3319 0 +3320 0 +3321 0 +3322 0 +3323 0 +3324 0 +3325 1 +3326 0 +3327 0 +3328 0 +3329 0 +3330 0 +3331 0 +3332 0 +3333 0 +3334 0 +3335 1 +3336 0 +3337 0 +3338 0 +3339 0 +3340 0 +3341 0 +3342 0 +3343 0 +3344 1 +3345 0 +3346 0 +3347 0 +3348 0 +3349 0 +3350 0 +3351 0 +3352 0 +3353 0 +3354 1 +3355 0 +3356 0 +3357 0 +3358 0 +3359 0 +3360 0 +3361 0 +3362 0 +3363 0 +3364 0 +3365 1 +3366 0 +3367 0 +3368 0 +3369 0 +3370 0 +3371 0 +3372 0 +3373 0 +3374 0 +3375 1 +3376 0 +3377 0 +3378 0 +3379 0 +3380 0 +3381 0 +3382 0 +3383 0 +3384 0 +3385 0 +3386 1 +3387 0 +3388 0 +3389 0 +3390 0 +3391 0 +3392 0 +3393 0 +3394 0 +3395 0 +3396 0 +3397 1 +3398 0 +3399 0 +3400 0 +3401 0 +3402 0 +3403 0 +3404 0 +3405 0 +3406 0 +3407 1 +3408 0 +3409 0 +3410 0 +3411 0 +3412 0 +3413 0 +3414 0 +3415 0 +3416 0 +3417 1 +3418 0 +3419 0 +3420 0 +3421 0 +3422 0 +3423 0 +3424 0 +3425 0 +3426 0 +3427 0 +3428 1 +3429 0 +3430 0 +3431 0 +3432 0 +3433 0 +3434 0 +3435 0 +3436 0 +3437 1 +3438 0 +3439 0 +3440 0 +3441 0 +3442 0 +3443 0 +3444 0 +3445 1 +3446 0 +3447 0 +3448 0 +3449 0 +3450 0 +3451 0 +3452 0 +3453 0 +3454 1 +3455 0 +3456 0 +3457 0 +3458 0 +3459 0 +3460 0 +3461 0 +3462 0 +3463 0 +3464 1 +3465 0 +3466 0 +3467 0 +3468 0 +3469 0 +3470 0 +3471 0 +3472 0 +3473 0 +3474 1 +3475 0 +3476 0 +3477 0 +3478 0 +3479 0 +3480 0 +3481 0 +3482 0 +3483 0 +3484 1 +3485 0 +3486 0 +3487 0 +3488 0 +3489 0 +3490 0 +3491 0 +3492 0 +3493 0 +3494 1 +3495 0 +3496 0 +3497 0 +3498 0 +3499 0 +3500 0 +3501 0 +3502 0 +3503 0 +3504 1 +3505 0 +3506 0 +3507 0 +3508 0 +3509 0 +3510 0 +3511 0 +3512 0 +3513 0 +3514 1 +3515 0 +3516 0 +3517 0 +3518 0 +3519 0 +3520 0 +3521 0 +3522 0 +3523 0 +3524 1 +3525 0 +3526 0 +3527 0 +3528 0 +3529 0 +3530 0 +3531 0 +3532 0 +3533 1 +3534 0 +3535 0 +3536 0 +3537 0 +3538 0 +3539 0 +3540 0 +3541 0 +3542 0 +3543 0 +3544 0 +3545 0 +3546 0 +3547 0 +3548 0 +3549 0 +3550 0 +3551 1 +3552 0 +3553 0 +3554 0 +3555 0 +3556 0 +3557 0 +3558 0 +3559 0 +3560 0 +3561 1 +3562 0 +3563 0 +3564 0 +3565 0 +3566 0 +3567 0 +3568 0 +3569 0 +3570 1 +3571 0 +3572 0 +3573 0 +3574 0 +3575 0 +3576 0 +3577 0 +3578 0 +3579 0 +3580 1 +3581 0 +3582 0 +3583 0 +3584 0 +3585 0 +3586 0 +3587 0 +3588 0 +3589 0 +3590 1 +3591 0 +3592 0 +3593 0 +3594 0 +3595 0 +3596 0 +3597 0 +3598 0 +3599 1 +3600 0 +3601 0 +3602 0 +3603 0 +3604 0 +3605 0 +3606 0 +3607 0 +3608 0 +3609 1 +3610 0 +3611 0 +3612 0 +3613 0 +3614 0 +3615 0 +3616 0 +3617 0 +3618 0 +3619 0 +3620 1 +3621 0 +3622 0 +3623 0 +3624 0 +3625 0 +3626 0 +3627 0 +3628 0 +3629 0 +3630 1 +3631 0 +3632 0 +3633 0 +3634 0 +3635 0 +3636 0 +3637 0 +3638 0 +3639 1 +3640 0 +3641 0 +3642 0 +3643 0 +3644 0 +3645 1 +3646 0 +3647 0 +3648 0 +3649 0 +3650 0 +3651 1 +3652 0 +3653 0 +3654 0 +3655 0 +3656 0 +3657 0 +3658 1 +3659 0 +3660 0 +3661 0 +3662 0 +3663 0 +3664 0 +3665 0 +3666 1 +3667 0 +3668 0 +3669 0 +3670 0 +3671 0 +3672 0 +3673 0 +3674 0 +3675 0 +3676 1 +3677 0 +3678 0 +3679 0 +3680 0 +3681 0 +3682 0 +3683 0 +3684 0 +3685 1 +3686 0 +3687 0 +3688 0 +3689 0 +3690 0 +3691 0 +3692 0 +3693 0 +3694 0 +3695 1 +3696 0 +3697 0 +3698 0 +3699 0 +3700 0 +3701 0 +3702 0 +3703 0 +3704 0 +3705 0 +3706 1 +3707 0 +3708 0 +3709 0 +3710 0 +3711 0 +3712 0 +3713 0 +3714 0 +3715 0 +3716 1 +3717 0 +3718 0 +3719 0 +3720 0 +3721 0 +3722 0 +3723 0 +3724 0 +3725 0 +3726 0 +3727 0 +3728 0 +3729 0 +3730 0 +3731 0 +3732 0 +3733 0 +3734 0 +3735 0 +3736 1 +3737 0 +3738 0 +3739 0 +3740 0 +3741 0 +3742 0 +3743 0 +3744 0 +3745 0 +3746 1 +3747 0 +3748 0 +3749 0 +3750 0 +3751 0 +3752 0 +3753 0 +3754 0 +3755 0 +3756 1 +3757 0 +3758 0 +3759 0 +3760 0 +3761 0 +3762 0 +3763 1 +3764 0 +3765 0 +3766 0 +3767 0 +3768 0 +3769 0 +3770 0 +3771 1 +3772 0 +3773 0 +3774 0 +3775 0 +3776 0 +3777 0 +3778 1 +3779 0 +3780 0 +3781 0 +3782 0 +3783 0 +3784 0 +3785 0 +3786 0 +3787 0 +3788 0 +3789 0 +3790 0 +3791 0 +3792 0 +3793 0 +3794 0 +3795 0 +3796 0 +3797 1 +3798 0 +3799 0 +3800 0 +3801 0 +3802 0 +3803 0 +3804 0 +3805 0 +3806 1 +3807 0 +3808 0 +3809 0 +3810 0 +3811 0 +3812 0 +3813 0 +3814 0 +3815 0 +3816 0 +3817 1 +3818 0 +3819 0 +3820 0 +3821 0 +3822 0 +3823 0 +3824 0 +3825 0 +3826 0 +3827 1 +3828 0 +3829 1 +3830 0 +3831 0 +3832 0 +3833 0 +3834 1 +3835 0 +3836 0 +3837 0 +3838 0 +3839 0 +3840 0 +3841 0 +3842 0 +3843 0 +3844 0 +3845 1 +3846 0 +3847 0 +3848 0 +3849 0 +3850 0 +3851 0 +3852 0 +3853 0 +3854 0 +3855 1 +3856 0 +3857 0 +3858 0 +3859 0 +3860 0 +3861 0 +3862 0 +3863 1 +3864 0 +3865 0 +3866 0 +3867 0 +3868 0 +3869 0 +3870 0 +3871 0 +3872 0 +3873 1 +3874 0 +3875 0 +3876 0 +3877 0 +3878 0 +3879 0 +3880 0 +3881 0 +3882 0 +3883 1 +3884 0 +3885 0 +3886 0 +3887 0 +3888 0 +3889 0 +3890 0 +3891 0 +3892 0 +3893 0 +3894 1 +3895 0 +3896 0 +3897 0 +3898 0 +3899 0 +3900 0 +3901 0 +3902 0 +3903 0 +3904 0 +3905 1 +3906 0 +3907 0 +3908 0 +3909 0 +3910 0 +3911 0 +3912 0 +3913 0 +3914 1 +3915 0 +3916 0 +3917 0 +3918 0 +3919 0 +3920 0 +3921 0 +3922 0 +3923 0 +3924 0 +3925 1 +3926 0 +3927 0 +3928 0 +3929 0 +3930 0 +3931 0 +3932 0 +3933 0 +3934 1 +3935 0 +3936 0 +3937 0 +3938 0 +3939 0 +3940 0 +3941 0 +3942 0 +3943 0 +3944 0 +3945 1 +3946 0 +3947 0 +3948 0 +3949 0 +3950 0 +3951 0 +3952 0 +3953 0 +3954 0 +3955 1 +3956 0 +3957 0 +3958 0 +3959 0 +3960 0 +3961 0 +3962 0 +3963 0 +3964 0 +3965 0 +3966 1 +3967 0 +3968 0 +3969 0 +3970 0 +3971 0 +3972 0 +3973 0 +3974 0 +3975 1 +3976 0 +3977 0 +3978 0 +3979 0 +3980 0 +3981 0 +3982 0 +3983 0 +3984 1 +3985 0 +3986 0 +3987 0 +3988 0 +3989 0 +3990 0 +3991 0 +3992 0 +3993 0 +3994 1 +3995 0 +3996 0 +3997 0 +3998 0 +3999 0 +4000 0 +4001 0 +4002 0 +4003 0 +4004 0 +4005 0 +4006 0 +4007 0 +4008 0 +4009 0 +4010 0 +4011 0 +4012 0 +4013 0 +4014 1 +4015 0 +4016 0 +4017 0 +4018 0 +4019 0 +4020 0 +4021 0 +4022 0 +4023 0 +4024 1 +4025 0 +4026 0 +4027 0 +4028 0 +4029 0 +4030 0 +4031 0 +4032 0 +4033 0 +4034 0 +4035 1 +4036 0 +4037 0 +4038 0 +4039 0 +4040 0 +4041 0 +4042 0 +4043 0 +4044 0 +4045 1 +4046 0 +4047 0 +4048 0 +4049 0 +4050 0 +4051 0 +4052 0 +4053 0 +4054 0 +4055 0 +4056 1 +4057 0 +4058 0 +4059 0 +4060 0 +4061 0 +4062 0 +4063 0 +4064 0 +4065 0 +4066 1 +4067 0 +4068 0 +4069 0 +4070 0 +4071 0 +4072 0 +4073 0 +4074 1 +4075 0 +4076 0 +4077 0 +4078 0 +4079 0 +4080 0 +4081 0 +4082 0 +4083 0 +4084 1 +4085 0 +4086 0 +4087 0 +4088 0 +4089 0 +4090 0 +4091 0 +4092 0 +4093 1 +4094 0 +4095 0 +4096 0 +4097 0 +4098 0 +4099 0 +4100 0 +4101 0 +4102 1 +4103 0 +4104 0 +4105 0 +4106 0 +4107 0 +4108 0 +4109 0 +4110 0 +4111 0 +4112 1 +4113 0 +4114 0 +4115 0 +4116 0 +4117 0 +4118 0 +4119 0 +4120 0 +4121 0 +4122 1 +4123 0 +4124 0 +4125 0 +4126 0 +4127 0 +4128 0 +4129 0 +4130 0 +4131 0 +4132 0 +4133 1 +4134 0 +4135 0 +4136 0 +4137 0 +4138 0 +4139 0 +4140 0 +4141 0 +4142 0 +4143 0 +4144 1 +4145 0 +4146 0 +4147 0 +4148 0 +4149 0 +4150 0 +4151 0 +4152 0 +4153 0 +4154 1 +4155 0 +4156 0 +4157 0 +4158 0 +4159 0 +4160 0 +4161 0 +4162 0 +4163 0 +4164 0 +4165 1 +4166 0 +4167 0 +4168 0 +4169 0 +4170 0 +4171 0 +4172 0 +4173 0 +4174 0 +4175 0 +4176 1 +4177 0 +4178 0 +4179 0 +4180 0 +4181 0 +4182 0 +4183 0 +4184 0 +4185 1 +4186 0 +4187 0 +4188 0 +4189 0 +4190 0 +4191 0 +4192 0 +4193 0 +4194 0 +4195 1 +4196 0 +4197 0 +4198 0 +4199 0 +4200 0 +4201 0 +4202 0 +4203 0 +4204 0 +4205 0 +4206 0 +4207 0 +4208 0 +4209 0 +4210 0 +4211 0 +4212 1 +4213 0 +4214 0 +4215 0 +4216 0 +4217 0 +4218 0 +4219 0 +4220 0 +4221 1 +4222 0 +4223 0 +4224 0 +4225 0 +4226 0 +4227 0 +4228 0 +4229 0 +4230 1 +4231 0 +4232 0 +4233 0 +4234 0 +4235 0 +4236 0 +4237 0 +4238 0 +4239 1 +4240 0 +4241 0 +4242 0 +4243 0 +4244 0 +4245 0 +4246 0 +4247 0 +4248 0 +4249 1 +4250 0 +4251 0 +4252 0 +4253 0 +4254 0 +4255 0 +4256 0 +4257 0 +4258 1 +4259 0 +4260 0 +4261 0 +4262 0 +4263 0 +4264 0 +4265 0 +4266 0 +4267 0 +4268 1 +4269 0 +4270 0 +4271 0 +4272 0 +4273 0 +4274 0 +4275 0 +4276 0 +4277 0 +4278 1 +4279 0 +4280 0 +4281 0 +4282 0 +4283 0 +4284 0 +4285 0 +4286 0 +4287 0 +4288 0 +4289 1 +4290 0 +4291 0 +4292 0 +4293 0 +4294 0 +4295 0 +4296 0 +4297 0 +4298 0 +4299 1 +4300 0 +4301 0 +4302 0 +4303 0 +4304 0 +4305 0 +4306 0 +4307 0 +4308 0 +4309 1 +4310 0 +4311 0 +4312 0 +4313 0 +4314 0 +4315 0 +4316 0 +4317 0 +4318 1 +4319 0 +4320 0 +4321 0 +4322 0 +4323 0 +4324 0 +4325 0 +4326 0 +4327 1 +4328 0 +4329 0 +4330 0 +4331 0 +4332 0 +4333 0 +4334 0 +4335 0 +4336 0 +4337 1 +4338 0 +4339 0 +4340 0 +4341 0 +4342 0 +4343 0 +4344 0 +4345 0 +4346 0 +4347 1 +4348 0 +4349 0 +4350 0 +4351 0 +4352 0 +4353 0 +4354 0 +4355 1 +4356 0 +4357 0 +4358 0 +4359 0 +4360 0 +4361 0 +4362 0 +4363 0 +4364 0 +4365 0 +4366 0 +4367 0 +4368 0 +4369 0 +4370 0 +4371 0 +4372 0 +4373 0 +4374 1 +4375 0 +4376 0 +4377 0 +4378 0 +4379 0 +4380 0 +4381 0 +4382 0 +4383 0 +4384 1 +4385 0 +4386 0 +4387 0 +4388 0 +4389 0 +4390 0 +4391 0 +4392 0 +4393 1 +4394 0 +4395 0 +4396 0 +4397 0 +4398 0 +4399 0 +4400 0 +4401 0 +4402 0 +4403 1 +4404 0 +4405 0 +4406 0 +4407 0 +4408 0 +4409 0 +4410 0 +4411 0 +4412 1 +4413 0 +4414 0 +4415 0 +4416 0 +4417 0 +4418 0 +4419 0 +4420 0 +4421 0 +4422 0 +4423 1 +4424 0 +4425 0 +4426 0 +4427 0 +4428 0 +4429 0 +4430 2 +4431 0 +4432 0 +4433 0 +4434 0 +4435 0 +4436 0 +4437 1 +4438 0 +4439 0 +4440 0 +4441 0 +4442 0 +4443 0 +4444 0 +4445 1 +4446 0 +4447 0 +4448 0 +4449 0 +4450 0 +4451 0 +4452 0 +4453 0 +4454 1 +4455 0 +4456 0 +4457 0 +4458 0 +4459 0 +4460 0 +4461 0 +4462 1 +4463 0 +4464 0 +4465 0 +4466 0 +4467 0 +4468 0 +4469 0 +4470 0 +4471 1 +4472 0 +4473 0 +4474 0 +4475 0 +4476 0 +4477 0 +4478 0 +4479 0 +4480 1 +4481 0 +4482 0 +4483 0 +4484 0 +4485 0 +4486 0 +4487 0 +4488 1 +4489 0 +4490 0 +4491 0 +4492 0 +4493 0 +4494 0 +4495 0 +4496 0 +4497 1 +4498 0 +4499 0 +4500 0 +4501 0 +4502 0 +4503 0 +4504 0 +4505 1 +4506 0 +4507 0 +4508 0 +4509 0 +4510 0 +4511 0 +4512 0 +4513 1 +4514 0 +4515 0 +4516 0 +4517 0 +4518 0 +4519 0 +4520 1 +4521 0 +4522 0 +4523 0 +4524 0 +4525 0 +4526 0 +4527 0 +4528 0 +4529 1 +4530 0 +4531 0 +4532 0 +4533 0 +4534 0 +4535 0 +4536 0 +4537 0 +4538 1 +4539 0 +4540 0 +4541 0 +4542 0 +4543 0 +4544 0 +4545 0 +4546 1 +4547 0 +4548 0 +4549 0 +4550 0 +4551 0 +4552 1 +4553 0 +4554 0 +4555 0 +4556 0 +4557 0 +4558 0 +4559 1 +4560 0 +4561 0 +4562 0 +4563 0 +4564 0 +4565 0 +4566 0 +4567 1 +4568 0 +4569 0 +4570 0 +4571 0 +4572 0 +4573 0 +4574 0 +4575 1 +4576 0 +4577 0 +4578 0 +4579 0 +4580 0 +4581 0 +4582 0 +4583 1 +4584 0 +4585 0 +4586 0 +4587 0 +4588 0 +4589 0 +4590 0 +4591 1 +4592 0 +4593 0 +4594 0 +4595 0 +4596 0 +4597 0 +4598 0 +4599 0 +4600 1 +4601 0 +4602 0 +4603 0 +4604 0 +4605 0 +4606 0 +4607 1 +4608 0 +4609 0 +4610 0 +4611 0 +4612 0 +4613 0 +4614 0 +4615 0 +4616 1 +4617 0 +4618 0 +4619 0 +4620 0 +4621 0 +4622 0 +4623 0 +4624 0 +4625 1 +4626 0 +4627 0 +4628 0 +4629 0 +4630 0 +4631 0 +4632 0 +4633 0 +4634 1 +4635 0 +4636 0 +4637 0 +4638 0 +4639 0 +4640 0 +4641 0 +4642 0 +4643 0 +4644 0 +4645 0 +4646 0 +4647 0 +4648 0 +4649 0 +4650 0 +4651 0 +4652 1 +4653 0 +4654 0 +4655 0 +4656 0 +4657 0 +4658 0 +4659 0 +4660 0 +4661 1 +4662 0 +4663 0 +4664 0 +4665 1 +4666 0 +4667 0 +4668 0 +4669 0 +4670 0 +4671 0 +4672 1 +4673 0 +4674 0 +4675 0 +4676 0 +4677 0 +4678 1 +4679 0 +4680 0 +4681 0 +4682 0 +4683 0 +4684 0 +4685 0 +4686 1 +4687 0 +4688 0 +4689 0 +4690 0 +4691 0 +4692 0 +4693 0 +4694 1 +4695 0 +4696 0 +4697 0 +4698 0 +4699 0 +4700 0 +4701 0 +4702 1 +4703 0 +4704 0 +4705 0 +4706 0 +4707 0 +4708 0 +4709 1 +4710 0 +4711 0 +4712 0 +4713 0 +4714 0 +4715 0 +4716 0 +4717 1 +4718 0 +4719 0 +4720 0 +4721 0 +4722 0 +4723 0 +4724 0 +4725 1 +4726 0 +4727 0 +4728 0 +4729 0 +4730 0 +4731 0 +4732 0 +4733 0 +4734 1 +4735 0 +4736 0 +4737 0 +4738 0 +4739 0 +4740 0 +4741 0 +4742 0 +4743 0 +4744 1 +4745 0 +4746 0 +4747 0 +4748 0 +4749 0 +4750 0 +4751 0 +4752 1 +4753 0 +4754 0 +4755 0 +4756 0 +4757 0 +4758 0 +4759 0 +4760 1 +4761 0 +4762 0 +4763 0 +4764 0 +4765 0 +4766 0 +4767 0 +4768 0 +4769 1 +4770 0 +4771 0 +4772 0 +4773 0 +4774 0 +4775 0 +4776 0 +4777 0 +4778 1 +4779 0 +4780 0 +4781 0 +4782 0 +4783 0 +4784 0 +4785 0 +4786 1 +4787 0 +4788 0 +4789 0 +4790 0 +4791 0 +4792 0 +4793 0 +4794 0 +4795 0 +4796 1 +4797 0 +4798 0 +4799 0 +4800 0 +4801 0 +4802 0 +4803 0 +4804 1 +4805 0 +4806 0 +4807 0 +4808 0 +4809 0 +4810 0 +4811 0 +4812 0 +4813 1 +4814 0 +4815 0 +4816 0 +4817 0 +4818 0 +4819 0 +4820 0 +4821 0 +4822 1 +4823 0 +4824 0 +4825 0 +4826 0 +4827 0 +4828 0 +4829 0 +4830 0 +4831 1 +4832 0 +4833 0 +4834 0 +4835 0 +4836 0 +4837 0 +4838 0 +4839 0 +4840 0 +4841 0 +4842 0 +4843 0 +4844 0 +4845 0 +4846 0 +4847 0 +4848 0 +4849 0 +4850 0 +4851 0 +4852 0 +4853 0 +4854 0 +4855 0 +4856 0 +4857 0 +4858 0 +4859 0 +4860 0 +4861 0 +4862 0 +4863 0 +4864 0 +4865 1 +4866 0 +4867 0 +4868 0 +4869 0 +4870 0 +4871 0 +4872 1 +4873 0 +4874 0 +4875 0 +4876 0 +4877 0 +4878 0 +4879 0 +4880 1 +4881 0 +4882 0 +4883 0 +4884 0 +4885 0 +4886 0 +4887 0 +4888 0 +4889 0 +4890 1 +4891 0 +4892 0 +4893 0 +4894 0 +4895 0 +4896 0 +4897 0 +4898 1 +4899 0 +4900 0 +4901 0 +4902 0 +4903 0 +4904 0 +4905 1 +4906 0 +4907 0 +4908 0 +4909 0 +4910 0 +4911 0 +4912 0 +4913 1 +4914 0 +4915 0 +4916 0 +4917 0 +4918 0 +4919 0 +4920 0 +4921 0 +4922 0 +4923 1 +4924 0 +4925 0 +4926 0 +4927 0 +4928 0 +4929 0 +4930 0 +4931 0 +4932 0 +4933 1 +4934 0 +4935 0 +4936 0 +4937 0 +4938 0 +4939 0 +4940 0 +4941 0 +4942 0 +4943 0 +4944 0 +4945 0 +4946 0 +4947 0 +4948 1 +4949 0 +4950 0 +4951 0 +4952 0 +4953 0 +4954 0 +4955 0 +4956 1 +4957 0 +4958 0 +4959 0 +4960 0 +4961 0 +4962 0 +4963 0 +4964 1 +4965 0 +4966 0 +4967 0 +4968 0 +4969 0 +4970 0 +4971 0 +4972 1 +4973 0 +4974 0 +4975 0 +4976 0 +4977 0 +4978 0 +4979 1 +4980 0 +4981 0 +4982 0 +4983 0 +4984 0 +4985 0 +4986 0 +4987 1 +4988 0 +4989 0 +4990 0 +4991 0 +4992 0 +4993 0 +4994 1 +4995 0 +4996 0 +4997 0 +4998 0 +4999 0 +5000 0 +5001 0 +5002 0 +5003 1 +5004 0 +5005 0 +5006 0 +5007 0 +5008 0 +5009 0 +5010 0 +5011 0 +5012 1 +5013 0 +5014 0 +5015 0 +5016 0 +5017 0 +5018 0 +5019 0 +5020 1 +5021 0 +5022 0 +5023 0 +5024 0 +5025 0 +5026 0 +5027 0 +5028 0 +5029 1 +5030 0 +5031 0 +5032 0 +5033 0 +5034 0 +5035 0 +5036 0 +5037 1 +5038 0 +5039 0 +5040 0 +5041 0 +5042 0 +5043 0 +5044 0 +5045 1 +5046 0 +5047 0 +5048 0 +5049 0 +5050 0 +5051 0 +5052 0 +5053 1 +5054 0 +5055 0 +5056 0 +5057 0 +5058 0 +5059 0 +5060 0 +5061 0 +5062 1 +5063 0 +5064 0 +5065 0 +5066 0 +5067 0 +5068 0 +5069 0 +5070 0 +5071 0 +5072 0 +5073 0 +5074 0 +5075 0 +5076 0 +5077 0 +5078 0 +5079 1 +5080 0 +5081 0 +5082 0 +5083 0 +5084 0 +5085 0 +5086 1 +5087 0 +5088 0 +5089 0 +5090 0 +5091 0 +5092 0 +5093 0 +5094 1 +5095 0 +5096 0 +5097 0 +5098 0 +5099 0 +5100 0 +5101 0 +5102 0 +5103 1 +5104 0 +5105 0 +5106 0 +5107 0 +5108 0 +5109 0 +5110 1 +5111 0 +5112 0 +5113 0 +5114 0 +5115 0 +5116 0 +5117 0 +5118 1 +5119 0 +5120 0 +5121 0 +5122 0 +5123 0 +5124 0 +5125 0 +5126 0 +5127 1 +5128 0 +5129 0 +5130 0 +5131 0 +5132 0 +5133 0 +5134 1 +5135 0 +5136 0 +5137 0 +5138 0 +5139 0 +5140 0 +5141 1 +5142 0 +5143 0 +5144 0 +5145 0 +5146 0 +5147 0 +5148 0 +5149 1 +5150 0 +5151 0 +5152 0 +5153 0 +5154 0 +5155 0 +5156 0 +5157 0 +5158 1 +5159 0 +5160 0 +5161 0 +5162 0 +5163 0 +5164 0 +5165 0 +5166 0 +5167 1 +5168 0 +5169 0 +5170 0 +5171 0 +5172 0 +5173 0 +5174 0 +5175 1 +5176 0 +5177 0 +5178 0 +5179 0 +5180 0 +5181 0 +5182 1 +5183 0 +5184 0 +5185 0 +5186 0 +5187 0 +5188 0 +5189 0 +5190 1 +5191 0 +5192 0 +5193 0 +5194 0 +5195 0 +5196 0 +5197 0 +5198 0 +5199 1 +5200 0 +5201 0 +5202 0 +5203 0 +5204 0 +5205 0 +5206 0 +5207 0 +5208 1 +5209 0 +5210 0 +5211 0 +5212 0 +5213 0 +5214 0 +5215 0 +5216 0 +5217 0 +5218 1 +5219 0 +5220 0 +5221 0 +5222 0 +5223 0 +5224 0 +5225 0 +5226 1 +5227 0 +5228 0 +5229 0 +5230 0 +5231 0 +5232 0 +5233 0 +5234 1 +5235 0 +5236 0 +5237 0 +5238 0 +5239 0 +5240 0 +5241 0 +5242 1 +5243 0 +5244 0 +5245 0 +5246 0 +5247 0 +5248 0 +5249 0 +5250 0 +5251 1 +5252 0 +5253 0 +5254 0 +5255 0 +5256 0 +5257 0 +5258 0 +5259 0 +5260 0 +5261 0 +5262 0 +5263 0 +5264 0 +5265 0 +5266 0 +5267 0 +5268 1 +5269 0 +5270 0 +5271 0 +5272 0 +5273 0 +5274 0 +5275 0 +5276 1 +5277 0 +5278 0 +5279 0 +5280 0 +5281 0 +5282 0 +5283 1 +5284 0 +5285 0 +5286 0 +5287 0 +5288 0 +5289 0 +5290 0 +5291 0 +5292 0 +5293 1 +5294 0 +5295 0 +5296 0 +5297 0 +5298 0 +5299 0 +5300 0 +5301 1 +5302 0 +5303 0 +5304 0 +5305 0 +5306 0 +5307 0 +5308 0 +5309 0 +5310 1 +5311 0 +5312 0 +5313 0 +5314 0 +5315 0 +5316 0 +5317 0 +5318 1 +5319 0 +5320 0 +5321 0 +5322 0 +5323 0 +5324 0 +5325 1 +5326 0 +5327 0 +5328 0 +5329 0 +5330 0 +5331 0 +5332 0 +5333 0 +5334 0 +5335 0 +5336 0 +5337 0 +5338 0 +5339 0 +5340 0 +5341 0 +5342 1 +5343 0 +5344 0 +5345 0 +5346 0 +5347 0 +5348 0 +5349 1 +5350 0 +5351 0 +5352 0 +5353 0 +5354 0 +5355 0 +5356 0 +5357 0 +5358 1 +5359 0 +5360 0 +5361 0 +5362 0 +5363 0 +5364 0 +5365 0 +5366 1 +5367 0 +5368 0 +5369 0 +5370 0 +5371 0 +5372 0 +5373 1 +5374 0 +5375 0 +5376 0 +5377 0 +5378 0 +5379 0 +5380 0 +5381 1 +5382 0 +5383 0 +5384 0 +5385 0 +5386 0 +5387 0 +5388 0 +5389 0 +5390 1 +5391 0 +5392 0 +5393 0 +5394 0 +5395 0 +5396 0 +5397 0 +5398 1 +5399 0 +5400 0 +5401 0 +5402 0 +5403 0 +5404 0 +5405 0 +5406 1 +5407 0 +5408 0 +5409 0 +5410 0 +5411 0 +5412 0 +5413 0 +5414 1 +5415 0 +5416 0 +5417 0 +5418 0 +5419 0 +5420 0 +5421 0 +5422 1 +5423 0 +5424 0 +5425 0 +5426 0 +5427 0 +5428 0 +5429 0 +5430 0 +5431 0 +5432 0 +5433 0 +5434 0 +5435 0 +5436 0 +5437 0 +5438 1 +5439 0 +5440 0 +5441 0 +5442 0 +5443 0 +5444 0 +5445 0 +5446 0 +5447 1 +5448 0 +5449 0 +5450 0 +5451 0 +5452 0 +5453 0 +5454 0 +5455 0 +5456 1 +5457 0 +5458 0 +5459 0 +5460 0 +5461 0 +5462 0 +5463 0 +5464 1 +5465 0 +5466 0 +5467 0 +5468 0 +5469 0 +5470 0 +5471 0 +5472 1 +5473 0 +5474 0 +5475 0 +5476 0 +5477 0 +5478 0 +5479 0 +5480 0 +5481 1 +5482 0 +5483 0 +5484 0 +5485 0 +5486 0 +5487 0 +5488 0 +5489 1 +5490 0 +5491 0 +5492 0 +5493 0 +5494 0 +5495 0 +5496 0 +5497 0 +5498 1 +5499 0 +5500 0 +5501 0 +5502 0 +5503 0 +5504 0 +5505 0 +5506 1 +5507 0 +5508 0 +5509 0 +5510 0 +5511 0 +5512 0 +5513 0 +5514 1 +5515 0 +5516 0 +5517 0 +5518 0 +5519 0 +5520 0 +5521 0 +5522 0 +5523 1 +5524 0 +5525 0 +5526 0 +5527 0 +5528 0 +5529 0 +5530 0 +5531 1 +5532 0 +5533 0 +5534 0 +5535 0 +5536 0 +5537 0 +5538 0 +5539 0 +5540 1 +5541 0 +5542 0 +5543 0 +5544 0 +5545 0 +5546 0 +5547 0 +5548 0 +5549 1 +5550 0 +5551 0 +5552 0 +5553 0 +5554 0 +5555 0 +5556 0 +5557 0 +5558 0 +5559 0 +5560 0 +5561 0 +5562 0 +5563 0 +5564 0 +5565 1 +5566 0 +5567 0 +5568 0 +5569 0 +5570 0 +5571 1 +5572 0 +5573 0 +5574 0 +5575 0 +5576 0 +5577 0 +5578 0 +5579 1 +5580 0 +5581 0 +5582 0 +5583 0 +5584 0 +5585 0 +5586 0 +5587 0 +5588 1 +5589 0 +5590 0 +5591 0 +5592 0 +5593 0 +5594 0 +5595 0 +5596 1 +5597 0 +5598 0 +5599 0 +5600 0 +5601 0 +5602 0 +5603 0 +5604 0 +5605 0 +5606 1 +5607 0 +5608 0 +5609 0 +5610 0 +5611 0 +5612 0 +5613 0 +5614 1 +5615 0 +5616 0 +5617 0 +5618 0 +5619 0 +5620 0 +5621 0 +5622 1 +5623 0 +5624 0 +5625 0 +5626 0 +5627 0 +5628 0 +5629 0 +5630 0 +5631 0 +5632 0 +5633 0 +5634 0 +5635 0 +5636 0 +5637 0 +5638 1 +5639 0 +5640 0 +5641 0 +5642 0 +5643 0 +5644 0 +5645 0 +5646 0 +5647 1 +5648 0 +5649 0 +5650 0 +5651 0 +5652 0 +5653 0 +5654 1 +5655 0 +5656 0 +5657 0 +5658 0 +5659 0 +5660 0 +5661 0 +5662 1 +5663 0 +5664 0 +5665 0 +5666 0 +5667 0 +5668 0 +5669 0 +5670 1 +5671 0 +5672 0 +5673 0 +5674 0 +5675 0 +5676 0 +5677 0 +5678 0 +5679 1 +5680 2 +5681 1 +5682 0 +5683 0 +5684 0 +5685 0 +5686 0 +5687 1 +5688 0 +5689 0 +5690 0 +5691 0 +5692 1 +5693 0 +5694 0 +5695 0 +5696 0 +5697 1 +5698 0 +5699 0 +5700 0 +5701 0 +5702 0 +5703 0 +5704 0 +5705 1 +5706 0 +5707 0 +5708 0 +5709 0 +5710 0 +5711 1 +5712 0 +5713 0 +5714 0 +5715 0 +5716 0 +5717 0 +5718 0 +5719 0 +5720 0 +5721 0 +5722 0 +5723 0 +5724 0 +5725 0 +5726 1 +5727 0 +5728 0 +5729 0 +5730 0 +5731 0 +5732 0 +5733 0 +5734 1 +5735 0 +5736 0 +5737 0 +5738 0 +5739 0 +5740 0 +5741 0 +5742 1 +5743 0 +5744 0 +5745 0 +5746 0 +5747 0 +5748 0 +5749 0 +5750 0 +5751 1 +5752 0 +5753 0 +5754 0 +5755 0 +5756 0 +5757 0 +5758 0 +5759 1 +5760 0 +5761 0 +5762 0 +5763 0 +5764 0 +5765 0 +5766 1 +5767 0 +5768 0 +5769 0 +5770 0 +5771 0 +5772 0 +5773 0 +5774 1 +5775 0 +5776 0 +5777 0 +5778 0 +5779 0 +5780 0 +5781 0 +5782 1 +5783 0 +5784 0 +5785 0 +5786 0 +5787 0 +5788 0 +5789 0 +5790 0 +5791 1 +5792 0 +5793 0 +5794 0 +5795 0 +5796 0 +5797 0 +5798 0 +5799 0 +5800 1 +5801 0 +5802 0 +5803 0 +5804 0 +5805 0 +5806 0 +5807 0 +5808 0 +5809 1 +5810 0 +5811 0 +5812 0 +5813 0 +5814 0 +5815 0 +5816 1 +5817 0 +5818 0 +5819 0 +5820 0 +5821 0 +5822 0 +5823 0 +5824 0 +5825 1 +5826 0 +5827 0 +5828 0 +5829 0 +5830 0 +5831 0 +5832 0 +5833 0 +5834 1 +5835 0 +5836 0 +5837 0 +5838 0 +5839 0 +5840 0 +5841 0 +5842 1 +5843 0 +5844 0 +5845 0 +5846 0 +5847 0 +5848 0 +5849 0 +5850 1 +5851 0 +5852 0 +5853 0 +5854 0 +5855 0 +5856 0 +5857 0 +5858 1 +5859 0 +5860 0 +5861 0 +5862 0 +5863 0 +5864 0 +5865 0 +5866 0 +5867 1 +5868 0 +5869 0 +5870 0 +5871 0 +5872 0 +5873 0 +5874 0 +5875 1 +5876 0 +5877 0 +5878 0 +5879 0 +5880 0 +5881 0 +5882 0 +5883 0 +5884 1 +5885 0 +5886 0 +5887 0 +5888 0 +5889 0 +5890 0 +5891 1 +5892 0 +5893 0 +5894 0 +5895 0 +5896 0 +5897 0 +5898 0 +5899 0 +5900 1 +5901 0 +5902 0 +5903 0 +5904 0 +5905 0 +5906 0 +5907 0 +5908 0 +5909 1 +5910 0 +5911 0 +5912 0 +5913 0 +5914 0 +5915 0 +5916 0 +5917 1 +5918 0 +5919 0 +5920 0 +5921 0 +5922 0 +5923 0 +5924 0 +5925 0 +5926 1 +5927 0 +5928 0 +5929 0 +5930 0 +5931 0 +5932 0 +5933 0 +5934 1 +5935 0 +5936 0 +5937 0 +5938 0 +5939 0 +5940 0 +5941 0 +5942 0 +5943 0 +5944 1 +5945 0 +5946 0 +5947 0 +5948 0 +5949 0 +5950 0 +5951 0 +5952 0 +5953 0 +5954 0 +5955 0 +5956 0 +5957 0 +5958 0 +5959 0 +5960 0 +5961 0 +5962 0 +5963 0 +5964 0 +5965 0 +5966 0 +5967 0 +5968 0 +5969 0 +5970 1 +5971 0 +5972 0 +5973 0 +5974 0 +5975 0 +5976 0 +5977 0 +5978 1 +5979 0 +5980 0 +5981 0 +5982 0 +5983 0 +5984 0 +5985 0 +5986 0 +5987 1 +5988 0 +5989 0 +5990 0 +5991 0 +5992 0 +5993 0 +5994 0 +5995 0 +5996 1 +5997 0 +5998 0 +5999 0 +6000 0 +6001 0 +6002 0 +6003 0 +6004 0 +6005 0 +6006 1 +6007 0 +6008 0 +6009 0 +6010 0 +6011 0 +6012 0 +6013 0 +6014 1 +6015 0 +6016 0 +6017 0 +6018 0 +6019 0 +6020 0 +6021 0 +6022 0 +6023 1 +6024 0 +6025 0 +6026 0 +6027 0 +6028 0 +6029 0 +6030 0 +6031 1 +6032 0 +6033 0 +6034 0 +6035 0 +6036 0 +6037 0 +6038 1 +6039 0 +6040 0 +6041 0 +6042 0 +6043 0 +6044 0 +6045 0 +6046 0 +6047 0 +6048 1 +6049 0 +6050 0 +6051 0 +6052 0 +6053 0 +6054 0 +6055 1 +6056 0 +6057 0 +6058 0 +6059 0 +6060 0 +6061 1 +6062 0 +6063 0 +6064 0 +6065 0 +6066 0 +6067 0 +6068 1 +6069 0 +6070 0 +6071 0 +6072 0 +6073 0 +6074 0 +6075 0 +6076 1 +6077 0 +6078 0 +6079 0 +6080 0 +6081 0 +6082 0 +6083 0 +6084 0 +6085 1 +6086 0 +6087 0 +6088 0 +6089 0 +6090 0 +6091 0 +6092 0 +6093 0 +6094 0 +6095 1 +6096 0 +6097 0 +6098 0 +6099 0 +6100 0 +6101 0 +6102 0 +6103 0 +6104 1 +6105 0 +6106 0 +6107 0 +6108 0 +6109 0 +6110 0 +6111 0 +6112 1 +6113 0 +6114 0 +6115 0 +6116 0 +6117 0 +6118 0 +6119 0 +6120 0 +6121 0 +6122 0 +6123 0 +6124 0 +6125 1 +6126 0 +6127 0 +6128 0 +6129 0 +6130 0 +6131 0 +6132 0 +6133 0 +6134 0 +6135 0 +6136 0 +6137 0 +6138 0 +6139 0 +6140 0 +6141 0 +6142 1 +6143 0 +6144 0 +6145 0 +6146 0 +6147 0 +6148 0 +6149 0 +6150 1 +6151 0 +6152 0 +6153 0 +6154 0 +6155 0 +6156 0 +6157 0 +6158 0 +6159 1 +6160 0 +6161 0 +6162 0 +6163 0 +6164 0 +6165 0 +6166 0 +6167 1 +6168 0 +6169 0 +6170 0 +6171 0 +6172 0 +6173 0 +6174 0 +6175 1 +6176 0 +6177 0 +6178 0 +6179 0 +6180 0 +6181 0 +6182 0 +6183 1 +6184 0 +6185 0 +6186 0 +6187 0 +6188 0 +6189 0 +6190 0 +6191 0 +6192 1 +6193 0 +6194 0 +6195 0 +6196 0 +6197 0 +6198 0 +6199 0 +6200 0 +6201 1 +6202 0 +6203 0 +6204 0 +6205 0 +6206 0 +6207 0 +6208 0 +6209 0 +6210 1 +6211 0 +6212 0 +6213 0 +6214 0 +6215 0 +6216 0 +6217 1 +6218 0 +6219 0 +6220 0 +6221 0 +6222 0 +6223 0 +6224 0 +6225 1 +6226 0 +6227 0 +6228 0 +6229 0 +6230 0 +6231 0 +6232 0 +6233 0 +6234 1 +6235 0 +6236 0 +6237 0 +6238 0 +6239 0 +6240 0 +6241 1 +6242 0 +6243 0 +6244 0 +6245 0 +6246 0 +6247 0 +6248 0 +6249 0 +6250 1 +6251 0 +6252 0 +6253 0 +6254 0 +6255 0 +6256 0 +6257 0 +6258 1 +6259 0 +6260 0 +6261 0 +6262 0 +6263 0 +6264 0 +6265 0 +6266 0 +6267 0 +6268 1 +6269 0 +6270 0 +6271 0 +6272 0 +6273 0 +6274 0 +6275 0 +6276 0 +6277 1 +6278 0 +6279 0 +6280 0 +6281 0 +6282 0 +6283 0 +6284 0 +6285 1 +6286 0 +6287 0 +6288 0 +6289 0 +6290 0 +6291 0 +6292 1 +6293 0 +6294 0 +6295 0 +6296 0 +6297 0 +6298 0 +6299 1 +6300 0 +6301 0 +6302 0 +6303 0 +6304 0 +6305 0 +6306 0 +6307 1 +6308 0 +6309 0 +6310 0 +6311 0 +6312 0 +6313 0 +6314 0 +6315 1 +6316 0 +6317 0 +6318 0 +6319 0 +6320 0 +6321 0 +6322 0 +6323 0 +6324 1 +6325 0 +6326 0 +6327 0 +6328 0 +6329 0 +6330 0 +6331 0 +6332 1 +6333 0 +6334 0 +6335 0 +6336 0 +6337 0 +6338 0 +6339 0 +6340 0 +6341 1 +6342 0 +6343 0 +6344 0 +6345 0 +6346 0 +6347 0 +6348 0 +6349 0 +6350 1 +6351 0 +6352 0 +6353 0 +6354 0 +6355 0 +6356 0 +6357 0 +6358 1 +6359 0 +6360 0 +6361 0 +6362 0 +6363 0 +6364 0 +6365 0 +6366 1 +6367 0 +6368 0 +6369 0 +6370 0 +6371 0 +6372 0 +6373 0 +6374 0 +6375 1 +6376 0 +6377 0 +6378 0 +6379 0 +6380 0 +6381 0 +6382 0 +6383 1 +6384 0 +6385 0 +6386 0 +6387 0 +6388 0 +6389 0 +6390 0 +6391 4 +6392 0 +6393 1 +6394 0 +6395 0 +6396 0 +6397 1 +6398 0 +6399 0 +6400 0 +6401 0 +6402 1 +6403 0 +6404 0 +6405 0 +6406 0 +6407 1 +6408 0 +6409 0 +6410 0 +6411 0 +6412 1 +6413 0 +6414 0 +6415 0 +6416 0 +6417 0 +6418 1 +6419 0 +6420 0 +6421 0 +6422 0 +6423 0 +6424 0 +6425 1 +6426 0 +6427 0 +6428 0 +6429 0 +6430 0 +6431 0 +6432 0 +6433 0 +6434 1 +6435 0 +6436 0 +6437 0 +6438 0 +6439 0 +6440 0 +6441 0 +6442 0 +6443 1 +6444 0 +6445 0 +6446 0 +6447 0 +6448 0 +6449 0 +6450 0 +6451 0 +6452 1 +6453 0 +6454 0 +6455 0 +6456 0 +6457 0 +6458 0 +6459 0 +6460 0 +6461 0 +6462 0 +6463 1 +6464 0 +6465 0 +6466 0 +6467 0 +6468 0 +6469 0 +6470 0 +6471 0 +6472 1 +6473 0 +6474 0 +6475 0 +6476 0 +6477 0 +6478 0 +6479 0 +6480 0 +6481 0 +6482 1 +6483 0 +6484 0 +6485 0 +6486 0 +6487 0 +6488 0 +6489 0 +6490 0 +6491 0 +6492 1 +6493 0 +6494 0 +6495 0 +6496 0 +6497 0 +6498 0 +6499 0 +6500 0 +6501 0 +6502 0 +6503 0 +6504 0 +6505 0 +6506 0 +6507 0 +6508 0 +6509 0 +6510 0 +6511 0 +6512 1 +6513 0 +6514 0 +6515 0 +6516 0 +6517 0 +6518 0 +6519 0 +6520 0 +6521 1 +6522 0 +6523 0 +6524 0 +6525 0 +6526 0 +6527 0 +6528 0 +6529 0 +6530 0 +6531 1 +6532 0 +6533 0 +6534 0 +6535 0 +6536 0 +6537 0 +6538 0 +6539 0 +6540 1 +6541 0 +6542 0 +6543 0 +6544 0 +6545 0 +6546 0 +6547 0 +6548 0 +6549 0 +6550 1 +6551 0 +6552 0 +6553 0 +6554 0 +6555 0 +6556 0 +6557 0 +6558 0 +6559 0 +6560 1 +6561 0 +6562 0 +6563 0 +6564 0 +6565 0 +6566 0 +6567 0 +6568 0 +6569 1 +6570 0 +6571 0 +6572 0 +6573 0 +6574 0 +6575 0 +6576 0 +6577 1 +6578 0 +6579 0 +6580 0 +6581 0 +6582 0 +6583 0 +6584 0 +6585 0 +6586 1 +6587 0 +6588 0 +6589 0 +6590 0 +6591 0 +6592 0 +6593 0 +6594 0 +6595 1 +6596 0 +6597 0 +6598 0 +6599 0 +6600 0 +6601 0 +6602 0 +6603 0 +6604 1 +6605 0 +6606 0 +6607 0 +6608 0 +6609 0 +6610 0 +6611 0 +6612 0 +6613 1 +6614 0 +6615 0 +6616 0 +6617 0 +6618 0 +6619 0 +6620 0 +6621 0 +6622 1 +6623 0 +6624 0 +6625 0 +6626 0 +6627 0 +6628 0 +6629 0 +6630 0 +6631 1 +6632 0 +6633 0 +6634 0 +6635 0 +6636 0 +6637 0 +6638 0 +6639 0 +6640 1 +6641 0 +6642 0 +6643 0 +6644 0 +6645 0 +6646 0 +6647 0 +6648 0 +6649 0 +6650 1 +6651 0 +6652 0 +6653 0 +6654 0 +6655 0 +6656 0 +6657 0 +6658 0 +6659 0 +6660 1 +6661 0 +6662 0 +6663 0 +6664 0 +6665 0 +6666 0 +6667 0 +6668 0 +6669 1 +6670 0 +6671 0 +6672 0 +6673 0 +6674 0 +6675 0 +6676 0 +6677 0 +6678 0 +6679 1 +6680 0 +6681 0 +6682 0 +6683 0 +6684 0 +6685 0 +6686 0 +6687 0 +6688 1 +6689 0 +6690 0 +6691 0 +6692 0 +6693 0 +6694 0 +6695 0 +6696 0 +6697 0 +6698 1 +6699 0 +6700 0 +6701 0 +6702 0 +6703 0 +6704 0 +6705 0 +6706 1 +6707 0 +6708 0 +6709 0 +6710 0 +6711 0 +6712 0 +6713 0 +6714 0 +6715 0 +6716 1 +6717 0 +6718 0 +6719 0 +6720 0 +6721 0 +6722 0 +6723 0 +6724 0 +6725 0 +6726 1 +6727 0 +6728 0 +6729 0 +6730 0 +6731 0 +6732 0 +6733 0 +6734 0 +6735 0 +6736 0 +6737 1 +6738 0 +6739 0 +6740 0 +6741 0 +6742 0 +6743 0 +6744 0 +6745 0 +6746 1 +6747 0 +6748 0 +6749 0 +6750 0 +6751 0 +6752 0 +6753 0 +6754 0 +6755 0 +6756 1 +6757 0 +6758 0 +6759 0 +6760 0 +6761 0 +6762 0 +6763 0 +6764 0 +6765 0 +6766 1 +6767 0 +6768 0 +6769 0 +6770 0 +6771 0 +6772 0 +6773 0 +6774 0 +6775 1 +6776 0 +6777 0 +6778 0 +6779 0 +6780 0 +6781 0 +6782 0 +6783 0 +6784 1 +6785 0 +6786 0 +6787 0 +6788 0 +6789 0 +6790 0 +6791 0 +6792 0 +6793 0 +6794 1 +6795 0 +6796 0 +6797 0 +6798 0 +6799 0 +6800 0 +6801 0 +6802 0 +6803 1 +6804 0 +6805 0 +6806 0 +6807 0 +6808 0 +6809 0 +6810 0 +6811 0 +6812 0 +6813 1 +6814 0 +6815 0 +6816 0 +6817 0 +6818 0 +6819 0 +6820 0 +6821 0 +6822 0 +6823 0 +6824 1 +6825 0 +6826 0 +6827 0 +6828 0 +6829 0 +6830 0 +6831 0 +6832 1 +6833 0 +6834 0 +6835 0 +6836 0 +6837 0 +6838 0 +6839 0 +6840 0 +6841 0 +6842 1 +6843 0 +6844 0 +6845 0 +6846 0 +6847 0 +6848 0 +6849 0 +6850 0 +6851 1 +6852 0 +6853 0 +6854 0 +6855 0 +6856 0 +6857 0 +6858 0 +6859 0 +6860 0 +6861 0 +6862 1 +6863 0 +6864 0 +6865 0 +6866 0 +6867 0 +6868 0 +6869 0 +6870 0 +6871 1 +6872 0 +6873 0 +6874 0 +6875 0 +6876 0 +6877 0 +6878 0 +6879 1 +6880 0 +6881 0 +6882 0 +6883 0 +6884 0 +6885 0 +6886 1 +6887 0 +6888 0 +6889 0 +6890 0 +6891 0 +6892 0 +6893 0 +6894 0 +6895 1 +6896 0 +6897 0 +6898 0 +6899 0 +6900 0 +6901 0 +6902 0 +6903 0 +6904 0 +6905 0 +6906 0 +6907 0 +6908 0 +6909 0 +6910 0 +6911 0 +6912 0 +6913 0 +6914 1 +6915 0 +6916 0 +6917 0 +6918 0 +6919 0 +6920 0 +6921 0 +6922 0 +6923 1 +6924 0 +6925 0 +6926 0 +6927 0 +6928 0 +6929 0 +6930 0 +6931 0 +6932 0 +6933 0 +6934 1 +6935 0 +6936 0 +6937 0 +6938 0 +6939 0 +6940 0 +6941 0 +6942 0 +6943 0 +6944 1 +6945 0 +6946 0 +6947 0 +6948 0 +6949 0 +6950 0 +6951 0 +6952 0 +6953 0 +6954 1 +6955 0 +6956 0 +6957 0 +6958 0 +6959 0 +6960 0 +6961 0 +6962 0 +6963 0 +6964 1 +6965 0 +6966 0 +6967 0 +6968 0 +6969 0 +6970 0 +6971 0 +6972 0 +6973 0 +6974 1 +6975 0 +6976 0 +6977 0 +6978 0 +6979 0 +6980 0 +6981 0 +6982 0 +6983 1 +6984 0 +6985 0 +6986 0 +6987 0 +6988 0 +6989 0 +6990 0 +6991 0 +6992 1 +6993 0 +6994 0 +6995 0 +6996 0 +6997 0 +6998 0 +6999 0 +7000 0 +7001 1 +7002 0 +7003 0 +7004 0 +7005 0 +7006 0 +7007 0 +7008 0 +7009 0 +7010 1 +7011 0 +7012 0 +7013 0 +7014 0 +7015 0 +7016 0 +7017 0 +7018 0 +7019 0 +7020 1 +7021 0 +7022 0 +7023 0 +7024 0 +7025 0 +7026 0 +7027 0 +7028 0 +7029 0 +7030 1 +7031 0 +7032 0 +7033 0 +7034 0 +7035 0 +7036 0 +7037 0 +7038 0 +7039 1 +7040 0 +7041 0 +7042 0 +7043 0 +7044 0 +7045 0 +7046 0 +7047 0 +7048 1 +7049 0 +7050 0 +7051 0 +7052 0 +7053 0 +7054 0 +7055 0 +7056 0 +7057 0 +7058 0 +7059 1 +7060 0 +7061 0 +7062 0 +7063 0 +7064 0 +7065 0 +7066 0 +7067 0 +7068 0 +7069 1 +7070 0 +7071 0 +7072 0 +7073 0 +7074 0 +7075 0 +7076 0 +7077 0 +7078 0 +7079 1 +7080 0 +7081 0 +7082 0 +7083 0 +7084 0 +7085 0 +7086 0 +7087 1 +7088 0 +7089 0 +7090 0 +7091 0 +7092 0 +7093 0 +7094 0 +7095 0 +7096 0 +7097 1 +7098 0 +7099 0 +7100 0 +7101 0 +7102 0 +7103 0 +7104 0 +7105 1 +7106 0 +7107 0 +7108 0 +7109 0 +7110 0 +7111 0 +7112 0 +7113 0 +7114 1 +7115 0 +7116 0 +7117 0 +7118 0 +7119 0 +7120 0 +7121 0 +7122 0 +7123 0 +7124 1 +7125 0 +7126 0 +7127 0 +7128 0 +7129 0 +7130 0 +7131 0 +7132 0 +7133 0 +7134 1 +7135 0 +7136 0 +7137 0 +7138 0 +7139 0 +7140 0 +7141 0 +7142 0 +7143 1 +7144 0 +7145 0 +7146 0 +7147 0 +7148 0 +7149 0 +7150 0 +7151 0 +7152 1 +7153 0 +7154 0 +7155 0 +7156 0 +7157 0 +7158 0 +7159 0 +7160 0 +7161 0 +7162 1 +7163 0 +7164 0 +7165 0 +7166 0 +7167 0 +7168 0 +7169 0 +7170 0 +7171 0 +7172 1 +7173 0 +7174 0 +7175 0 +7176 0 +7177 0 +7178 0 +7179 0 +7180 0 +7181 0 +7182 1 +7183 0 +7184 0 +7185 0 +7186 0 +7187 0 +7188 0 +7189 0 +7190 0 +7191 0 +7192 0 +7193 1 +7194 0 +7195 0 +7196 0 +7197 0 +7198 0 +7199 0 +7200 0 +7201 0 +7202 0 +7203 1 +7204 0 +7205 0 +7206 0 +7207 0 +7208 0 +7209 0 +7210 0 +7211 0 +7212 0 +7213 0 +7214 0 +7215 0 +7216 0 +7217 0 +7218 0 +7219 0 +7220 0 +7221 0 +7222 1 +7223 0 +7224 0 +7225 0 +7226 0 +7227 0 +7228 0 +7229 0 +7230 0 +7231 0 +7232 1 +7233 0 +7234 0 +7235 0 +7236 0 +7237 0 +7238 0 +7239 0 +7240 0 +7241 0 +7242 0 +7243 1 +7244 0 +7245 0 +7246 0 +7247 0 +7248 0 +7249 0 +7250 0 +7251 0 +7252 0 +7253 1 +7254 0 +7255 0 +7256 0 +7257 0 +7258 0 +7259 0 +7260 0 +7261 0 +7262 0 +7263 0 +7264 1 +7265 0 +7266 0 +7267 0 +7268 0 +7269 0 +7270 0 +7271 0 +7272 0 +7273 0 +7274 1 +7275 0 +7276 0 +7277 0 +7278 0 +7279 0 +7280 0 +7281 0 +7282 0 +7283 0 +7284 0 +7285 1 +7286 0 +7287 0 +7288 0 +7289 0 +7290 0 +7291 0 +7292 0 +7293 0 +7294 0 +7295 0 +7296 0 +7297 0 +7298 0 +7299 0 +7300 0 +7301 0 +7302 0 +7303 0 +7304 1 +7305 0 +7306 0 +7307 0 +7308 0 +7309 0 +7310 0 +7311 0 +7312 0 +7313 0 +7314 0 +7315 1 +7316 0 +7317 0 +7318 0 +7319 0 +7320 0 +7321 0 +7322 0 +7323 0 +7324 1 +7325 0 +7326 0 +7327 0 +7328 0 +7329 0 +7330 0 +7331 0 +7332 0 +7333 1 +7334 0 +7335 0 +7336 0 +7337 0 +7338 0 +7339 0 +7340 0 +7341 0 +7342 1 +7343 0 +7344 0 +7345 0 +7346 0 +7347 0 +7348 0 +7349 0 +7350 0 +7351 0 +7352 1 +7353 0 +7354 0 +7355 0 +7356 0 +7357 0 +7358 0 +7359 0 +7360 0 +7361 0 +7362 0 +7363 1 +7364 0 +7365 0 +7366 0 +7367 0 +7368 0 +7369 0 +7370 0 +7371 0 +7372 1 +7373 0 +7374 0 +7375 0 +7376 0 +7377 0 +7378 0 +7379 0 +7380 0 +7381 0 +7382 1 +7383 0 +7384 0 +7385 0 +7386 0 +7387 0 +7388 0 +7389 0 +7390 0 +7391 1 +7392 0 +7393 0 +7394 0 +7395 0 +7396 0 +7397 0 +7398 0 +7399 0 +7400 0 +7401 1 +7402 0 +7403 0 +7404 0 +7405 0 +7406 0 +7407 0 +7408 0 +7409 0 +7410 0 +7411 0 +7412 1 +7413 0 +7414 0 +7415 0 +7416 0 +7417 0 +7418 0 +7419 0 +7420 0 +7421 0 +7422 1 +7423 0 +7424 0 +7425 0 +7426 0 +7427 0 +7428 0 +7429 0 +7430 0 +7431 0 +7432 1 +7433 0 +7434 0 +7435 0 +7436 0 +7437 0 +7438 0 +7439 0 +7440 0 +7441 1 +7442 0 +7443 0 +7444 0 +7445 0 +7446 0 +7447 0 +7448 0 +7449 1 +7450 0 +7451 0 +7452 0 +7453 0 +7454 0 +7455 0 +7456 0 +7457 0 +7458 0 +7459 0 +7460 1 +7461 0 +7462 0 +7463 0 +7464 0 +7465 0 +7466 0 +7467 0 +7468 0 +7469 1 +7470 0 +7471 0 +7472 0 +7473 0 +7474 0 +7475 0 +7476 0 +7477 0 +7478 1 +7479 0 +7480 0 +7481 0 +7482 0 +7483 0 +7484 0 +7485 0 +7486 0 +7487 1 +7488 0 +7489 0 +7490 0 +7491 0 +7492 0 +7493 0 +7494 0 +7495 0 +7496 0 +7497 1 +7498 0 +7499 0 +7500 0 +7501 0 +7502 0 +7503 0 +7504 0 +7505 0 +7506 0 +7507 0 +7508 1 +7509 0 +7510 0 +7511 0 +7512 0 +7513 0 +7514 0 +7515 0 +7516 0 +7517 0 +7518 1 +7519 0 +7520 0 +7521 0 +7522 0 +7523 0 +7524 0 +7525 0 +7526 0 +7527 0 +7528 0 +7529 0 +7530 0 +7531 0 +7532 0 +7533 0 +7534 0 +7535 0 +7536 0 +7537 0 +7538 0 +7539 1 +7540 0 +7541 0 +7542 0 +7543 0 +7544 0 +7545 0 +7546 0 +7547 0 +7548 0 +7549 2 +7550 0 +7551 0 +7552 0 +7553 0 +7554 0 +7555 0 +7556 0 +7557 1 +7558 0 +7559 0 +7560 0 +7561 0 +7562 0 +7563 0 +7564 0 +7565 0 +7566 0 +7567 0 +7568 1 +7569 0 +7570 0 +7571 0 +7572 0 +7573 0 +7574 0 +7575 0 +7576 0 +7577 0 +7578 0 +7579 0 +7580 0 +7581 0 +7582 0 +7583 0 +7584 0 +7585 0 +7586 0 +7587 0 +7588 1 +7589 0 +7590 0 +7591 0 +7592 0 +7593 0 +7594 0 +7595 0 +7596 0 +7597 0 +7598 0 +7599 1 +7600 0 +7601 0 +7602 0 +7603 0 +7604 0 +7605 0 +7606 0 +7607 0 +7608 0 +7609 0 +7610 1 +7611 0 +7612 0 +7613 0 +7614 0 +7615 0 +7616 0 +7617 0 +7618 0 +7619 0 +7620 0 +7621 1 +7622 0 +7623 0 +7624 0 +7625 0 +7626 0 +7627 1 +7628 0 +7629 0 +7630 0 +7631 0 +7632 0 +7633 0 +7634 1 +7635 0 +7636 0 +7637 0 +7638 0 +7639 0 +7640 0 +7641 1 +7642 0 +7643 0 +7644 0 +7645 0 +7646 0 +7647 0 +7648 0 +7649 1 +7650 0 +7651 0 +7652 0 +7653 0 +7654 0 +7655 0 +7656 0 +7657 0 +7658 0 +7659 0 +7660 1 +7661 0 +7662 0 +7663 0 +7664 0 +7665 0 +7666 0 +7667 0 +7668 0 +7669 0 +7670 1 +7671 0 +7672 0 +7673 0 +7674 0 +7675 0 +7676 0 +7677 0 +7678 0 +7679 0 +7680 0 +7681 1 +7682 0 +7683 0 +7684 0 +7685 0 +7686 0 +7687 0 +7688 0 +7689 0 +7690 0 +7691 1 +7692 0 +7693 0 +7694 0 +7695 0 +7696 0 +7697 0 +7698 0 +7699 0 +7700 0 +7701 0 +7702 1 +7703 0 +7704 0 +7705 0 +7706 0 +7707 0 +7708 0 +7709 0 +7710 0 +7711 0 +7712 1 +7713 0 +7714 0 +7715 0 +7716 0 +7717 0 +7718 0 +7719 0 +7720 0 +7721 0 +7722 1 +7723 0 +7724 0 +7725 0 +7726 0 +7727 0 +7728 0 +7729 0 +7730 0 +7731 0 +7732 1 +7733 0 +7734 0 +7735 0 +7736 0 +7737 0 +7738 0 +7739 0 +7740 0 +7741 0 +7742 1 +7743 0 +7744 0 +7745 0 +7746 0 +7747 0 +7748 0 +7749 0 +7750 0 +7751 0 +7752 1 +7753 0 +7754 0 +7755 0 +7756 0 +7757 0 +7758 0 +7759 0 +7760 0 +7761 1 +7762 0 +7763 0 +7764 0 +7765 0 +7766 0 +7767 0 +7768 0 +7769 0 +7770 1 +7771 0 +7772 0 +7773 0 +7774 0 +7775 0 +7776 0 +7777 0 +7778 0 +7779 1 +7780 0 +7781 0 +7782 0 +7783 0 +7784 0 +7785 0 +7786 0 +7787 0 +7788 0 +7789 1 +7790 0 +7791 0 +7792 0 +7793 0 +7794 0 +7795 0 +7796 0 +7797 0 +7798 0 +7799 1 +7800 0 +7801 0 +7802 0 +7803 0 +7804 0 +7805 0 +7806 0 +7807 0 +7808 0 +7809 0 +7810 1 +7811 0 +7812 0 +7813 0 +7814 0 +7815 0 +7816 0 +7817 0 +7818 0 +7819 1 +7820 0 +7821 0 +7822 0 +7823 0 +7824 0 +7825 0 +7826 0 +7827 0 +7828 1 +7829 0 +7830 0 +7831 0 +7832 0 +7833 0 +7834 0 +7835 0 +7836 0 +7837 0 +7838 0 +7839 1 +7840 0 +7841 0 +7842 0 +7843 0 +7844 0 +7845 0 +7846 0 +7847 0 +7848 0 +7849 1 +7850 0 +7851 0 +7852 0 +7853 0 +7854 0 +7855 0 +7856 0 +7857 0 +7858 1 +7859 0 +7860 0 +7861 0 +7862 0 +7863 0 +7864 0 +7865 0 +7866 0 +7867 0 +7868 1 +7869 0 +7870 0 +7871 0 +7872 0 +7873 0 +7874 0 +7875 0 +7876 0 +7877 0 +7878 0 +7879 0 +7880 0 +7881 0 +7882 0 +7883 0 +7884 0 +7885 0 +7886 0 +7887 1 +7888 0 +7889 0 +7890 0 +7891 0 +7892 0 +7893 0 +7894 0 +7895 0 +7896 0 +7897 0 +7898 1 +7899 0 +7900 0 +7901 0 +7902 0 +7903 0 +7904 0 +7905 0 +7906 0 +7907 0 +7908 1 +7909 0 +7910 0 +7911 0 +7912 0 +7913 0 +7914 0 +7915 0 +7916 0 +7917 0 +7918 1 +7919 0 +7920 0 +7921 0 +7922 0 +7923 0 +7924 0 +7925 0 +7926 0 +7927 0 +7928 1 +7929 0 +7930 0 +7931 0 +7932 0 +7933 0 +7934 0 +7935 0 +7936 0 +7937 0 +7938 1 +7939 0 +7940 0 +7941 0 +7942 0 +7943 0 +7944 0 +7945 0 +7946 0 +7947 0 +7948 1 +7949 0 +7950 0 +7951 0 +7952 0 +7953 0 +7954 0 +7955 0 +7956 0 +7957 0 +7958 1 +7959 0 +7960 0 +7961 0 +7962 0 +7963 0 +7964 0 +7965 0 +7966 0 +7967 0 +7968 1 +7969 0 +7970 0 +7971 0 +7972 0 +7973 0 +7974 0 +7975 0 +7976 0 +7977 0 +7978 1 +7979 0 +7980 0 +7981 0 +7982 0 +7983 0 +7984 0 +7985 1 +7986 0 +7987 0 +7988 0 +7989 0 +7990 0 +7991 0 +7992 0 +7993 0 +7994 0 +7995 1 +7996 0 +7997 0 +7998 0 +7999 0 +8000 0 +8001 0 +8002 0 +8003 0 +8004 0 +8005 0 +8006 1 +8007 0 +8008 0 +8009 0 +8010 0 +8011 0 +8012 0 +8013 0 +8014 0 +8015 1 +8016 0 +8017 0 +8018 0 +8019 0 +8020 0 +8021 0 +8022 0 +8023 0 +8024 0 +8025 1 +8026 0 +8027 0 +8028 0 +8029 0 +8030 0 +8031 0 +8032 0 +8033 0 +8034 0 +8035 0 +8036 1 +8037 0 +8038 0 +8039 0 +8040 0 +8041 0 +8042 0 +8043 0 +8044 0 +8045 0 +8046 1 +8047 0 +8048 0 +8049 0 +8050 0 +8051 0 +8052 0 +8053 0 +8054 0 +8055 0 +8056 0 +8057 1 +8058 0 +8059 0 +8060 0 +8061 0 +8062 0 +8063 0 +8064 0 +8065 0 +8066 0 +8067 1 +8068 0 +8069 0 +8070 0 +8071 0 +8072 0 +8073 0 +8074 0 +8075 0 +8076 0 +8077 0 +8078 1 +8079 0 +8080 0 +8081 0 +8082 0 +8083 0 +8084 0 +8085 0 +8086 0 +8087 0 +8088 1 +8089 0 +8090 0 +8091 0 +8092 0 +8093 0 +8094 0 +8095 0 +8096 0 +8097 0 +8098 1 +8099 0 +8100 0 +8101 0 +8102 0 +8103 0 +8104 0 +8105 1 +8106 0 +8107 0 +8108 0 +8109 0 +8110 0 +8111 0 +8112 0 +8113 0 +8114 0 +8115 1 +8116 0 +8117 0 +8118 0 +8119 0 +8120 0 +8121 0 +8122 0 +8123 0 +8124 0 +8125 1 +8126 0 +8127 0 +8128 0 +8129 0 +8130 0 +8131 0 +8132 0 +8133 0 +8134 1 +8135 0 +8136 0 +8137 0 +8138 0 +8139 0 +8140 0 +8141 0 +8142 0 +8143 0 +8144 0 +8145 1 +8146 0 +8147 0 +8148 0 +8149 0 +8150 0 +8151 0 +8152 0 +8153 0 +8154 0 +8155 0 +8156 1 +8157 0 +8158 0 +8159 0 +8160 0 +8161 0 +8162 0 +8163 0 +8164 0 +8165 0 +8166 1 +8167 0 +8168 0 +8169 0 +8170 0 +8171 0 +8172 0 +8173 0 +8174 0 +8175 0 +8176 1 +8177 0 +8178 0 +8179 0 +8180 0 +8181 0 +8182 0 +8183 0 +8184 0 +8185 0 +8186 1 +8187 0 +8188 0 +8189 0 +8190 0 +8191 0 +8192 0 +8193 0 +8194 0 +8195 0 +8196 0 +8197 1 +8198 0 +8199 0 +8200 0 +8201 0 +8202 0 +8203 0 +8204 0 +8205 0 +8206 0 +8207 1 +8208 0 +8209 0 +8210 0 +8211 0 +8212 0 +8213 0 +8214 0 +8215 0 +8216 1 +8217 0 +8218 0 +8219 0 +8220 0 +8221 0 +8222 0 +8223 0 +8224 0 +8225 1 +8226 0 +8227 0 +8228 0 +8229 0 +8230 0 +8231 0 +8232 0 +8233 0 +8234 0 +8235 1 +8236 0 +8237 0 +8238 0 +8239 0 +8240 0 +8241 0 +8242 0 +8243 0 +8244 1 +8245 0 +8246 0 +8247 0 +8248 0 +8249 0 +8250 0 +8251 0 +8252 0 +8253 0 +8254 1 +8255 0 +8256 0 +8257 0 +8258 0 +8259 0 +8260 0 +8261 0 +8262 0 +8263 0 +8264 0 +8265 1 +8266 0 +8267 0 +8268 0 +8269 0 +8270 0 +8271 0 +8272 0 +8273 0 +8274 0 +8275 1 +8276 0 +8277 0 +8278 0 +8279 0 +8280 0 +8281 0 +8282 0 +8283 0 +8284 0 +8285 0 +8286 1 +8287 0 +8288 0 +8289 0 +8290 0 +8291 0 +8292 0 +8293 0 +8294 0 +8295 0 +8296 1 +8297 0 +8298 0 +8299 0 +8300 0 +8301 0 +8302 0 +8303 0 +8304 1 +8305 0 +8306 0 +8307 0 +8308 0 +8309 0 +8310 0 +8311 0 +8312 0 +8313 0 +8314 1 +8315 0 +8316 0 +8317 0 +8318 0 +8319 0 +8320 0 +8321 0 +8322 0 +8323 0 +8324 1 +8325 0 +8326 0 +8327 0 +8328 0 +8329 0 +8330 0 +8331 0 +8332 0 +8333 0 +8334 0 +8335 0 +8336 0 +8337 0 +8338 0 +8339 0 +8340 0 +8341 0 +8342 1 +8343 0 +8344 0 +8345 0 +8346 0 +8347 0 +8348 0 +8349 0 +8350 0 +8351 1 +8352 0 +8353 0 +8354 0 +8355 0 +8356 0 +8357 0 +8358 0 +8359 0 +8360 0 +8361 1 +8362 0 +8363 0 +8364 0 +8365 0 +8366 0 +8367 0 +8368 0 +8369 0 +8370 0 +8371 1 +8372 0 +8373 0 +8374 0 +8375 0 +8376 0 +8377 0 +8378 0 +8379 0 +8380 1 +8381 0 +8382 0 +8383 0 +8384 0 +8385 0 +8386 0 +8387 0 +8388 0 +8389 1 +8390 0 +8391 0 +8392 0 +8393 0 +8394 0 +8395 0 +8396 0 +8397 0 +8398 0 +8399 1 +8400 0 +8401 0 +8402 0 +8403 0 +8404 0 +8405 0 +8406 0 +8407 0 +8408 0 +8409 1 +8410 0 +8411 0 +8412 0 +8413 0 +8414 0 +8415 0 +8416 0 +8417 0 +8418 0 +8419 1 +8420 0 +8421 0 +8422 0 +8423 0 +8424 0 +8425 0 +8426 0 +8427 0 +8428 0 +8429 0 +8430 1 +8431 0 +8432 0 +8433 0 +8434 0 +8435 0 +8436 0 +8437 0 +8438 1 +8439 0 +8440 0 +8441 0 +8442 0 +8443 0 +8444 0 +8445 0 +8446 0 +8447 1 +8448 0 +8449 0 +8450 0 +8451 0 +8452 0 +8453 0 +8454 0 +8455 0 +8456 0 +8457 1 +8458 0 +8459 0 +8460 0 +8461 0 +8462 0 +8463 0 +8464 0 +8465 0 +8466 0 +8467 1 +8468 0 +8469 0 +8470 0 +8471 0 +8472 0 +8473 0 +8474 0 +8475 0 +8476 0 +8477 1 +8478 0 +8479 0 +8480 0 +8481 0 +8482 0 +8483 0 +8484 0 +8485 0 +8486 1 +8487 0 +8488 0 +8489 0 +8490 0 +8491 0 +8492 0 +8493 0 +8494 0 +8495 0 +8496 0 +8497 0 +8498 0 +8499 0 +8500 0 +8501 0 +8502 0 +8503 0 +8504 0 +8505 0 +8506 1 +8507 0 +8508 0 +8509 0 +8510 0 +8511 0 +8512 0 +8513 0 +8514 0 +8515 0 +8516 0 +8517 0 +8518 0 +8519 0 +8520 0 +8521 0 +8522 0 +8523 1 +8524 0 +8525 0 +8526 0 +8527 0 +8528 0 +8529 0 +8530 0 +8531 0 +8532 1 +8533 0 +8534 0 +8535 0 +8536 0 +8537 0 +8538 0 +8539 0 +8540 0 +8541 1 +8542 0 +8543 0 +8544 0 +8545 0 +8546 0 +8547 0 +8548 0 +8549 1 +8550 0 +8551 0 +8552 0 +8553 0 +8554 0 +8555 0 +8556 0 +8557 0 +8558 0 +8559 1 +8560 0 +8561 0 +8562 0 +8563 0 +8564 0 +8565 0 +8566 0 +8567 0 +8568 1 +8569 0 +8570 0 +8571 0 +8572 0 +8573 0 +8574 0 +8575 0 +8576 0 +8577 1 +8578 0 +8579 0 +8580 0 +8581 0 +8582 0 +8583 0 +8584 0 +8585 0 +8586 1 +8587 0 +8588 0 +8589 0 +8590 0 +8591 0 +8592 0 +8593 0 +8594 0 +8595 0 +8596 1 +8597 0 +8598 0 +8599 0 +8600 0 +8601 0 +8602 0 +8603 0 +8604 0 +8605 0 +8606 1 +8607 0 +8608 0 +8609 0 +8610 0 +8611 0 +8612 0 +8613 0 +8614 0 +8615 0 +8616 1 +8617 0 +8618 0 +8619 0 +8620 0 +8621 0 +8622 0 +8623 0 +8624 0 +8625 1 +8626 0 +8627 0 +8628 0 +8629 0 +8630 0 +8631 0 +8632 0 +8633 1 +8634 0 +8635 0 +8636 0 +8637 0 +8638 0 +8639 0 +8640 0 +8641 0 +8642 0 +8643 1 +8644 0 +8645 0 +8646 0 +8647 0 +8648 0 +8649 0 +8650 0 +8651 1 +8652 0 +8653 0 +8654 0 +8655 0 +8656 0 +8657 0 +8658 0 +8659 0 +8660 1 +8661 0 +8662 0 +8663 0 +8664 0 +8665 0 +8666 0 +8667 0 +8668 0 +8669 1 +8670 0 +8671 0 +8672 0 +8673 0 +8674 0 +8675 0 +8676 0 +8677 1 +8678 0 +8679 0 +8680 0 +8681 0 +8682 0 +8683 0 +8684 0 +8685 0 +8686 1 +8687 0 +8688 0 +8689 0 +8690 0 +8691 0 +8692 0 +8693 0 +8694 0 +8695 0 +8696 1 +8697 0 +8698 0 +8699 0 +8700 0 +8701 0 +8702 0 +8703 0 +8704 0 +8705 1 +8706 0 +8707 0 +8708 0 +8709 0 +8710 0 +8711 0 +8712 0 +8713 0 +8714 0 +8715 1 +8716 0 +8717 0 +8718 0 +8719 0 +8720 0 +8721 0 +8722 0 +8723 0 +8724 0 +8725 1 +8726 0 +8727 0 +8728 0 +8729 0 +8730 0 +8731 0 +8732 0 +8733 0 +8734 0 +8735 1 +8736 0 +8737 0 +8738 0 +8739 0 +8740 0 +8741 0 +8742 0 +8743 0 +8744 0 +8745 1 +8746 0 +8747 0 +8748 0 +8749 0 +8750 0 +8751 0 +8752 0 +8753 0 +8754 0 +8755 1 +8756 0 +8757 0 +8758 0 +8759 0 +8760 0 +8761 0 +8762 0 +8763 1 +8764 0 +8765 0 +8766 0 +8767 0 +8768 0 +8769 0 +8770 1 +8771 0 +8772 0 +8773 0 +8774 0 +8775 0 +8776 0 +8777 0 +8778 0 +8779 0 +8780 1 +8781 0 +8782 0 +8783 0 +8784 0 +8785 0 +8786 0 +8787 0 +8788 0 +8789 1 +8790 0 +8791 0 +8792 0 +8793 0 +8794 0 +8795 0 +8796 0 +8797 0 +8798 1 +8799 0 +8800 0 +8801 0 +8802 0 +8803 0 +8804 0 +8805 0 +8806 0 +8807 3 +8808 0 +8809 0 +8810 1 +8811 0 +8812 0 +8813 0 +8814 0 +8815 1 +8816 0 +8817 0 +8818 0 +8819 0 +8820 1 +8821 0 +8822 0 +8823 0 +8824 1 +8825 0 +8826 0 +8827 0 +8828 0 +8829 0 +8830 1 +8831 0 +8832 0 +8833 0 +8834 0 +8835 0 +8836 0 +8837 1 +8838 0 +8839 0 +8840 0 +8841 0 +8842 0 +8843 0 +8844 0 +8845 1 +8846 0 +8847 0 +8848 0 +8849 0 +8850 0 +8851 0 +8852 0 +8853 0 +8854 0 +8855 1 +8856 0 +8857 0 +8858 0 +8859 0 +8860 0 +8861 0 +8862 0 +8863 0 +8864 0 +8865 1 +8866 0 +8867 0 +8868 0 +8869 0 +8870 0 +8871 0 +8872 1 +8873 0 +8874 0 +8875 0 +8876 0 +8877 0 +8878 0 +8879 0 +8880 1 +8881 0 +8882 0 +8883 0 +8884 0 +8885 0 +8886 0 +8887 0 +8888 1 +8889 0 +8890 0 +8891 0 +8892 0 +8893 0 +8894 0 +8895 0 +8896 0 +8897 0 +8898 0 +8899 0 +8900 0 +8901 0 +8902 0 +8903 0 +8904 0 +8905 1 +8906 0 +8907 0 +8908 0 +8909 0 +8910 0 +8911 0 +8912 1 +8913 0 +8914 0 +8915 0 +8916 0 +8917 0 +8918 0 +8919 0 +8920 1 +8921 0 +8922 0 +8923 0 +8924 0 +8925 0 +8926 0 +8927 0 +8928 0 +8929 1 +8930 0 +8931 0 +8932 0 +8933 0 +8934 0 +8935 0 +8936 0 +8937 0 +8938 0 +8939 1 +8940 0 +8941 0 +8942 0 +8943 0 +8944 0 +8945 0 +8946 0 +8947 0 +8948 0 +8949 1 +8950 0 +8951 0 +8952 0 +8953 0 +8954 0 +8955 0 +8956 0 +8957 0 +8958 0 +8959 1 +8960 0 +8961 0 +8962 0 +8963 0 +8964 0 +8965 0 +8966 0 +8967 0 +8968 0 +8969 1 +8970 0 +8971 0 +8972 0 +8973 0 +8974 0 +8975 0 +8976 0 +8977 0 +8978 1 +8979 0 +8980 0 +8981 0 +8982 0 +8983 0 +8984 0 +8985 0 +8986 0 +8987 1 +8988 0 +8989 0 +8990 0 +8991 0 +8992 0 +8993 0 +8994 0 +8995 0 +8996 0 +8997 1 +8998 0 +8999 0 +9000 0 +9001 0 +9002 0 +9003 0 +9004 0 +9005 0 +9006 1 +9007 0 +9008 0 +9009 0 +9010 0 +9011 0 +9012 0 +9013 0 +9014 1 +9015 0 +9016 0 +9017 0 +9018 0 +9019 0 +9020 0 +9021 0 +9022 1 +9023 0 +9024 0 +9025 0 +9026 0 +9027 0 +9028 0 +9029 0 +9030 1 +9031 0 +9032 0 +9033 0 +9034 0 +9035 0 +9036 0 +9037 0 +9038 1 +9039 0 +9040 0 +9041 0 +9042 0 +9043 0 +9044 0 +9045 0 +9046 0 +9047 1 +9048 0 +9049 0 +9050 0 +9051 0 +9052 0 +9053 0 +9054 0 +9055 1 +9056 0 +9057 0 +9058 0 +9059 0 +9060 0 +9061 0 +9062 0 +9063 1 +9064 0 +9065 0 +9066 0 +9067 0 +9068 0 +9069 0 +9070 0 +9071 0 +9072 0 +9073 1 +9074 0 +9075 0 +9076 0 +9077 0 +9078 0 +9079 0 +9080 0 +9081 0 +9082 0 +9083 0 +9084 0 +9085 0 +9086 0 +9087 0 +9088 0 +9089 0 +9090 0 +9091 0 +9092 1 +9093 0 +9094 0 +9095 0 +9096 0 +9097 0 +9098 0 +9099 0 +9100 1 +9101 0 +9102 0 +9103 0 +9104 0 +9105 0 +9106 0 +9107 0 +9108 1 +9109 0 +9110 0 +9111 0 +9112 0 +9113 0 +9114 0 +9115 0 +9116 0 +9117 1 +9118 0 +9119 0 +9120 0 +9121 0 +9122 0 +9123 0 +9124 0 +9125 0 +9126 1 +9127 0 +9128 0 +9129 0 +9130 0 +9131 0 +9132 0 +9133 0 +9134 0 +9135 1 +9136 0 +9137 0 +9138 0 +9139 0 +9140 0 +9141 0 +9142 0 +9143 1 +9144 0 +9145 0 +9146 0 +9147 0 +9148 0 +9149 0 +9150 0 +9151 0 +9152 1 +9153 0 +9154 0 +9155 0 +9156 0 +9157 0 +9158 0 +9159 0 +9160 0 +9161 1 +9162 0 +9163 0 +9164 0 +9165 0 +9166 0 +9167 0 +9168 0 +9169 1 +9170 0 +9171 0 +9172 0 +9173 0 +9174 0 +9175 0 +9176 0 +9177 0 +9178 1 +9179 0 +9180 0 +9181 0 +9182 0 +9183 0 +9184 0 +9185 0 +9186 0 +9187 0 +9188 1 +9189 0 +9190 0 +9191 0 +9192 0 +9193 0 +9194 0 +9195 0 +9196 0 +9197 1 +9198 0 +9199 0 +9200 0 +9201 0 +9202 0 +9203 0 +9204 0 +9205 0 +9206 0 +9207 0 +9208 0 +9209 0 +9210 0 +9211 0 +9212 0 +9213 0 +9214 0 +9215 0 +9216 0 +9217 0 +9218 0 +9219 0 +9220 0 +9221 1 +9222 0 +9223 0 +9224 0 +9225 0 +9226 0 +9227 0 +9228 1 +9229 0 +9230 0 +9231 0 +9232 0 +9233 0 +9234 0 +9235 0 +9236 0 +9237 1 +9238 0 +9239 0 +9240 0 +9241 0 +9242 0 +9243 0 +9244 0 +9245 0 +9246 1 +9247 0 +9248 0 +9249 0 +9250 0 +9251 0 +9252 0 +9253 0 +9254 0 +9255 1 +9256 0 +9257 0 +9258 0 +9259 0 +9260 0 +9261 1 +9262 0 +9263 0 +9264 0 +9265 0 +9266 0 +9267 0 +9268 0 +9269 0 +9270 0 +9271 0 +9272 0 +9273 0 +9274 0 +9275 0 +9276 1 +9277 0 +9278 0 +9279 0 +9280 0 +9281 0 +9282 0 +9283 0 +9284 0 +9285 0 +9286 0 +9287 0 +9288 0 +9289 0 +9290 1 +9291 0 +9292 0 +9293 0 +9294 0 +9295 0 +9296 0 +9297 0 +9298 0 +9299 0 +9300 1 +9301 0 +9302 0 +9303 0 +9304 0 +9305 0 +9306 0 +9307 0 +9308 1 +9309 0 +9310 0 +9311 0 +9312 0 +9313 0 +9314 0 +9315 0 +9316 1 +9317 0 +9318 0 +9319 0 +9320 0 +9321 0 +9322 0 +9323 1 +9324 0 +9325 0 +9326 0 +9327 0 +9328 0 +9329 0 +9330 0 +9331 1 +9332 0 +9333 0 +9334 0 +9335 0 +9336 0 +9337 0 +9338 1 +9339 0 +9340 0 +9341 0 +9342 0 +9343 0 +9344 0 +9345 1 +9346 0 +9347 0 +9348 0 +9349 0 +9350 0 +9351 0 +9352 0 +9353 0 +9354 0 +9355 1 +9356 0 +9357 0 +9358 0 +9359 0 +9360 0 +9361 0 +9362 0 +9363 1 +9364 0 +9365 0 +9366 0 +9367 0 +9368 0 +9369 0 +9370 1 +9371 0 +9372 0 +9373 0 +9374 0 +9375 0 +9376 0 +9377 0 +9378 1 +9379 0 +9380 0 +9381 0 +9382 0 +9383 0 +9384 0 +9385 0 +9386 0 +9387 0 +9388 0 +9389 0 +9390 0 +9391 0 +9392 0 +9393 0 +9394 0 +9395 1 +9396 0 +9397 0 +9398 0 +9399 0 +9400 0 +9401 0 +9402 0 +9403 1 +9404 0 +9405 0 +9406 0 +9407 0 +9408 0 +9409 0 +9410 0 +9411 0 +9412 1 +9413 0 +9414 0 +9415 0 +9416 0 +9417 0 +9418 0 +9419 0 +9420 1 +9421 0 +9422 0 +9423 0 +9424 0 +9425 0 +9426 0 +9427 0 +9428 0 +9429 1 +9430 0 +9431 0 +9432 0 +9433 0 +9434 0 +9435 0 +9436 0 +9437 0 +9438 0 +9439 1 +9440 0 +9441 0 +9442 0 +9443 0 +9444 0 +9445 0 +9446 0 +9447 0 +9448 0 +9449 1 +9450 0 +9451 0 +9452 0 +9453 0 +9454 0 +9455 0 +9456 0 +9457 1 +9458 0 +9459 0 +9460 0 +9461 0 +9462 0 +9463 0 +9464 1 +9465 0 +9466 0 +9467 0 +9468 0 +9469 0 +9470 0 +9471 0 +9472 0 +9473 1 +9474 0 +9475 0 +9476 0 +9477 0 +9478 0 +9479 0 +9480 0 +9481 1 +9482 0 +9483 0 +9484 0 +9485 0 +9486 0 +9487 0 +9488 1 +9489 0 +9490 0 +9491 0 +9492 0 +9493 0 +9494 0 +9495 0 +9496 0 +9497 1 +9498 0 +9499 0 +9500 0 +9501 0 +9502 0 +9503 0 +9504 0 +9505 0 +9506 0 +9507 0 +9508 0 +9509 0 +9510 0 +9511 0 +9512 0 +9513 0 +9514 1 +9515 0 +9516 0 +9517 0 +9518 0 +9519 0 +9520 0 +9521 0 +9522 1 +9523 0 +9524 0 +9525 0 +9526 0 +9527 0 +9528 0 +9529 0 +9530 1 +9531 0 +9532 0 +9533 0 +9534 0 +9535 0 +9536 0 +9537 0 +9538 1 +9539 0 +9540 0 +9541 0 +9542 0 +9543 0 +9544 0 +9545 0 +9546 0 +9547 1 +9548 0 +9549 0 +9550 0 +9551 0 +9552 0 +9553 0 +9554 0 +9555 1 +9556 0 +9557 0 +9558 0 +9559 0 +9560 0 +9561 0 +9562 0 +9563 1 +9564 0 +9565 0 +9566 0 +9567 0 +9568 0 +9569 0 +9570 0 +9571 0 +9572 1 +9573 0 +9574 0 +9575 0 +9576 0 +9577 0 +9578 0 +9579 0 +9580 1 +9581 0 +9582 0 +9583 0 +9584 0 +9585 0 +9586 0 +9587 0 +9588 0 +9589 1 +9590 0 +9591 0 +9592 0 +9593 0 +9594 0 +9595 0 +9596 0 +9597 0 +9598 0 +9599 0 +9600 0 +9601 0 +9602 0 +9603 0 +9604 0 +9605 0 +9606 0 +9607 0 +9608 1 +9609 0 +9610 0 +9611 0 +9612 0 +9613 0 +9614 0 +9615 1 +9616 0 +9617 0 +9618 0 +9619 0 +9620 0 +9621 0 +9622 1 +9623 0 +9624 0 +9625 0 +9626 0 +9627 0 +9628 0 +9629 0 +9630 1 +9631 0 +9632 0 +9633 0 +9634 0 +9635 0 +9636 0 +9637 0 +9638 0 +9639 1 +9640 0 +9641 0 +9642 0 +9643 0 +9644 0 +9645 0 +9646 0 +9647 0 +9648 1 +9649 0 +9650 0 +9651 0 +9652 0 +9653 0 +9654 0 +9655 0 +9656 1 +9657 0 +9658 0 +9659 0 +9660 0 +9661 0 +9662 0 +9663 1 +9664 0 +9665 0 +9666 0 +9667 0 +9668 0 +9669 0 +9670 0 +9671 0 +9672 0 +9673 1 +9674 0 +9675 0 +9676 0 +9677 0 +9678 0 +9679 0 +9680 0 +9681 1 +9682 0 +9683 0 +9684 0 +9685 0 +9686 0 +9687 0 +9688 0 +9689 1 +9690 0 +9691 0 +9692 0 +9693 0 +9694 0 +9695 0 +9696 1 +9697 0 +9698 0 +9699 0 +9700 0 +9701 0 +9702 0 +9703 0 +9704 1 +9705 0 +9706 0 +9707 0 +9708 0 +9709 0 +9710 0 +9711 0 +9712 1 +9713 0 +9714 0 +9715 0 +9716 0 +9717 0 +9718 0 +9719 0 +9720 0 +9721 0 +9722 1 +9723 0 +9724 0 +9725 0 +9726 0 +9727 0 +9728 0 +9729 0 +9730 0 +9731 1 +9732 0 +9733 0 +9734 0 +9735 0 +9736 0 +9737 0 +9738 0 +9739 0 +9740 1 +9741 0 +9742 0 +9743 0 +9744 0 +9745 0 +9746 0 +9747 0 +9748 0 +9749 1 +9750 0 +9751 0 +9752 0 +9753 0 +9754 0 +9755 0 +9756 1 +9757 0 +9758 0 +9759 0 +9760 0 +9761 0 +9762 0 +9763 0 +9764 0 +9765 0 +9766 0 +9767 0 +9768 0 +9769 0 +9770 0 +9771 0 +9772 0 +9773 1 +9774 0 +9775 0 +9776 0 +9777 0 +9778 0 +9779 0 +9780 1 +9781 0 +9782 0 +9783 0 +9784 0 +9785 0 +9786 0 +9787 0 +9788 1 +9789 0 +9790 0 +9791 0 +9792 0 +9793 0 +9794 0 +9795 0 +9796 0 +9797 0 +9798 0 +9799 0 +9800 0 +9801 0 +9802 0 +9803 1 +9804 0 +9805 0 +9806 0 +9807 0 +9808 0 +9809 0 +9810 0 +9811 0 +9812 1 +9813 0 +9814 0 +9815 0 +9816 0 +9817 0 +9818 0 +9819 0 +9820 1 +9821 0 +9822 0 +9823 0 +9824 0 +9825 0 +9826 0 +9827 0 +9828 0 +9829 1 +9830 0 +9831 0 +9832 0 +9833 0 +9834 0 +9835 0 +9836 0 +9837 0 +9838 1 +9839 0 +9840 0 +9841 0 +9842 0 +9843 0 +9844 0 +9845 0 +9846 0 +9847 0 +9848 1 +9849 0 +9850 0 +9851 0 +9852 0 +9853 0 +9854 4 +9855 0 +9856 0 +9857 1 +9858 0 +9859 0 +9860 0 +9861 0 +9862 1 +9863 0 +9864 0 +9865 0 +9866 0 +9867 0 +9868 1 +9869 0 +9870 0 +9871 0 +9872 0 +9873 1 +9874 0 +9875 0 +9876 0 +9877 0 +9878 1 +9879 0 +9880 0 +9881 0 +9882 0 +9883 0 +9884 0 +9885 0 +9886 1 +9887 0 +9888 0 +9889 0 +9890 0 +9891 0 +9892 0 +9893 0 +9894 0 +9895 1 +9896 0 +9897 0 +9898 0 +9899 0 +9900 0 +9901 0 +9902 0 +9903 0 +9904 1 +9905 0 +9906 0 +9907 0 +9908 0 +9909 0 +9910 0 +9911 0 +9912 0 +9913 0 +9914 0 +9915 0 +9916 0 +9917 0 +9918 0 +9919 0 +9920 0 +9921 0 +9922 0 +9923 0 +9924 1 +9925 0 +9926 0 +9927 0 +9928 0 +9929 0 +9930 0 +9931 0 +9932 0 +9933 0 +9934 1 +9935 0 +9936 0 +9937 0 +9938 0 +9939 0 +9940 0 +9941 0 +9942 0 +9943 0 +9944 1 +9945 0 +9946 0 +9947 0 +9948 0 +9949 0 +9950 0 +9951 0 +9952 0 +9953 0 +9954 1 +9955 0 +9956 0 +9957 0 +9958 0 +9959 0 +9960 0 +9961 0 +9962 0 +9963 1 +9964 0 +9965 0 +9966 0 +9967 0 +9968 0 +9969 0 +9970 0 +9971 0 +9972 1 +9973 0 +9974 0 +9975 0 +9976 0 +9977 0 +9978 0 +9979 0 +9980 0 +9981 0 +9982 0 +9983 1 +9984 0 +9985 0 +9986 0 +9987 0 +9988 0 +9989 0 +9990 0 +9991 0 +9992 0 +9993 1 +9994 0 +9995 0 +9996 0 +9997 0 +9998 0 +9999 0 +10000 0 +10001 0 +10002 0 +10003 0 +10004 1 +10005 0 +10006 0 +10007 0 +10008 0 +10009 0 +10010 0 +10011 0 +10012 0 +10013 1 +10014 0 +10015 0 +10016 0 +10017 0 +10018 0 +10019 0 +10020 0 +10021 0 +10022 0 +10023 1 +10024 0 +10025 0 +10026 0 +10027 0 +10028 0 +10029 0 +10030 0 +10031 1 +10032 0 +10033 0 +10034 0 +10035 0 +10036 0 +10037 0 +10038 0 +10039 0 +10040 0 +10041 1 +10042 0 +10043 0 +10044 0 +10045 0 +10046 0 +10047 0 +10048 0 +10049 0 +10050 0 +10051 1 +10052 0 +10053 0 +10054 0 +10055 0 +10056 0 +10057 0 +10058 0 +10059 0 +10060 1 +10061 0 +10062 0 +10063 0 +10064 0 +10065 0 +10066 0 +10067 0 +10068 0 +10069 1 +10070 0 +10071 0 +10072 0 +10073 0 +10074 0 +10075 0 +10076 0 +10077 0 +10078 1 +10079 0 +10080 0 +10081 0 +10082 0 +10083 0 +10084 0 +10085 0 +10086 0 +10087 1 +10088 0 +10089 0 +10090 0 +10091 0 +10092 0 +10093 0 +10094 0 +10095 0 +10096 0 +10097 1 +10098 0 +10099 0 +10100 0 +10101 0 +10102 0 +10103 0 +10104 0 +10105 0 +10106 0 +10107 0 +10108 1 +10109 0 +10110 0 +10111 0 +10112 0 +10113 0 +10114 0 +10115 0 +10116 0 +10117 0 +10118 1 +10119 0 +10120 0 +10121 0 +10122 0 +10123 0 +10124 0 +10125 0 +10126 0 +10127 1 +10128 0 +10129 0 +10130 0 +10131 0 +10132 0 +10133 0 +10134 0 +10135 0 +10136 0 +10137 1 +10138 0 +10139 0 +10140 0 +10141 0 +10142 0 +10143 0 +10144 0 +10145 0 +10146 0 +10147 1 +10148 0 +10149 0 +10150 0 +10151 0 +10152 0 +10153 0 +10154 0 +10155 0 +10156 0 +10157 1 +10158 0 +10159 0 +10160 0 +10161 0 +10162 0 +10163 0 +10164 0 +10165 0 +10166 0 +10167 1 +10168 0 +10169 0 +10170 0 +10171 0 +10172 0 +10173 0 +10174 0 +10175 0 +10176 1 +10177 0 +10178 0 +10179 0 +10180 0 +10181 0 +10182 0 +10183 0 +10184 0 +10185 1 +10186 0 +10187 0 +10188 0 +10189 0 +10190 0 +10191 0 +10192 0 +10193 1 +10194 0 +10195 0 +10196 0 +10197 0 +10198 0 +10199 0 +10200 0 +10201 1 +10202 0 +10203 0 +10204 0 +10205 0 +10206 0 +10207 0 +10208 0 +10209 0 +10210 0 +10211 1 +10212 0 +10213 0 +10214 0 +10215 0 +10216 0 +10217 0 +10218 0 +10219 0 +10220 1 +10221 0 +10222 0 +10223 0 +10224 0 +10225 0 +10226 0 +10227 0 +10228 0 +10229 0 +10230 1 +10231 0 +10232 0 +10233 0 +10234 0 +10235 0 +10236 0 +10237 0 +10238 0 +10239 0 +10240 1 +10241 0 +10242 0 +10243 0 +10244 0 +10245 0 +10246 0 +10247 0 +10248 0 +10249 0 +10250 1 +10251 0 +10252 0 +10253 0 +10254 0 +10255 0 +10256 0 +10257 0 +10258 0 +10259 0 +10260 1 +10261 0 +10262 0 +10263 0 +10264 1 +10265 0 +10266 0 +10267 0 +10268 0 +10269 0 +10270 1 +10271 0 +10272 0 +10273 0 +10274 0 +10275 0 +10276 0 +10277 0 +10278 1 +10279 0 +10280 0 +10281 0 +10282 0 +10283 0 +10284 0 +10285 0 +10286 1 +10287 0 +10288 0 +10289 0 +10290 0 +10291 0 +10292 0 +10293 0 +10294 0 +10295 0 +10296 1 +10297 0 +10298 0 +10299 0 +10300 0 +10301 0 +10302 0 +10303 0 +10304 0 +10305 1 +10306 0 +10307 0 +10308 0 +10309 0 +10310 0 +10311 0 +10312 0 +10313 0 +10314 1 +10315 0 +10316 0 +10317 0 +10318 0 +10319 0 +10320 0 +10321 0 +10322 0 +10323 1 +10324 0 +10325 0 +10326 0 +10327 0 +10328 0 +10329 0 +10330 0 +10331 0 +10332 0 +10333 1 +10334 0 +10335 0 +10336 0 +10337 0 +10338 0 +10339 0 +10340 0 +10341 0 +10342 0 +10343 0 +10344 0 +10345 0 +10346 0 +10347 0 +10348 0 +10349 0 +10350 0 +10351 1 +10352 0 +10353 0 +10354 0 +10355 0 +10356 0 +10357 0 +10358 0 +10359 0 +10360 1 +10361 0 +10362 0 +10363 0 +10364 0 +10365 0 +10366 0 +10367 0 +10368 0 +10369 0 +10370 1 +10371 0 +10372 0 +10373 0 +10374 0 +10375 0 +10376 0 +10377 0 +10378 0 +10379 0 +10380 1 +10381 0 +10382 0 +10383 0 +10384 0 +10385 0 +10386 0 +10387 1 +10388 0 +10389 0 +10390 0 +10391 0 +10392 0 +10393 0 +10394 0 +10395 1 +10396 0 +10397 0 +10398 0 +10399 0 +10400 0 +10401 0 +10402 0 +10403 0 +10404 1 +10405 0 +10406 0 +10407 0 +10408 0 +10409 0 +10410 0 +10411 0 +10412 0 +10413 0 +10414 1 +10415 0 +10416 0 +10417 0 +10418 0 +10419 0 +10420 0 +10421 0 +10422 0 +10423 1 +10424 0 +10425 0 +10426 0 +10427 0 +10428 0 +10429 0 +10430 0 +10431 0 +10432 0 +10433 1 +10434 0 +10435 0 +10436 0 +10437 0 +10438 0 +10439 0 +10440 0 +10441 0 +10442 0 +10443 1 +10444 0 +10445 0 +10446 0 +10447 0 +10448 0 +10449 0 +10450 0 +10451 0 +10452 1 +10453 0 +10454 0 +10455 0 +10456 0 +10457 0 +10458 0 +10459 0 +10460 1 +10461 0 +10462 0 +10463 0 +10464 0 +10465 0 +10466 0 +10467 0 +10468 0 +10469 1 +10470 0 +10471 0 +10472 0 +10473 0 +10474 0 +10475 0 +10476 0 +10477 0 +10478 0 +10479 1 +10480 0 +10481 0 +10482 0 +10483 0 +10484 0 +10485 0 +10486 0 +10487 0 +10488 0 +10489 1 +10490 0 +10491 0 +10492 0 +10493 0 +10494 0 +10495 0 +10496 0 +10497 0 +10498 1 +10499 0 +10500 0 +10501 0 +10502 0 +10503 0 +10504 0 +10505 0 +10506 1 +10507 0 +10508 0 +10509 0 +10510 0 +10511 0 +10512 0 +10513 0 +10514 0 +10515 0 +10516 0 +10517 1 +10518 0 +10519 0 +10520 0 +10521 0 +10522 0 +10523 0 +10524 0 +10525 0 +10526 0 +10527 1 +10528 0 +10529 0 +10530 0 +10531 0 +10532 0 +10533 0 +10534 0 +10535 0 +10536 1 +10537 0 +10538 0 +10539 0 +10540 0 +10541 0 +10542 0 +10543 0 +10544 0 +10545 1 +10546 0 +10547 0 +10548 0 +10549 0 +10550 0 +10551 0 +10552 0 +10553 0 +10554 0 +10555 1 +10556 0 +10557 0 +10558 0 +10559 0 +10560 0 +10561 0 +10562 0 +10563 0 +10564 0 +10565 0 +10566 1 +10567 0 +10568 0 +10569 0 +10570 0 +10571 0 +10572 0 +10573 0 +10574 0 +10575 0 +10576 0 +10577 0 +10578 0 +10579 0 +10580 0 +10581 0 +10582 0 +10583 0 +10584 0 +10585 0 +10586 0 +10587 1 +10588 0 +10589 0 +10590 0 +10591 0 +10592 0 +10593 0 +10594 0 +10595 0 +10596 0 +10597 0 +10598 1 +10599 0 +10600 0 +10601 0 +10602 0 +10603 0 +10604 0 +10605 0 +10606 0 +10607 0 +10608 0 +10609 1 +10610 0 +10611 0 +10612 0 +10613 0 +10614 0 +10615 0 +10616 0 +10617 1 +10618 0 +10619 0 +10620 0 +10621 0 +10622 0 +10623 0 +10624 0 +10625 1 +10626 0 +10627 0 +10628 0 +10629 0 +10630 0 +10631 0 +10632 0 +10633 0 +10634 1 +10635 0 +10636 0 +10637 0 +10638 0 +10639 0 +10640 0 +10641 0 +10642 0 +10643 0 +10644 1 +10645 0 +10646 0 +10647 0 +10648 0 +10649 0 +10650 0 +10651 0 +10652 0 +10653 1 +10654 0 +10655 0 +10656 0 +10657 0 +10658 0 +10659 0 +10660 0 +10661 1 +10662 0 +10663 0 +10664 0 +10665 0 +10666 0 +10667 0 +10668 0 +10669 0 +10670 0 +10671 1 +10672 0 +10673 0 +10674 0 +10675 0 +10676 0 +10677 0 +10678 0 +10679 0 +10680 0 +10681 1 +10682 0 +10683 0 +10684 0 +10685 0 +10686 0 +10687 0 +10688 0 +10689 0 +10690 0 +10691 0 +10692 0 +10693 0 +10694 0 +10695 0 +10696 0 +10697 0 +10698 0 +10699 0 +10700 0 +10701 1 +10702 0 +10703 0 +10704 0 +10705 0 +10706 0 +10707 0 +10708 0 +10709 0 +10710 0 +10711 1 +10712 0 +10713 0 +10714 0 +10715 0 +10716 0 +10717 0 +10718 0 +10719 0 +10720 0 +10721 1 +10722 0 +10723 0 +10724 0 +10725 0 +10726 0 +10727 0 +10728 0 +10729 0 +10730 1 +10731 0 +10732 0 +10733 0 +10734 0 +10735 0 +10736 0 +10737 0 +10738 0 +10739 0 +10740 1 +10741 0 +10742 0 +10743 0 +10744 0 +10745 0 +10746 0 +10747 0 +10748 0 +10749 1 +10750 0 +10751 0 +10752 0 +10753 0 +10754 0 +10755 0 +10756 0 +10757 0 +10758 0 +10759 1 +10760 0 +10761 0 +10762 0 +10763 0 +10764 0 +10765 0 +10766 0 +10767 0 +10768 0 +10769 0 +10770 1 +10771 0 +10772 0 +10773 0 +10774 0 +10775 0 +10776 0 +10777 0 +10778 0 +10779 0 +10780 1 +10781 0 +10782 0 +10783 0 +10784 0 +10785 0 +10786 0 +10787 0 +10788 0 +10789 0 +10790 1 +10791 0 +10792 0 +10793 0 +10794 0 +10795 0 +10796 0 +10797 0 +10798 0 +10799 0 +10800 1 +10801 0 +10802 0 +10803 0 +10804 0 +10805 0 +10806 0 +10807 0 +10808 0 +10809 0 +10810 0 +10811 0 +10812 0 +10813 0 +10814 0 +10815 0 +10816 0 +10817 0 +10818 0 +10819 0 +10820 1 +10821 0 +10822 0 +10823 0 +10824 0 +10825 0 +10826 0 +10827 0 +10828 0 +10829 0 +10830 0 +10831 1 +10832 0 +10833 0 +10834 0 +10835 0 +10836 0 +10837 0 +10838 0 +10839 0 +10840 1 +10841 0 +10842 0 +10843 0 +10844 0 +10845 0 +10846 0 +10847 0 +10848 0 +10849 0 +10850 0 +10851 0 +10852 0 +10853 0 +10854 0 +10855 0 +10856 0 +10857 0 +10858 0 +10859 0 +10860 1 +10861 0 +10862 0 +10863 0 +10864 0 +10865 0 +10866 0 +10867 0 +10868 0 +10869 1 +10870 0 +10871 0 +10872 0 +10873 0 +10874 0 +10875 0 +10876 0 +10877 0 +10878 0 +10879 0 +10880 1 +10881 0 +10882 0 +10883 0 +10884 0 +10885 0 +10886 0 +10887 0 +10888 0 +10889 0 +10890 1 +10891 0 +10892 0 +10893 0 +10894 0 +10895 0 +10896 0 +10897 0 +10898 0 +10899 0 +10900 1 +10901 0 +10902 0 +10903 0 +10904 0 +10905 0 +10906 0 +10907 0 +10908 0 +10909 0 +10910 0 +10911 1 +10912 0 +10913 0 +10914 0 +10915 0 +10916 0 +10917 0 +10918 0 +10919 0 +10920 0 +10921 1 +10922 0 +10923 0 +10924 0 +10925 0 +10926 0 +10927 0 +10928 0 +10929 0 +10930 0 +10931 1 +10932 0 +10933 0 +10934 0 +10935 0 +10936 0 +10937 0 +10938 0 +10939 0 +10940 1 +10941 0 +10942 0 +10943 0 +10944 0 +10945 0 +10946 0 +10947 0 +10948 0 +10949 1 +10950 0 +10951 0 +10952 0 +10953 0 +10954 0 +10955 0 +10956 0 +10957 0 +10958 1 +10959 0 +10960 0 +10961 0 +10962 0 +10963 0 +10964 0 +10965 0 +10966 0 +10967 0 +10968 1 +10969 0 +10970 0 +10971 0 +10972 0 +10973 0 +10974 0 +10975 0 +10976 0 +10977 0 +10978 1 +10979 0 +10980 0 +10981 0 +10982 0 +10983 0 +10984 0 +10985 0 +10986 0 +10987 0 +10988 0 +10989 1 +10990 0 +10991 0 +10992 0 +10993 0 +10994 0 +10995 0 +10996 0 +10997 0 +10998 0 +10999 0 +11000 1 \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..0c44ae7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Isaac Z. Schlueter ("Author") +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md new file mode 100644 index 0000000..34c1189 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md @@ -0,0 +1,15 @@ +# readable-stream + +***Node-core streams for userland*** + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png)](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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..b513d61 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,89 @@ +// 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..895ca50 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,46 @@ +// 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..6307220 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,982 @@ +// 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..eb188df --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,210 @@ +// 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..4bdaa4f --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,386 @@ +// 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/LICENSE b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/LICENSE new file mode 100644 index 0000000..d8d7f94 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/LICENSE @@ -0,0 +1,19 @@ +Copyright Node.js 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..ff4c851 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// 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(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +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 objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (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; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json new file mode 100644 index 0000000..ddd227e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json @@ -0,0 +1,60 @@ +{ + "name": "core-util-is", + "version": "1.0.2", + "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.git" + }, + "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" + }, + "scripts": { + "test": "tap test.js" + }, + "devDependencies": { + "tap": "^2.3.0" + }, + "gitHead": "a177da234df5638b363ddc15fa324619a38577c8", + "homepage": "https://github.com/isaacs/core-util-is#readme", + "_id": "core-util-is@1.0.2", + "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "_from": "core-util-is@>=1.0.0 <1.1.0", + "_npmVersion": "3.3.2", + "_nodeVersion": "4.0.0", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "dist": { + "shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "tarball": "http://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/test.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/test.js new file mode 100644 index 0000000..1a490c6 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/test.js @@ -0,0 +1,68 @@ +var assert = require('tap'); + +var t = require('./lib/util'); + +assert.equal(t.isArray([]), true); +assert.equal(t.isArray({}), false); + +assert.equal(t.isBoolean(null), false); +assert.equal(t.isBoolean(true), true); +assert.equal(t.isBoolean(false), true); + +assert.equal(t.isNull(null), true); +assert.equal(t.isNull(undefined), false); +assert.equal(t.isNull(false), false); +assert.equal(t.isNull(), false); + +assert.equal(t.isNullOrUndefined(null), true); +assert.equal(t.isNullOrUndefined(undefined), true); +assert.equal(t.isNullOrUndefined(false), false); +assert.equal(t.isNullOrUndefined(), true); + +assert.equal(t.isNumber(null), false); +assert.equal(t.isNumber('1'), false); +assert.equal(t.isNumber(1), true); + +assert.equal(t.isString(null), false); +assert.equal(t.isString('1'), true); +assert.equal(t.isString(1), false); + +assert.equal(t.isSymbol(null), false); +assert.equal(t.isSymbol('1'), false); +assert.equal(t.isSymbol(1), false); +assert.equal(t.isSymbol(Symbol()), true); + +assert.equal(t.isUndefined(null), false); +assert.equal(t.isUndefined(undefined), true); +assert.equal(t.isUndefined(false), false); +assert.equal(t.isUndefined(), true); + +assert.equal(t.isRegExp(null), false); +assert.equal(t.isRegExp('1'), false); +assert.equal(t.isRegExp(new RegExp()), true); + +assert.equal(t.isObject({}), true); +assert.equal(t.isObject([]), true); +assert.equal(t.isObject(new RegExp()), true); +assert.equal(t.isObject(new Date()), true); + +assert.equal(t.isDate(null), false); +assert.equal(t.isDate('1'), false); +assert.equal(t.isDate(new Date()), true); + +assert.equal(t.isError(null), false); +assert.equal(t.isError({ err: true }), false); +assert.equal(t.isError(new Error()), true); + +assert.equal(t.isFunction(null), false); +assert.equal(t.isFunction({ }), false); +assert.equal(t.isFunction(function() {}), true); + +assert.equal(t.isPrimitive(null), true); +assert.equal(t.isPrimitive(''), true); +assert.equal(t.isPrimitive(0), true); +assert.equal(t.isPrimitive(new Date()), false); + +assert.equal(t.isBuffer(null), false); +assert.equal(t.isBuffer({}), false); +assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json new file mode 100644 index 0000000..93d5078 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json @@ -0,0 +1,50 @@ +{ + "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.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "_id": "inherits@2.0.1", + "dist": { + "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/inherits#readme" +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md new file mode 100644 index 0000000..052a62b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js new file mode 100644 index 0000000..ec58596 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js new file mode 100644 index 0000000..5f5ad45 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json new file mode 100644 index 0000000..19228ab --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json @@ -0,0 +1,53 @@ +{ + "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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// 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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json new file mode 100644 index 0000000..0364d54 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json @@ -0,0 +1,54 @@ +{ + "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", + "gitHead": "d46d4fd87cf1d06e031c23f1ba170ca7d4ade9a0", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "_id": "string_decoder@0.10.31", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_from": "string_decoder@>=0.10.0 <0.11.0", + "_npmVersion": "1.4.23", + "_npmUser": { + "name": "rvagg", + "email": "rod@vagg.org" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + }, + { + "name": "rvagg", + "email": "rod@vagg.org" + } + ], + "dist": { + "shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "tarball": "http://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json new file mode 100644 index 0000000..2dc3a25 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json @@ -0,0 +1,69 @@ +{ + "name": "readable-stream", + "version": "1.0.31", + "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.git" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/readable-stream/issues" + }, + "homepage": "https://github.com/isaacs/readable-stream", + "_id": "readable-stream@1.0.31", + "_shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", + "_from": "readable-stream@1.0.31", + "_npmVersion": "1.4.9", + "_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": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", + "tarball": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..4d1ddfc --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js @@ -0,0 +1,6 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +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/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/package.json b/5-3/node_modules/mongoose/node_modules/mongodb/package.json new file mode 100644 index 0000000..ec73276 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/package.json @@ -0,0 +1,85 @@ +{ + "name": "mongodb", + "version": "2.1.6", + "description": "MongoDB legacy driver emulation layer on top of mongodb-core", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" + }, + "keywords": [ + "mongodb", + "driver", + "legacy" + ], + "dependencies": { + "es6-promise": "3.0.2", + "mongodb-core": "1.3.1", + "readable-stream": "1.0.31" + }, + "devDependencies": { + "JSONStream": "^1.0.7", + "betterbenchmarks": "^0.1.0", + "bluebird": "2.9.27", + "bson": "^0.4.20", + "cli-table": "^0.3.1", + "co": "4.5.4", + "colors": "^1.1.2", + "coveralls": "^2.11.6", + "event-stream": "^3.3.2", + "gleak": "0.5.0", + "integra": "0.1.8", + "jsdoc": "3.3.0-beta3", + "ldjson-stream": "^1.2.1", + "mongodb-extended-json": "1.3.0", + "mongodb-topology-manager": "1.0.x", + "mongodb-version-manager": "^0.8.10", + "nyc": "^5.5.0", + "optimist": "0.6.1", + "rimraf": "2.2.6", + "semver": "4.1.0", + "worker-farm": "^1.3.1" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.3" + }, + "bugs": { + "url": "https://github.com/mongodb/node-mongodb-native/issues" + }, + "scripts": { + "test": "node test/runner.js -t functional", + "coverage": "nyc node test/runner.js -t functional && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls" + }, + "homepage": "https://github.com/mongodb/node-mongodb-native", + "gitHead": "173e568b5e7678b9cf9f3602ac28028309a1b85d", + "_id": "mongodb@2.1.6", + "_shasum": "ebeec407dd72ec1d79f161ddb3e9b1c89fd49380", + "_from": "mongodb@2.1.6", + "_npmVersion": "2.14.12", + "_nodeVersion": "4.2.4", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "ebeec407dd72ec1d79f161ddb3e9b1c89fd49380", + "tarball": "http://registry.npmjs.org/mongodb/-/mongodb-2.1.6.tgz" + }, + "_npmOperationalInternal": { + "host": "packages-9-west.internal.npmjs.com", + "tmp": "tmp/mongodb-2.1.6.tgz_1454648397133_0.14874957758001983" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-2.1.6.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/test.js b/5-3/node_modules/mongoose/node_modules/mongodb/test.js new file mode 100644 index 0000000..68f40d1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/test.js @@ -0,0 +1,14 @@ +var MongoClient = require('./').MongoClient; + +MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { + console.dir(err) + + var json = require('./test.json'); + + db.collection('t').insertOne(json, function(err, r) { + console.dir(err) + console.dir(r) + db.close(); + + }) +}); diff --git a/5-3/node_modules/mongoose/node_modules/mongodb/test.json b/5-3/node_modules/mongoose/node_modules/mongodb/test.json new file mode 100644 index 0000000..6644553 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mongodb/test.json @@ -0,0 +1,28 @@ +{ + "military_base": { + "type": "military", + "level": 0, + "maxLevel": 25, + "upgrade": true, + "targetEnvironment": [], + "timeUntilBuilt": 0, + "costCoef": 0.4, + "requiredResearches": ["foo#4", "bar#1"], + "requiredResources" : ["cash", "metal", "palladium"], + "inProgress": 0, + "queue": [] + }, + "aqua_center": { + "type": "industrial", + "level": 0, + "maxLevel": 25, + "upgrade": true, + "targetEnvironment": ["ocean", "snowy"], + "timeUntilBuilt": 0, + "costCoef": 0.7, + "requiredResearches": ["lorem#10", "ipsum#3"], + "requiredResources" : ["cash", "cristal"], + "inProgress": 0, + "queue": [] + } +} diff --git a/5-3/node_modules/mongoose/node_modules/mpath/.npmignore b/5-3/node_modules/mongoose/node_modules/mpath/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/5-3/node_modules/mongoose/node_modules/mpath/.travis.yml b/5-3/node_modules/mongoose/node_modules/mpath/.travis.yml new file mode 100644 index 0000000..895dbd3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/5-3/node_modules/mongoose/node_modules/mpath/History.md b/5-3/node_modules/mongoose/node_modules/mpath/History.md new file mode 100644 index 0000000..87de484 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/History.md @@ -0,0 +1,30 @@ + +0.2.1 / 2013-03-22 +================== + + * test; added for #5 + * fix typo that breaks set #5 [Contra](https://github.com/Contra) + +0.2.0 / 2013-03-15 +================== + + * added; adapter support for set + * added; adapter support for get + * add basic benchmarks + * add support for using module as a component #2 [Contra](https://github.com/Contra) + +0.1.1 / 2012-12-21 +================== + + * added; map support + +0.1.0 / 2012-12-13 +================== + + * added; set('array.property', val, object) support + * added; get('array.property', object) support + +0.0.1 / 2012-11-03 +================== + + * initial release diff --git a/5-3/node_modules/mongoose/node_modules/mpath/LICENSE b/5-3/node_modules/mongoose/node_modules/mpath/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/LICENSE @@ -0,0 +1,22 @@ +(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/5-3/node_modules/mongoose/node_modules/mpath/Makefile b/5-3/node_modules/mongoose/node_modules/mpath/Makefile new file mode 100644 index 0000000..314c361 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/Makefile @@ -0,0 +1,8 @@ + +test: + @node_modules/mocha/bin/mocha -A $(T) + +bench: + node bench.js + +.PHONY: test diff --git a/5-3/node_modules/mongoose/node_modules/mpath/README.md b/5-3/node_modules/mongoose/node_modules/mpath/README.md new file mode 100644 index 0000000..9831dd0 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/README.md @@ -0,0 +1,278 @@ +#mpath + +{G,S}et javascript object values using MongoDB-like path notation. + +###Getting + +```js +var mpath = require('mpath'); + +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.1.title', obj) // 'exciting!' +``` + +`mpath.get` supports array property notation as well. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.title', obj) // ['funny', 'exciting!'] +``` + +Array property and indexing syntax, when used together, are very powerful. + +```js +var obj = { + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} + +var found = mpath.get('array.o.array.x.b.1', obj); + +console.log(found); // prints.. + + [ [6, undefined] + , [2, undefined, undefined] + , [null, 1] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + +``` + +#####Field selection rules: + +The following rules are iteratively applied to each `segment` in the passed `path`. For example: + +```js +var path = 'one.two.14'; // path +'one' // segment 0 +'two' // segment 1 +14 // segment 2 +``` + +- 1) when value of the segment parent is not an array, return the value of `parent.segment` +- 2) when value of the segment parent is an array + - a) if the segment is an integer, replace the parent array with the value at `parent[segment]` + - b) if not an integer, keep the array but replace each array `item` with the value returned from calling `get(remainingSegments, item)` or undefined if falsey. + +#####Maps + +`mpath.get` also accepts an optional `map` argument which receives each individual found value. The value returned from the `map` function will be used in the original found values place. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.get('comments.title', obj, function (val) { + return 'funny' == val + ? 'amusing' + : val; +}); +// ['amusing', 'exciting!'] +``` + +###Setting + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.1.title', 'hilarious', obj) +console.log(obj.comments[1].title) // 'hilarious' +``` + +`mpath.set` supports the same array property notation as `mpath.get`. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: 'hilarious' }, + { title: 'fruity' } + ]} +``` + +Array property and indexing syntax can be used together also when setting. + +```js +var obj = { + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ] +} + +mpath.set('array.1.o', 'this was changed', obj); + +console.log(require('util').inspect(obj, false, 1000)); // prints.. + +{ + array: [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: 'this was changed' } + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} + +mpath.set('array.o.array.x', 'this was changed too', obj); + +console.log(require('util').inspect(obj, false, 1000)); // prints.. + +{ + array: [ + { o: { array: [{x: 'this was changed too'}, { y: 10, x: 'this was changed too'} ] }} + , { o: 'this was changed' } + , { o: { array: [{x: 'this was changed too'}, { x: 'this was changed too'}] }} + , { o: { array: [{x: 'this was changed too'}] }} + , { o: { array: [{x: 'this was changed too', y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; +} +``` + +####Setting arrays + +By default, setting a property within an array to another array results in each element of the new array being set to the item in the destination array at the matching index. An example is helpful. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: 'hilarious' }, + { title: 'fruity' } + ]} +``` + +If we do not desire this destructuring-like assignment behavior we may instead specify the `$` operator in the path being set to force the array to be copied directly. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.$.title', ['hilarious', 'fruity'], obj); + +console.log(obj); // prints.. + + { comments: [ + { title: ['hilarious', 'fruity'] }, + { title: ['hilarious', 'fruity'] } + ]} +``` + +####Field assignment rules + +The rules utilized mirror those used on `mpath.get`, meaning we can take values returned from `mpath.get`, update them, and reassign them using `mpath.set`. Note that setting nested arrays of arrays can get unweildy quickly. Check out the [tests](https://github.com/aheckmann/mpath/blob/master/test/index.js) for more extreme examples. + +#####Maps + +`mpath.set` also accepts an optional `map` argument which receives each individual value being set. The value returned from the `map` function will be used in the original values place. + +```js +var obj = { + comments: [ + { title: 'funny' }, + { title: 'exciting!' } + ] +} + +mpath.set('comments.title', ['hilarious', 'fruity'], obj, function (val) { + return val.length; +}); + +console.log(obj); // prints.. + + { comments: [ + { title: 9 }, + { title: 6 } + ]} +``` + +### Custom object types + +Sometimes you may want to enact the same functionality on custom object types that store all their real data internally, say for an ODM type object. No fear, `mpath` has you covered. Simply pass the name of the property being used to store the internal data and it will be traversed instead: + +```js +var mpath = require('mpath'); + +var obj = { + comments: [ + { title: 'exciting!', _doc: { title: 'great!' }} + ] +} + +mpath.get('comments.0.title', obj, '_doc') // 'great!' +mpath.set('comments.0.title', 'nov 3rd', obj, '_doc') +mpath.get('comments.0.title', obj, '_doc') // 'nov 3rd' +mpath.get('comments.0.title', obj) // 'exciting' +``` + +When used with a `map`, the `map` argument comes last. + +```js +mpath.get(path, obj, '_doc', map); +mpath.set(path, val, obj, '_doc', map); +``` + +[LICENSE](https://github.com/aheckmann/mpath/blob/master/LICENSE) + diff --git a/5-3/node_modules/mongoose/node_modules/mpath/bench.js b/5-3/node_modules/mongoose/node_modules/mpath/bench.js new file mode 100644 index 0000000..7ec6a87 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/bench.js @@ -0,0 +1,109 @@ + +var mpath = require('./') +var Bench = require('benchmark'); +var sha = require('child_process').exec("git log --pretty=format:'%h' -n 1", function (err, sha) { + if (err) throw err; + + var fs = require('fs') + var filename = __dirname + '/bench.out'; + var out = fs.createWriteStream(filename, { flags: 'a', encoding: 'utf8' }); + + /** + * test doc creator + */ + + function doc () { + var o = { first: { second: { third: [3,{ name: 'aaron' }, 9] }}}; + o.comments = [ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ]; + o.name = 'jiro'; + o.array = [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; + o.arr = [ + { arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true } + ] + return o; + } + + var o = doc(); + + var s = new Bench.Suite; + s.add('mpath.get("first", obj)', function () { + mpath.get('first', o); + }) + s.add('mpath.get("first.second", obj)', function () { + mpath.get('first.second', o); + }) + s.add('mpath.get("first.second.third.1.name", obj)', function () { + mpath.get('first.second.third.1.name', o); + }) + s.add('mpath.get("comments", obj)', function () { + mpath.get('comments', o); + }) + s.add('mpath.get("comments.1", obj)', function () { + mpath.get('comments.1', o); + }) + s.add('mpath.get("comments.2.name", obj)', function () { + mpath.get('comments.2.name', o); + }) + s.add('mpath.get("comments.2.comments.1.comments.0.val", obj)', function () { + mpath.get('comments.2.comments.1.comments.0.val', o); + }) + s.add('mpath.get("comments.name", obj)', function () { + mpath.get('comments.name', o); + }) + + s.add('mpath.set("first", obj, val)', function () { + mpath.set('first', o, 1); + }) + s.add('mpath.set("first.second", obj, val)', function () { + mpath.set('first.second', o, 1); + }) + s.add('mpath.set("first.second.third.1.name", obj, val)', function () { + mpath.set('first.second.third.1.name', o, 1); + }) + s.add('mpath.set("comments", obj, val)', function () { + mpath.set('comments', o, 1); + }) + s.add('mpath.set("comments.1", obj, val)', function () { + mpath.set('comments.1', o, 1); + }) + s.add('mpath.set("comments.2.name", obj, val)', function () { + mpath.set('comments.2.name', o, 1); + }) + s.add('mpath.set("comments.2.comments.1.comments.0.val", obj, val)', function () { + mpath.set('comments.2.comments.1.comments.0.val', o, 1); + }) + s.add('mpath.set("comments.name", obj, val)', function () { + mpath.set('comments.name', o, 1); + }) + + s.on('start', function () { + console.log('starting...'); + out.write('*' + sha + ': ' + String(new Date()) + '\n'); + }); + s.on('cycle', function (e) { + var s = String(e.target); + console.log(s); + out.write(s + '\n'); + }) + s.on('complete', function () { + console.log('done') + out.end(''); + }) + s.run() +}) + diff --git a/5-3/node_modules/mongoose/node_modules/mpath/bench.log b/5-3/node_modules/mongoose/node_modules/mpath/bench.log new file mode 100644 index 0000000..e69de29 diff --git a/5-3/node_modules/mongoose/node_modules/mpath/bench.out b/5-3/node_modules/mongoose/node_modules/mpath/bench.out new file mode 100644 index 0000000..40d3c31 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/bench.out @@ -0,0 +1,69 @@ +*b566c26: Fri Mar 15 2013 14:14:04 GMT-0700 (PDT) +mpath.get("first", obj) x 3,827,405 ops/sec ±0.91% (90 runs sampled) +mpath.get("first.second", obj) x 4,930,222 ops/sec ±1.92% (91 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,070,837 ops/sec ±1.45% (97 runs sampled) +mpath.get("comments", obj) x 3,649,771 ops/sec ±1.71% (93 runs sampled) +mpath.get("comments.1", obj) x 3,846,728 ops/sec ±0.86% (94 runs sampled) +mpath.get("comments.2.name", obj) x 3,527,680 ops/sec ±0.95% (96 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,046,982 ops/sec ±0.80% (96 runs sampled) +mpath.get("comments.name", obj) x 625,546 ops/sec ±2.02% (82 runs sampled) +*e42bdb1: Fri Mar 15 2013 14:19:28 GMT-0700 (PDT) +mpath.get("first", obj) x 3,700,783 ops/sec ±1.30% (95 runs sampled) +mpath.get("first.second", obj) x 4,621,795 ops/sec ±0.86% (95 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,012,671 ops/sec ±1.21% (100 runs sampled) +mpath.get("comments", obj) x 3,677,694 ops/sec ±0.80% (96 runs sampled) +mpath.get("comments.1", obj) x 3,798,862 ops/sec ±0.81% (91 runs sampled) +mpath.get("comments.2.name", obj) x 3,489,356 ops/sec ±0.66% (98 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,004,076 ops/sec ±0.85% (99 runs sampled) +mpath.get("comments.name", obj) x 613,270 ops/sec ±1.33% (83 runs sampled) +*0521aac: Fri Mar 15 2013 16:37:16 GMT-0700 (PDT) +mpath.get("first", obj) x 3,834,755 ops/sec ±0.70% (100 runs sampled) +mpath.get("first.second", obj) x 4,999,965 ops/sec ±1.01% (98 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,125,953 ops/sec ±0.97% (100 runs sampled) +mpath.get("comments", obj) x 3,759,233 ops/sec ±0.81% (97 runs sampled) +mpath.get("comments.1", obj) x 3,894,893 ops/sec ±0.76% (96 runs sampled) +mpath.get("comments.2.name", obj) x 3,576,929 ops/sec ±0.68% (98 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,149,610 ops/sec ±0.67% (97 runs sampled) +mpath.get("comments.name", obj) x 629,259 ops/sec ±1.30% (87 runs sampled) +mpath.set("first", obj, val) x 2,869,477 ops/sec ±0.63% (97 runs sampled) +mpath.set("first.second", obj, val) x 2,418,751 ops/sec ±0.62% (98 runs sampled) +mpath.set("first.second.third.1.name", obj, val) x 2,313,099 ops/sec ±0.69% (94 runs sampled) +mpath.set("comments", obj, val) x 2,680,882 ops/sec ±0.76% (99 runs sampled) +mpath.set("comments.1", obj, val) x 2,401,829 ops/sec ±0.68% (98 runs sampled) +mpath.set("comments.2.name", obj, val) x 2,335,081 ops/sec ±1.07% (96 runs sampled) +mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,245,436 ops/sec ±0.76% (92 runs sampled) +mpath.set("comments.name", obj, val) x 2,356,278 ops/sec ±1.15% (100 runs sampled) +*97e85d3: Fri Mar 15 2013 16:39:21 GMT-0700 (PDT) +mpath.get("first", obj) x 3,837,614 ops/sec ±0.74% (99 runs sampled) +mpath.get("first.second", obj) x 4,991,779 ops/sec ±1.01% (94 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,078,455 ops/sec ±1.17% (96 runs sampled) +mpath.get("comments", obj) x 3,770,961 ops/sec ±0.45% (101 runs sampled) +mpath.get("comments.1", obj) x 3,832,814 ops/sec ±0.67% (92 runs sampled) +mpath.get("comments.2.name", obj) x 3,536,436 ops/sec ±0.49% (100 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,141,947 ops/sec ±0.72% (98 runs sampled) +mpath.get("comments.name", obj) x 667,898 ops/sec ±1.62% (85 runs sampled) +mpath.set("first", obj, val) x 2,642,517 ops/sec ±0.72% (98 runs sampled) +mpath.set("first.second", obj, val) x 2,502,124 ops/sec ±1.28% (99 runs sampled) +mpath.set("first.second.third.1.name", obj, val) x 2,426,804 ops/sec ±0.55% (99 runs sampled) +mpath.set("comments", obj, val) x 2,699,478 ops/sec ±0.85% (98 runs sampled) +mpath.set("comments.1", obj, val) x 2,494,454 ops/sec ±1.05% (96 runs sampled) +mpath.set("comments.2.name", obj, val) x 2,463,894 ops/sec ±0.86% (98 runs sampled) +mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,320,398 ops/sec ±0.82% (95 runs sampled) +mpath.set("comments.name", obj, val) x 2,512,408 ops/sec ±0.77% (95 runs sampled) +*2368a6d: Fri Mar 22 2013 14:07:40 GMT-0700 (PDT) +mpath.get("first", obj) x 3,932,284 ops/sec ±0.65% (98 runs sampled) +mpath.get("first.second", obj) x 4,982,307 ops/sec ±1.52% (91 runs sampled) +mpath.get("first.second.third.1.name", obj) x 3,094,619 ops/sec ±1.17% (95 runs sampled) +mpath.get("comments", obj) x 3,843,924 ops/sec ±0.76% (95 runs sampled) +mpath.get("comments.1", obj) x 3,864,491 ops/sec ±1.03% (96 runs sampled) +mpath.get("comments.2.name", obj) x 3,568,867 ops/sec ±0.79% (96 runs sampled) +mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,120,898 ops/sec ±0.94% (95 runs sampled) +mpath.get("comments.name", obj) x 623,508 ops/sec ±1.95% (80 runs sampled) +mpath.set("first", obj, val) x 2,780,551 ops/sec ±1.23% (97 runs sampled) +mpath.set("first.second", obj, val) x 2,227,087 ops/sec ±0.59% (97 runs sampled) +mpath.set("first.second.third.1.name", obj, val) x 2,145,494 ops/sec ±0.86% (96 runs sampled) +mpath.set("comments", obj, val) x 2,768,894 ops/sec ±0.90% (98 runs sampled) +mpath.set("comments.1", obj, val) x 2,202,542 ops/sec ±0.92% (95 runs sampled) +mpath.set("comments.2.name", obj, val) x 2,169,428 ops/sec ±1.10% (96 runs sampled) +mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,060,389 ops/sec ±0.72% (100 runs sampled) +mpath.set("comments.name", obj, val) x 2,128,875 ops/sec ±1.16% (97 runs sampled) diff --git a/5-3/node_modules/mongoose/node_modules/mpath/component.json b/5-3/node_modules/mongoose/node_modules/mpath/component.json new file mode 100644 index 0000000..53c2846 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/component.json @@ -0,0 +1,8 @@ +{ + "name": "mpath", + "version": "0.2.1", + "main": "lib/index.js", + "scripts": [ + "lib/index.js" + ] +} diff --git a/5-3/node_modules/mongoose/node_modules/mpath/index.js b/5-3/node_modules/mongoose/node_modules/mpath/index.js new file mode 100644 index 0000000..f7b65dd --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/index.js @@ -0,0 +1 @@ +module.exports = exports = require('./lib'); diff --git a/5-3/node_modules/mongoose/node_modules/mpath/lib/index.js b/5-3/node_modules/mongoose/node_modules/mpath/lib/index.js new file mode 100644 index 0000000..1b755b7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/lib/index.js @@ -0,0 +1,215 @@ +/** + * Returns the value of object `o` at the given `path`. + * + * ####Example: + * + * var obj = { + * comments: [ + * { title: 'exciting!', _doc: { title: 'great!' }} + * , { title: 'number dos' } + * ] + * } + * + * mpath.get('comments.0.title', o) // 'exciting!' + * mpath.get('comments.0.title', o, '_doc') // 'great!' + * mpath.get('comments.title', o) // ['exciting!', 'number dos'] + * + * // summary + * mpath.get(path, o) + * mpath.get(path, o, special) + * mpath.get(path, o, map) + * mpath.get(path, o, special, map) + * + * @param {String} path + * @param {Object} o + * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. + * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. + */ + +exports.get = function (path, o, special, map) { + var lookup; + + if ('function' == typeof special) { + if (special.length < 2) { + map = special; + special = undefined; + } else { + lookup = special; + special = undefined; + } + } + + map || (map = K); + + var parts = 'string' == typeof path + ? path.split('.') + : path + + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } + + var obj = o + , part; + + for (var i = 0; i < parts.length; ++i) { + part = parts[i]; + + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + // reading a property from the array items + var paths = parts.slice(i); + + return obj.map(function (item) { + return item + ? exports.get(paths, item, special || lookup, map) + : map(undefined); + }); + } + + if (lookup) { + obj = lookup(obj, part); + } else { + obj = special && obj[special] + ? obj[special][part] + : obj[part]; + } + + if (!obj) return map(obj); + } + + return map(obj); +} + +/** + * Sets the `val` at the given `path` of object `o`. + * + * @param {String} path + * @param {Anything} val + * @param {Object} o + * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. + * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. + */ + +exports.set = function (path, val, o, special, map, _copying) { + var lookup; + + if ('function' == typeof special) { + if (special.length < 2) { + map = special; + special = undefined; + } else { + lookup = special; + special = undefined; + } + } + + map || (map = K); + + var parts = 'string' == typeof path + ? path.split('.') + : path + + if (!Array.isArray(parts)) { + throw new TypeError('Invalid `path`. Must be either string or array'); + } + + if (null == o) return; + + // the existance of $ in a path tells us if the user desires + // the copying of an array instead of setting each value of + // the array to the one by one to matching positions of the + // current array. + var copy = _copying || /\$/.test(path) + , obj = o + , part + + for (var i = 0, len = parts.length - 1; i < len; ++i) { + part = parts[i]; + + if ('$' == part) { + if (i == len - 1) { + break; + } else { + continue; + } + } + + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + var paths = parts.slice(i); + if (!copy && Array.isArray(val)) { + for (var j = 0; j < obj.length && j < val.length; ++j) { + // assignment of single values of array + exports.set(paths, val[j], obj[j], special || lookup, map, copy); + } + } else { + for (var j = 0; j < obj.length; ++j) { + // assignment of entire value + exports.set(paths, val, obj[j], special || lookup, map, copy); + } + } + return; + } + + if (lookup) { + obj = lookup(obj, part); + } else { + obj = special && obj[special] + ? obj[special][part] + : obj[part]; + } + + if (!obj) return; + } + + // process the last property of the path + + part = parts[len]; + + // use the special property if exists + if (special && obj[special]) { + obj = obj[special]; + } + + // set the value on the last branch + if (Array.isArray(obj) && !/^\d+$/.test(part)) { + if (!copy && Array.isArray(val)) { + for (var item, j = 0; j < obj.length && j < val.length; ++j) { + item = obj[j]; + if (item) { + if (lookup) { + lookup(item, part, map(val[j])); + } else { + if (item[special]) item = item[special]; + item[part] = map(val[j]); + } + } + } + } else { + for (var j = 0; j < obj.length; ++j) { + item = obj[j]; + if (item) { + if (lookup) { + lookup(item, part, map(val)); + } else { + if (item[special]) item = item[special]; + item[part] = map(val); + } + } + } + } + } else { + if (lookup) { + lookup(obj, part, map(val)); + } else { + obj[part] = map(val); + } + } +} + +/*! + * Returns the value passed to it. + */ + +function K (v) { + return v; +} diff --git a/5-3/node_modules/mongoose/node_modules/mpath/package.json b/5-3/node_modules/mongoose/node_modules/mpath/package.json new file mode 100644 index 0000000..e0b5c89 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/package.json @@ -0,0 +1,53 @@ +{ + "name": "mpath", + "version": "0.2.1", + "description": "{G,S}et object values using MongoDB-like path notation", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mpath.git" + }, + "keywords": [ + "mongodb", + "path", + "get", + "set" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.8.1", + "benchmark": "~1.0.0" + }, + "_id": "mpath@0.2.1", + "dist": { + "shasum": "3a4e829359801de96309c27a6b2e102e89f9e96e", + "tarball": "http://registry.npmjs.org/mpath/-/mpath-0.2.1.tgz" + }, + "_from": "mpath@0.2.1", + "_npmVersion": "1.2.15", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "directories": {}, + "_shasum": "3a4e829359801de96309c27a6b2e102e89f9e96e", + "_resolved": "https://registry.npmjs.org/mpath/-/mpath-0.2.1.tgz", + "bugs": { + "url": "https://github.com/aheckmann/mpath/issues" + }, + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/aheckmann/mpath#readme" +} diff --git a/5-3/node_modules/mongoose/node_modules/mpath/test/index.js b/5-3/node_modules/mongoose/node_modules/mpath/test/index.js new file mode 100644 index 0000000..53bdbd7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpath/test/index.js @@ -0,0 +1,1790 @@ + +/** + * Test dependencies. + */ + +var mpath = require('../') +var assert = require('assert') + +/** + * logging helper + */ + +function log (o) { + console.log(); + console.log(require('util').inspect(o, false, 1000)); +} + +/** + * special path for override tests + */ + +var special = '_doc'; + +/** + * Tests + */ + +describe('mpath', function(){ + + /** + * test doc creator + */ + + function doc () { + var o = { first: { second: { third: [3,{ name: 'aaron' }, 9] }}}; + o.comments = [ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ]; + o.name = 'jiro'; + o.array = [ + { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] }} + , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; + o.arr = [ + { arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true } + ] + return o; + } + + describe('get', function(){ + var o = doc(); + + it('`path` must be a string or array', function(done){ + assert.throws(function () { + mpath.get({}, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(4, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(function(){}, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(/asdf/, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(Math, o); + }, /Must be either string or array/); + assert.throws(function () { + mpath.get(Buffer, o); + }, /Must be either string or array/); + assert.doesNotThrow(function () { + mpath.get('string', o); + }); + assert.doesNotThrow(function () { + mpath.get([], o); + }); + done(); + }) + + describe('without `special`', function(){ + it('works', function(done){ + assert.equal('jiro', mpath.get('name', o)); + + assert.deepEqual( + { second: { third: [3,{ name: 'aaron' }, 9] }} + , mpath.get('first', o) + ); + + assert.deepEqual( + { third: [3,{ name: 'aaron' }, 9] } + , mpath.get('first.second', o) + ); + + assert.deepEqual( + [3,{ name: 'aaron' }, 9] + , mpath.get('first.second.third', o) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o) + ); + + assert.deepEqual([ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], + mpath.get('comments', o)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o)); + assert.deepEqual('one', mpath.get('comments.0.name', o)); + assert.deepEqual('two', mpath.get('comments.1.name', o)); + assert.deepEqual('three', mpath.get('comments.2.name', o)); + + assert.deepEqual([{},{ comments: [{val: 'twoo'}]}] + , mpath.get('comments.2.comments', o)); + + assert.deepEqual({ comments: [{val: 'twoo'}]} + , mpath.get('comments.2.comments.1', o)); + + assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o)); + + done(); + }) + + it('handles array.property dot-notation', function(done){ + assert.deepEqual( + ['one', 'two', 'three'] + , mpath.get('comments.name', o) + ); + done(); + }) + + it('handles array.array notation', function(done){ + assert.deepEqual( + [undefined, undefined, [{}, {comments:[{val:'twoo'}]}]] + , mpath.get('comments.comments', o) + ); + done(); + }) + + it('handles prop.prop.prop.arrayProperty notation', function(done){ + assert.deepEqual( + [undefined, 'aaron', undefined] + , mpath.get('first.second.third.name', o) + ); + assert.deepEqual( + [1, 'aaron', 1] + , mpath.get('first.second.third.name', o, function (v) { + return undefined === v ? 1 : v; + }) + ); + done(); + }) + + it('handles array.prop.array', function(done){ + assert.deepEqual( + [ [{x: {b: [4,6,8]}}, { y: 10} ] + , [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] + , [{x: {b: null }}, { x: { b: [null, 1]}}] + , [{x: null }] + , [{y: 3 }] + , [3, 0, null] + , undefined + ] + , mpath.get('array.o.array', o) + ); + done(); + }) + + it('handles array.prop.array.index', function(done){ + assert.deepEqual( + [ {x: {b: [4,6,8]}} + , {x: {b: [1,2,3]}} + , {x: {b: null }} + , {x: null } + , {y: 3 } + , 3 + , undefined + ] + , mpath.get('array.o.array.0', o) + ); + done(); + }) + + it('handles array.prop.array.index.prop', function(done){ + assert.deepEqual( + [ {b: [4,6,8]} + , {b: [1,2,3]} + , {b: null } + , null + , undefined + , undefined + , undefined + ] + , mpath.get('array.o.array.0.x', o) + ); + done(); + }) + + it('handles array.prop.array.prop', function(done){ + assert.deepEqual( + [ [undefined, 10 ] + , [undefined, undefined, undefined] + , [undefined, undefined] + , [undefined] + , [3] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.y', o) + ); + assert.deepEqual( + [ [{b: [4,6,8]}, undefined] + , [{b: [1,2,3]}, {z: 10 }, {b: 'hi'}] + , [{b: null }, { b: [null, 1]}] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.x', o) + ); + done(); + }) + + it('handles array.prop.array.prop.prop', function(done){ + assert.deepEqual( + [ [[4,6,8], undefined] + , [[1,2,3], undefined, 'hi'] + , [null, [null, 1]] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.x.b', o) + ); + done(); + }) + + it('handles array.prop.array.prop.prop.index', function(done){ + assert.deepEqual( + [ [6, undefined] + , [2, undefined, 'i'] // undocumented feature (string indexing) + , [null, 1] + , [null] + , [undefined] + , [undefined, undefined, undefined] + , undefined + ] + , mpath.get('array.o.array.x.b.1', o) + ); + assert.deepEqual( + [ [6, 0] + , [2, 0, 'i'] // undocumented feature (string indexing) + , [null, 1] + , [null] + , [0] + , [0, 0, 0] + , 0 + ] + , mpath.get('array.o.array.x.b.1', o, function (v) { + return undefined === v ? 0 : v; + }) + ); + done(); + }) + + it('handles array.index.prop.prop', function(done){ + assert.deepEqual( + [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] + , mpath.get('array.1.o.array', o) + ); + assert.deepEqual( + ['hi','hi','hi'] + , mpath.get('array.1.o.array', o, function (v) { + if (Array.isArray(v)) { + return v.map(function (val) { + return 'hi'; + }) + } + return v; + }) + ); + done(); + }) + + it('handles array.array.index', function(done){ + assert.deepEqual( + [{ a: { c: 48 }}, undefined] + , mpath.get('arr.arr.1', o) + ); + assert.deepEqual( + ['woot', undefined] + , mpath.get('arr.arr.1', o, function (v) { + if (v && v.a && v.a.c) return 'woot'; + return v; + }) + ); + done(); + }) + + it('handles array.array.index.prop', function(done){ + assert.deepEqual( + [{ c: 48 }, 'woot'] + , mpath.get('arr.arr.1.a', o, function (v) { + if (undefined === v) return 'woot'; + return v; + }) + ); + assert.deepEqual( + [{ c: 48 }, undefined] + , mpath.get('arr.arr.1.a', o) + ); + mpath.set('arr.arr.1.a', [{c:49},undefined], o) + assert.deepEqual( + [{ c: 49 }, undefined] + , mpath.get('arr.arr.1.a', o) + ); + mpath.set('arr.arr.1.a', [{c:48},undefined], o) + done(); + }) + + it('handles array.array.index.prop.prop', function(done){ + assert.deepEqual( + [48, undefined] + , mpath.get('arr.arr.1.a.c', o) + ); + assert.deepEqual( + [48, 'woot'] + , mpath.get('arr.arr.1.a.c', o, function (v) { + if (undefined === v) return 'woot'; + return v; + }) + ); + done(); + }) + + }) + + describe('with `special`', function(){ + describe('that is a string', function(){ + it('works', function(done){ + assert.equal('jiro', mpath.get('name', o, special)); + + assert.deepEqual( + { second: { third: [3,{ name: 'aaron' }, 9] }} + , mpath.get('first', o, special) + ); + + assert.deepEqual( + { third: [3,{ name: 'aaron' }, 9] } + , mpath.get('first.second', o, special) + ); + + assert.deepEqual( + [3,{ name: 'aaron' }, 9] + , mpath.get('first.second.third', o, special) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o, special) + ); + + assert.deepEqual( + 4 + , mpath.get('first.second.third.0', o, special, function (v) { + return 3 === v ? 4 : v; + }) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o, special) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o, special) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o, special) + ); + + assert.deepEqual([ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], + mpath.get('comments', o, special)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); + assert.deepEqual('one', mpath.get('comments.0.name', o, special)); + assert.deepEqual('2', mpath.get('comments.1.name', o, special)); + assert.deepEqual('3', mpath.get('comments.2.name', o, special)); + assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function (v) { + return '3' === v ? 'nice' : v; + })); + + assert.deepEqual([{},{ _doc: { comments: [{ val: 2 }] }}] + , mpath.get('comments.2.comments', o, special)); + + assert.deepEqual({ _doc: { comments: [{val: 2}]}} + , mpath.get('comments.2.comments.1', o, special)); + + assert.deepEqual(2, mpath.get('comments.2.comments.1.comments.0.val', o, special)); + done(); + }) + + it('handles array.property dot-notation', function(done){ + assert.deepEqual( + ['one', '2', '3'] + , mpath.get('comments.name', o, special) + ); + assert.deepEqual( + ['one', 2, '3'] + , mpath.get('comments.name', o, special, function (v) { + return '2' === v ? 2 : v + }) + ); + done(); + }) + + it('handles array.array notation', function(done){ + assert.deepEqual( + [undefined, undefined, [{}, {_doc: { comments:[{val:2}]}}]] + , mpath.get('comments.comments', o, special) + ); + done(); + }) + + it('handles array.array.index.array', function(done){ + assert.deepEqual( + [undefined, undefined, [{val:2}]] + , mpath.get('comments.comments.1.comments', o, special) + ); + done(); + }) + + it('handles array.array.index.array.prop', function(done){ + assert.deepEqual( + [undefined, undefined, [2]] + , mpath.get('comments.comments.1.comments.val', o, special) + ); + assert.deepEqual( + ['nil', 'nil', [2]] + , mpath.get('comments.comments.1.comments.val', o, special, function (v) { + return undefined === v ? 'nil' : v; + }) + ); + done(); + }) + }) + + describe('that is a function', function(){ + var special = function (obj, key) { + return obj[key] + } + + it('works', function(done){ + assert.equal('jiro', mpath.get('name', o, special)); + + assert.deepEqual( + { second: { third: [3,{ name: 'aaron' }, 9] }} + , mpath.get('first', o, special) + ); + + assert.deepEqual( + { third: [3,{ name: 'aaron' }, 9] } + , mpath.get('first.second', o, special) + ); + + assert.deepEqual( + [3,{ name: 'aaron' }, 9] + , mpath.get('first.second.third', o, special) + ); + + assert.deepEqual( + 3 + , mpath.get('first.second.third.0', o, special) + ); + + assert.deepEqual( + 4 + , mpath.get('first.second.third.0', o, special, function (v) { + return 3 === v ? 4 : v; + }) + ); + + assert.deepEqual( + 9 + , mpath.get('first.second.third.2', o, special) + ); + + assert.deepEqual( + { name: 'aaron' } + , mpath.get('first.second.third.1', o, special) + ); + + assert.deepEqual( + 'aaron' + , mpath.get('first.second.third.1.name', o, special) + ); + + assert.deepEqual([ + { name: 'one' } + , { name: 'two', _doc: { name: '2' }} + , { name: 'three' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], + mpath.get('comments', o, special)); + + assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); + assert.deepEqual('one', mpath.get('comments.0.name', o, special)); + assert.deepEqual('two', mpath.get('comments.1.name', o, special)); + assert.deepEqual('three', mpath.get('comments.2.name', o, special)); + assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function (v) { + return 'three' === v ? 'nice' : v; + })); + + assert.deepEqual([{},{ comments: [{ val: 'twoo' }] }] + , mpath.get('comments.2.comments', o, special)); + + assert.deepEqual({ comments: [{val: 'twoo'}]} + , mpath.get('comments.2.comments.1', o, special)); + + assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o, special)); + + var overide = false; + assert.deepEqual('twoo', mpath.get('comments.8.comments.1.comments.0.val', o, function (obj, path) { + if (Array.isArray(obj) && 8 == path) { + overide = true; + return obj[2]; + } + return obj[path]; + })); + assert.ok(overide); + + done(); + }) + + it('in combination with map', function(done){ + var special = function (obj, key) { + if (Array.isArray(obj)) return obj[key]; + return obj.mpath; + } + var map = function (val) { + return 'convert' == val + ? 'mpath' + : val; + } + var o = { mpath: [{ mpath: 'converse' }, { mpath: 'convert' }] } + + assert.equal('mpath', mpath.get('something.1.kewl', o, special, map)); + done(); + }) + }) + }) + }) + + describe('set', function(){ + describe('without `special`', function(){ + var o = doc(); + + it('works', function(done){ + mpath.set('name', 'a new val', o, function (v) { + return 'a new val' === v ? 'changed' : v; + }); + assert.deepEqual('changed', o.name); + + mpath.set('name', 'changed', o); + assert.deepEqual('changed', o.name); + + mpath.set('first.second.third', [1,{name:'x'},9], o); + assert.deepEqual([1,{name:'x'},9], o.first.second.third); + + mpath.set('first.second.third.1.name', 'y', o) + assert.deepEqual([1,{name:'y'},9], o.first.second.third); + + mpath.set('comments.1.name', 'ttwwoo', o); + assert.deepEqual({ name: 'ttwwoo', _doc: { name: '2' }}, o.comments[1]); + + mpath.set('comments.2.comments.1.comments.0.expand', 'added', o); + assert.deepEqual( + { val: 'twoo', expand: 'added'} + , o.comments[2].comments[1].comments[0]); + + mpath.set('comments.2.comments.1.comments.2', 'added', o); + assert.equal(3, o.comments[2].comments[1].comments.length); + assert.deepEqual( + { val: 'twoo', expand: 'added'} + , o.comments[2].comments[1].comments[0]); + assert.deepEqual( + undefined + , o.comments[2].comments[1].comments[1]); + assert.deepEqual( + 'added' + , o.comments[2].comments[1].comments[2]); + + done(); + }) + + describe('array.path', function(){ + describe('with single non-array value', function(){ + it('works', function(done){ + mpath.set('arr.yep', false, o, function (v) { + return false === v ? true: v; + }); + assert.deepEqual([ + { yep: true, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true } + ], o.arr); + + mpath.set('arr.yep', false, o); + + assert.deepEqual([ + { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: false } + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('that are equal in length', function(done){ + mpath.set('arr.yep', ['one',2], o, function (v) { + return 'one' === v ? 1 : v; + }); + assert.deepEqual([ + { yep: 1, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + mpath.set('arr.yep', ['one',2], o); + + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + + done(); + }) + + it('that is less than length', function(done){ + mpath.set('arr.yep', [47], o, function (v) { + return 47 === v ? 4 : v; + }); + assert.deepEqual([ + { yep: 4, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + + mpath.set('arr.yep', [47], o); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 2 } + ], o.arr); + + done(); + }) + + it('that is greater than length', function(done){ + mpath.set('arr.yep', [5,6,7], o, function (v) { + return 5 === v ? 'five' : v; + }); + assert.deepEqual([ + { yep: 'five', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 6 } + ], o.arr); + + mpath.set('arr.yep', [5,6,7], o); + assert.deepEqual([ + { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 6 } + ], o.arr); + + done(); + }) + }) + }) + + describe('array.$.path', function(){ + describe('with single non-array value', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', {xtra: 'double good'}, o, function (v) { + return v && v.xtra ? 'hi' : v; + }); + assert.deepEqual([ + { yep: 'hi', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 'hi'} + ], o.arr); + + mpath.set('arr.$.yep', {xtra: 'double good'}, o); + assert.deepEqual([ + { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: {xtra:'double good'}} + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', [15], o, function (v) { + return v.length === 1 ? [] : v; + }); + assert.deepEqual([ + { yep: [], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: []} + ], o.arr); + + mpath.set('arr.$.yep', [15], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: [15]} + ], o.arr); + + done(); + }) + }) + }) + + describe('array.index.path', function(){ + it('works', function(done){ + mpath.set('arr.1.yep', 0, o, function (v) { + return 0 === v ? 'zero' : v; + }); + assert.deepEqual([ + { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 'zero' } + ], o.arr); + + mpath.set('arr.1.yep', 0, o); + assert.deepEqual([ + { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.e', 35, o, function (v) { + return 35 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 3}, { a: { c: 48 }, e: 3}, { d: 'yep', e: 3 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.e', 35, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.e', ['a','b'], o, function (v) { + return 'a' === v ? 'x' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 'x'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.e', ['a','b'], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.a.b', 36, o, function (v) { + return 36 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 3 }, e: 'a'}, { a: { c: 48, b: 3 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.a.b', 36, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.a.b', [1,2,3,4], o, function (v) { + return 2 === v ? 'two' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 'two' }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.a.b', [1,2,3,4], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.$.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.$.a.b', '$', o, function (v) { + return '$' === v ? 'dolla billz' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: 'dolla billz' }, e: 'a'}, { a: { c: 48, b: 'dolla billz' }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', '$', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.$.a.b', [1], o, function (v) { + return Array.isArray(v) ? {} : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', [1], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + }) + + describe('array.array.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.0.a', 'single', o, function (v) { + return 'single' === v ? 'double' : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'double', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.arr.0.a', 'single', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, function (v) { + return 4 === v ? 3 : v; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 3, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: false } + ], o.arr); + + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: false } + ], o.arr); + + done(); + }) + }) + + describe('array.array.$.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.$.0.a', 'singles', o, function (v) { + return 0; + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 0, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('arr.arr.$.0.a', 'singles', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + mpath.set('$.arr.arr.0.a', 'single', o); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0 } + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, function (v) { + return 'nope' + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: 'nope', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + done(); + }) + }) + + describe('array.array.path.index', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.a.7', 47, o, function (v) { + return 1 + }); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,1], e: 'a'}, { a: { c: 48, b: [1], '7': 1 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + mpath.set('arr.arr.a.7', 47, o); + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0} + ], o.arr); + + done(); + }) + it('with array', function(done){ + o.arr[1].arr = [{ a: [] }, { a: [] }, { a: null }]; + mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o); + + var a1 = []; + var a2 = []; + a1[7] = undefined; + a2[7] = 'woot'; + + assert.deepEqual([ + { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } + , { yep: 0, arr: [{a:a1},{a:a2},{a:null}] } + ], o.arr); + + done(); + }) + }) + + describe('handles array.array.path', function(){ + it('with single', function(done){ + o.arr[1].arr = [{},{}]; + assert.deepEqual([{},{}], o.arr[1].arr); + o.arr.push({ arr: 'something else' }); + o.arr.push({ arr: ['something else'] }); + o.arr.push({ arr: [[]] }); + o.arr.push({ arr: [5] }); + + var weird = []; + weird.e = 'xmas'; + + // test + mpath.set('arr.arr.e', 47, o, function (v) { + return 'xmas' + }); + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 'xmas'} + , { a: { c: 48, b: [1], '7': 46 }, e: 'xmas'} + , { d: 'yep', e: 'xmas' } + ] + } + , { yep: 0, arr: [{e: 'xmas'}, {e:'xmas'}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + weird.e = 47; + + mpath.set('arr.arr.e', 47, o); + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 47} + , { a: { c: 48, b: [1], '7': 46 }, e: 47} + , { d: 'yep', e: 47 } + ] + } + , { yep: 0, arr: [{e: 47}, {e:47}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + done(); + }) + it('with arrays', function(done){ + mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, function (v) { + return 10; + }); + + var weird = []; + weird.e = 10; + + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 10} + , { a: { c: 48, b: [1], '7': 46 }, e: 10} + , { d: 'yep', e: 10 } + ] + } + , { yep: 0, arr: [{e: 10}, {e:10}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o); + + weird.e = 6; + + assert.deepEqual([ + { yep: [15], arr: [ + { a: [4,8,15,16,23,42,108,null], e: 1} + , { a: { c: 48, b: [1], '7': 46 }, e: 2} + , { d: 'yep', e: 3 } + ] + } + , { yep: 0, arr: [{e: 4}, {e:5}] } + , { arr: 'something else' } + , { arr: ['something else'] } + , { arr: [weird] } + , { arr: [5] } + ] + , o.arr); + + done(); + }) + }) + }) + + describe('with `special`', function(){ + var o = doc(); + + it('works', function(done){ + mpath.set('name', 'chan', o, special, function (v) { + return 'hi'; + }); + assert.deepEqual('hi', o.name); + + mpath.set('name', 'changer', o, special); + assert.deepEqual('changer', o.name); + + mpath.set('first.second.third', [1,{name:'y'},9], o, special); + assert.deepEqual([1,{name:'y'},9], o.first.second.third); + + mpath.set('first.second.third.1.name', 'z', o, special) + assert.deepEqual([1,{name:'z'},9], o.first.second.third); + + mpath.set('comments.1.name', 'ttwwoo', o, special); + assert.deepEqual({ name: 'two', _doc: { name: 'ttwwoo' }}, o.comments[1]); + + mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special, function (v) { + return 'super' + }); + assert.deepEqual( + { val: 2, expander: 'super'} + , o.comments[2]._doc.comments[1]._doc.comments[0]); + + mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special); + assert.deepEqual( + { val: 2, expander: 'adder'} + , o.comments[2]._doc.comments[1]._doc.comments[0]); + + mpath.set('comments.2.comments.1.comments.2', 'set', o, special); + assert.equal(3, o.comments[2]._doc.comments[1]._doc.comments.length); + assert.deepEqual( + { val: 2, expander: 'adder'} + , o.comments[2]._doc.comments[1]._doc.comments[0]); + assert.deepEqual( + undefined + , o.comments[2]._doc.comments[1]._doc.comments[1]); + assert.deepEqual( + 'set' + , o.comments[2]._doc.comments[1]._doc.comments[2]); + done(); + }) + + describe('array.path', function(){ + describe('with single non-array value', function(){ + it('works', function(done){ + o.arr[1]._doc = { special: true } + + mpath.set('arr.yep', false, o, special, function (v) { + return 'yes'; + }); + assert.deepEqual([ + { yep: 'yes', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 'yes'}} + ], o.arr); + + mpath.set('arr.yep', false, o, special); + assert.deepEqual([ + { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: false }} + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('that are equal in length', function(done){ + mpath.set('arr.yep', ['one',2], o, special, function (v) { + return 2 === v ? 20 : v; + }); + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 20}} + ], o.arr); + + mpath.set('arr.yep', ['one',2], o, special); + assert.deepEqual([ + { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + done(); + }) + + it('that is less than length', function(done){ + mpath.set('arr.yep', [47], o, special, function (v) { + return 80; + }); + assert.deepEqual([ + { yep: 80, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + mpath.set('arr.yep', [47], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + // add _doc to first element + o.arr[0]._doc = { yep: 46, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } + + mpath.set('arr.yep', [20], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 20, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 2}} + ], o.arr); + + done(); + }) + + it('that is greater than length', function(done){ + mpath.set('arr.yep', [5,6,7], o, special, function () { + return 'x'; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 'x', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 'x'}} + ], o.arr); + + mpath.set('arr.yep', [5,6,7], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 6}} + ], o.arr); + + done(); + }) + }) + }) + + describe('array.$.path', function(){ + describe('with single non-array value', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', {xtra: 'double good'}, o, special, function (v) { + return 9; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: 9, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 9}} + ], o.arr); + + mpath.set('arr.$.yep', {xtra: 'double good'}, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: {xtra:'double good'}}} + ], o.arr); + + done(); + }) + }) + describe('with array of values', function(){ + it('copies the value to each item in array', function(done){ + mpath.set('arr.$.yep', [15], o, special, function (v) { + return 'array' + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: 'array', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 'array'}} + ], o.arr); + + mpath.set('arr.$.yep', [15], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: [15]}} + ], o.arr); + + done(); + }) + }) + }) + + describe('array.index.path', function(){ + it('works', function(done){ + mpath.set('arr.1.yep', 0, o, special, function (v) { + return 1; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 1}} + ], o.arr); + + mpath.set('arr.1.yep', 0, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.e', 35, o, special, function (v) { + return 30 + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 30}, { a: { c: 48 }, e: 30}, { d: 'yep', e: 30 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.e', 35, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.e', ['a','b'], o, special, function (v) { + return 'a' === v ? 'A' : v; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'A'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.e', ['a','b'], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.a.b', 36, o, special, function (v) { + return 20 + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 20 }, e: 'a'}, { a: { c: 48, b: 20 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.a.b', 36, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special, function (v) { + return v*2; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 2 }, e: 'a'}, { a: { c: 48, b: 4 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.index.array.$.path.path', function(){ + it('with single value', function(done){ + mpath.set('arr.0.arr.$.a.b', '$', o, special, function (v) { + return 'dollaz' + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: 'dollaz' }, e: 'a'}, { a: { c: 48, b: 'dollaz' }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', '$', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.0.arr.$.a.b', [1], o, special, function (v) { + return {}; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.0.arr.$.a.b', [1], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.array.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.0.a', 'single', o, special, function (v) { + return 88; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 88, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.0.a', 'single', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special, function (v) { + return v*2; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 8, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.array.$.index.path', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.$.0.a', 'singles', o, special, function (v) { + return v.toUpperCase(); + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'SINGLES', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.$.0.a', 'singles', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('$.arr.arr.0.a', 'single', o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special, function (v) { + return Array + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: Array, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('array.array.path.index', function(){ + it('with single value', function(done){ + mpath.set('arr.arr.a.7', 47, o, special, function (v) { + return Object; + }); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,Object], e: 'a'}, { a: { c: 48, b: [1], '7': Object }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.a.7', 47, o, special); + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { special: true, yep: 0}} + ], o.arr); + + done(); + }) + it('with array', function(done){ + o.arr[1]._doc.arr = [{ a: [] }, { a: [] }, { a: null }]; + mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special, function (v) { + return undefined === v ? 'nope' : v; + }); + + var a1 = []; + var a2 = []; + a1[7] = 'nope'; + a2[7] = 'woot'; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} + ], o.arr); + + mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special); + + a1[7] = undefined; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } + , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} + ], o.arr); + + done(); + }) + }) + + describe('handles array.array.path', function(){ + it('with single', function(done){ + o.arr[1]._doc.arr = [{},{}]; + assert.deepEqual([{},{}], o.arr[1]._doc.arr); + o.arr.push({ _doc: { arr: 'something else' }}); + o.arr.push({ _doc: { arr: ['something else'] }}); + o.arr.push({ _doc: { arr: [[]] }}); + o.arr.push({ _doc: { arr: [5] }}); + + // test + mpath.set('arr.arr.e', 47, o, special); + + var weird = []; + weird.e = 47; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { + yep: [15] + , arr: [ + { a: [4,8,15,16,23,42,108,null], e: 47} + , { a: { c: 48, b: [1], '7': 46 }, e: 47} + , { d: 'yep', e: 47 } + ] + } + } + , { yep: true + , _doc: { + arr: [ + {e:47} + , {e:47} + ] + , special: true + , yep: 0 + } + } + , { _doc: { arr: 'something else' }} + , { _doc: { arr: ['something else'] }} + , { _doc: { arr: [weird] }} + , { _doc: { arr: [5] }} + ] + , o.arr); + + done(); + }) + it('with arrays', function(done){ + mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, special); + + var weird = []; + weird.e = 6; + + assert.deepEqual([ + { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] + , _doc: { + yep: [15] + , arr: [ + { a: [4,8,15,16,23,42,108,null], e: 1} + , { a: { c: 48, b: [1], '7': 46 }, e: 2} + , { d: 'yep', e: 3 } + ] + } + } + , { yep: true + , _doc: { + arr: [ + {e:4} + , {e:5} + ] + , special: true + , yep: 0 + } + } + , { _doc: { arr: 'something else' }} + , { _doc: { arr: ['something else'] }} + , { _doc: { arr: [weird] }} + , { _doc: { arr: [5] }} + ] + , o.arr); + + done(); + }) + }) + + describe('that is a function', function(){ + describe('without map', function(){ + it('works on array value', function(done){ + var o = { hello: { world: [{ how: 'are' }, { you: '?' }] }}; + var special = function (obj, key, val) { + if (val) { + obj[key] = val; + } else { + return 'thing' == key + ? obj.world + : obj[key] + } + } + mpath.set('hello.thing.how', 'arrrr', o, special); + assert.deepEqual(o, { hello: { world: [{ how: 'arrrr' }, { you: '?', how: 'arrrr' }] }}); + done(); + }) + it('works on non-array value', function(done){ + var o = { hello: { world: { how: 'are you' }}}; + var special = function (obj, key, val) { + if (val) { + obj[key] = val; + } else { + return 'thing' == key + ? obj.world + : obj[key] + } + } + mpath.set('hello.thing.how', 'RU', o, special); + assert.deepEqual(o, { hello: { world: { how: 'RU' }}}); + done(); + }) + }) + it('works with map', function(done){ + var o = { hello: { world: [{ how: 'are' }, { you: '?' }] }}; + var special = function (obj, key, val) { + if (val) { + obj[key] = val; + } else { + return 'thing' == key + ? obj.world + : obj[key] + } + } + var map = function (val) { + return 'convert' == val + ? 'ºº' + : val + } + mpath.set('hello.thing.how', 'convert', o, special, map); + assert.deepEqual(o, { hello: { world: [{ how: 'ºº' }, { you: '?', how: 'ºº' }] }}); + done(); + }) + }) + + }) + + describe('get/set integration', function(){ + var o = doc(); + + it('works', function(done){ + var vals = mpath.get('array.o.array.x.b', o); + + vals[0][0][2] = 10; + vals[1][0][1] = 0; + vals[1][1] = 'Rambaldi'; + vals[1][2] = [12,14]; + vals[2] = [{changed:true}, [null, ['changed','to','array']]]; + + mpath.set('array.o.array.x.b', vals, o); + + var t = [ + { o: { array: [{x: {b: [4,6,10]}}, { y: 10} ] }} + , { o: { array: [{x: {b: [1,0,3]}}, { x: {b:'Rambaldi',z: 10 }}, { x: {b: [12,14]}}] }} + , { o: { array: [{x: {b: {changed:true}}}, { x: { b: [null, ['changed','to','array']]}}]}} + , { o: { array: [{x: null }] }} + , { o: { array: [{y: 3 }] }} + , { o: { array: [3, 0, null] }} + , { o: { name: 'ha' }} + ]; + assert.deepEqual(t, o.array); + done(); + }) + + it('array.prop', function(done){ + mpath.set('comments.name', ['this', 'was', 'changed'], o); + + assert.deepEqual([ + { name: 'this' } + , { name: 'was', _doc: { name: '2' }} + , { name: 'changed' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ], o.comments); + + mpath.set('comments.name', ['also', 'changed', 'this'], o, special); + + assert.deepEqual([ + { name: 'also' } + , { name: 'was', _doc: { name: 'changed' }} + , { name: 'changed' + , comments: [{},{ comments: [{val: 'twoo'}]}] + , _doc: { name: 'this', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} + ], o.comments); + + done(); + }) + + }) + + describe('multiple $ use', function(){ + var o = doc(); + it('is ok', function(done){ + assert.doesNotThrow(function () { + mpath.set('arr.$.arr.$.a', 35, o); + }); + done(); + }) + }) + + it('ignores setting a nested path that doesnt exist', function(done){ + var o = doc(); + assert.doesNotThrow(function(){ + mpath.set('thing.that.is.new', 10, o); + }) + done(); + }) + }) + +}) diff --git a/5-3/node_modules/mongoose/node_modules/mpromise/.npmignore b/5-3/node_modules/mongoose/node_modules/mpromise/.npmignore new file mode 100644 index 0000000..e86496f --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpromise/.npmignore @@ -0,0 +1,4 @@ +*.sw* +node_modules/ +.DS_Store +.idea \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mpromise/.travis.yml b/5-3/node_modules/mongoose/node_modules/mpromise/.travis.yml new file mode 100644 index 0000000..d63ba09 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpromise/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 diff --git a/5-3/node_modules/mongoose/node_modules/mpromise/History.md b/5-3/node_modules/mongoose/node_modules/mpromise/History.md new file mode 100644 index 0000000..12c0dc3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpromise/History.md @@ -0,0 +1,80 @@ +0.5.5 / 2014-09-19 +================== + + * change `end()` semantics + * add `catch()` as in ES6 + +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/5-3/node_modules/mongoose/node_modules/mpromise/LICENSE b/5-3/node_modules/mongoose/node_modules/mpromise/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpromise/LICENSE @@ -0,0 +1,22 @@ +(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/5-3/node_modules/mongoose/node_modules/mpromise/README.md b/5-3/node_modules/mongoose/node_modules/mpromise/README.md new file mode 100644 index 0000000..2906f56 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpromise/README.md @@ -0,0 +1,224 @@ +#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/5-3/node_modules/mongoose/node_modules/mpromise/lib/promise.js b/5-3/node_modules/mongoose/node_modules/mpromise/lib/promise.js new file mode 100644 index 0000000..3cb4419 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpromise/lib/promise.js @@ -0,0 +1,445 @@ +'use strict'; +var util = require('util'); +var EventEmitter = require('events').EventEmitter; +function toArray(arr, start, end) { + return Array.prototype.slice.call(arr, start, end) +} +function strongUnshift(x, arrLike) { + var arr = toArray(arrLike); + arr.unshift(x); + return arr; +} + + +/** + * MPromise 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) { + this.emitter = new EventEmitter(); + this.emitted = {}; + this.ended = false; + if ('function' == typeof back) { + this.ended = true; + this.onResolve(back); + } +} + + +/* + * Module exports. + */ +module.exports = Promise; + + +/*! + * event names + */ +Promise.SUCCESS = 'fulfill'; +Promise.FAILURE = 'reject'; + + +/** + * 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 {MPromise} this + * @api private + */ +Promise.prototype.on = function (event, callback) { + if (this.emitted[event]) + callback.apply(undefined, this.emitted[event]); + else + this.emitter.on(event, callback); + + return this; +}; + + +/** + * Keeps track of emitted events to run them on `on`. + * + * @api private + */ +Promise.prototype.safeEmit = function (event) { + // ensures a promise can't be fulfill() or reject() more than once + if (event == Promise.SUCCESS || event == Promise.FAILURE) { + if (this.emitted[Promise.SUCCESS] || this.emitted[Promise.FAILURE]) { + return this; + } + this.emitted[event] = toArray(arguments, 1); + } + + this.emitter.emit.apply(this.emitter, arguments); + return this; +}; + + +/** + * @api private + */ +Promise.prototype.hasRejectListeners = function () { + return EventEmitter.listenerCount(this.emitter, Promise.FAILURE) > 0; +}; + + +/** + * 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 () { + return this.safeEmit.apply(this, strongUnshift(Promise.SUCCESS, arguments)); +}; + + +/** + * 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 {MPromise} this + */ +Promise.prototype.reject = function (reason) { + if (this.ended && !this.hasRejectListeners()) + throw reason; + return this.safeEmit(Promise.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 {MPromise} 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(Promise.SUCCESS, fn); +}; + + +/** + * Adds a listener to the FAILURE event. + * + * @return {MPromise} 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(Promise.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...) {} + * + * Also marks the promise as `end`ed, since it's the common use-case, and yet has no + * side effects unless `fn` is undefined or null. + * + * @param {Function} fn + * @return {MPromise} this + */ +Promise.prototype.onResolve = function (fn) { + if (!fn) return this; + if ('function' != typeof fn) throw new TypeError("fn should be a function"); + this.on(Promise.FAILURE, function (err) { fn.call(this, err); }); + this.on(Promise.SUCCESS, function () { fn.apply(this, strongUnshift(null, arguments)); }); + 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 {MPromise} newPromise + */ +Promise.prototype.then = function (onFulfill, onReject) { + var newPromise = new Promise; + + if ('function' == typeof onFulfill) { + this.onFulfill(handler(newPromise, onFulfill)); + } else { + this.onFulfill(newPromise.fulfill.bind(newPromise)); + } + + if ('function' == typeof onReject) { + this.onReject(handler(newPromise, onReject)); + } else { + this.onReject(newPromise.reject.bind(newPromise)); + } + + return newPromise; +}; + + +function handler(promise, fn) { + function newTickHandler() { + var pDomain = promise.emitter.domain; + if (pDomain && pDomain !== process.domain) pDomain.enter(); + try { + var x = fn.apply(undefined, boundHandler.args); + } catch (err) { + promise.reject(err); + return; + } + resolve(promise, x); + } + function boundHandler() { + boundHandler.args = arguments; + process.nextTick(newTickHandler); + } + return boundHandler; +} + + +function resolve(promise, x) { + function fulfillOnce() { + if (done++) return; + resolve.apply(undefined, strongUnshift(promise, arguments)); + } + function rejectOnce(reason) { + if (done++) return; + promise.reject(reason); + } + + if (promise === x) { + promise.reject(new TypeError("promise and x are the same")); + return; + } + var rest = toArray(arguments, 1); + var type = typeof x; + if ('undefined' == type || null == x || !('object' == type || 'function' == type)) { + promise.fulfill.apply(promise, rest); + return; + } + + try { + var theThen = x.then; + } catch (err) { + promise.reject(err); + return; + } + + if ('function' != typeof theThen) { + promise.fulfill.apply(promise, rest); + return; + } + + var done = 0; + try { + var ret = theThen.call(x, fulfillOnce, rejectOnce); + return ret; + } catch (err) { + if (done++) return; + promise.reject(err); + } +} + + +/** + * 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 {MPromise} this + */ +Promise.prototype.end = Promise.prototype['catch'] = function (onReject) { + if (!onReject && !this.hasRejectListeners()) + onReject = function idRejector(e) { throw e; }; + 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 {MPromise} p + * @param {String} name + * @return {MPromise} this + */ +Promise.trace = function (p, name) { + p.then( + function () { + console.log("%s fulfill %j", name, toArray(arguments)); + }, + function () { + console.log("%s reject %j", name, toArray(arguments)); + } + ) +}; + + +Promise.prototype.chain = function (p2) { + var p1 = this; + p1.onFulfill(p2.fulfill.bind(p2)); + p1.onReject(p2.reject.bind(p2)); + return p2; +}; + + +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; +}; + + +/* This is for the A+ tests, but it's very useful as well */ +Promise.fulfilled = function fulfilled() { var p = new Promise; p.fulfill.apply(p, arguments); return p; }; +Promise.rejected = function rejected(reason) { return new Promise().reject(reason); }; +Promise.deferred = function deferred() { + var p = new Promise; + return { + promise: p, + reject: p.reject.bind(p), + resolve: p.fulfill.bind(p), + callback: p.resolve.bind(p) + } +}; +/* End A+ tests adapter bit */ diff --git a/5-3/node_modules/mongoose/node_modules/mpromise/package.json b/5-3/node_modules/mongoose/node_modules/mpromise/package.json new file mode 100644 index 0000000..4cfcb7c --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpromise/package.json @@ -0,0 +1,66 @@ +{ + "name": "mpromise", + "version": "0.5.5", + "description": "Promises A+ conformant implementation", + "main": "lib/promise.js", + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "promises-aplus-tests": "2.1.0", + "mocha": "1.21.4" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/aheckmann/mpromise.git" + }, + "keywords": [ + "promise", + "mongoose", + "aplus", + "a+", + "plus" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "contributors": [ + { + "name": "Refael Ackermann", + "email": "refack@gmail", + "url": "http://node.org.il/" + } + ], + "license": "MIT", + "gitHead": "c8842ff1065e9fceef0eef7e97bdb291b7c2550e", + "bugs": { + "url": "https://github.com/aheckmann/mpromise/issues" + }, + "homepage": "https://github.com/aheckmann/mpromise", + "_id": "mpromise@0.5.5", + "_shasum": "f5b24259d763acc2257b0a0c8c6d866fd51732e6", + "_from": "mpromise@0.5.5", + "_npmVersion": "2.0.0-beta.2", + "_npmUser": { + "name": "refack", + "email": "refael@empeeric.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "refack", + "email": "refael@empeeric.com" + } + ], + "dist": { + "shasum": "f5b24259d763acc2257b0a0c8c6d866fd51732e6", + "tarball": "http://registry.npmjs.org/mpromise/-/mpromise-0.5.5.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mpromise/-/mpromise-0.5.5.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js b/5-3/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js new file mode 100644 index 0000000..a6a6be7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js @@ -0,0 +1,28 @@ +var Promise = require('../') + , Domain = require('domain').Domain + , assert = require('assert'); + + +describe("domains", function () { + it("exceptions should not breakout of domain boundaries", function (done) { + if (process.version.indexOf('v0.10') != 0) return done(); + var d = new Domain; + d.on('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(); + }); + + process.nextTick(function () { + p.fulfill(); + }); + }); +}); diff --git a/5-3/node_modules/mongoose/node_modules/mpromise/test/promise.test.js b/5-3/node_modules/mongoose/node_modules/mpromise/test/promise.test.js new file mode 100644 index 0000000..bf3044d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpromise/test/promise.test.js @@ -0,0 +1,554 @@ +/*global describe,it */ +/** + * Module dependencies. + */ + +var assert = require('assert'); +var MPromise = require('../'); + +/** + * Test. + */ + +describe('promise', function () { + it('events fire right after fulfill()', function (done) { + var promise = new MPromise() + , 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 MPromise() + , 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 MPromise(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 MPromise() + , called = 0; + + promise.fulfill('woot'); + + promise.onResolve(function (err, data) { + assert.equal(data, 'woot'); + called++; + }); + + promise.onResolve(function (err) { + assert.strictEqual(err, null); + called++; + }); + + assert.equal(2, called); + done(); + }) + }); + + describe('onFulfill shortcut', function () { + it('works', function (done) { + var promise = new MPromise() + , 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 MPromise() + , 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 MPromise(); + assert.ok(promise.on('jump', function () {}) instanceof MPromise); + done() + }); + + it('onFulfill()', function (done) { + var promise = new MPromise(); + assert.ok(promise.onFulfill(function () {}) instanceof MPromise); + done(); + }); + it('onReject()', function (done) { + var promise = new MPromise(); + assert.ok(promise.onReject(function () {}) instanceof MPromise); + done(); + }); + it('onResolve()', function (done) { + var promise = new MPromise(); + assert.ok(promise.onResolve(function () {}) instanceof MPromise); + done(); + }) + }); + + describe('casting errors', function () { + describe('reject()', function () { + it('does not cast arguments to Error', function (done) { + var p = new MPromise(function (err) { + 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 MPromise; + 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 MPromise; + 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 MPromise; + 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.10') != 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 MPromise; + 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 MPromise; + 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 MPromise; + 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 MPromise; + + 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('fulfill values and splats', function () { + it('should handle multiple values', function (done) { + var p = new MPromise; + p.onFulfill(function (a, b, c) { + assert.equal('a', a); + assert.equal('b', b); + assert.equal('c', c); + done(); + }); + p.fulfill('a', 'b', 'c'); + }); + + it('should handle multiple values from a then', function (done) { + MPromise.fulfilled().then( + function () { + return MPromise.fulfilled().then( + function () { + var p = new MPromise; + p.fulfill('a', 'b', 'c'); + return p; + } + ); + } + ).onFulfill( + function (a, b, c) { + assert.equal('a', a); + assert.equal('b', b); + assert.equal('c', c); + done(); + } + ).end() + }); + + it('should work with `fulfilled` convenience method', function (done) { + MPromise.fulfilled('a', 'b', 'c').then(function (a, b, c) { + assert.equal('a', a); + assert.equal('b', b); + assert.equal('c', c); + done(); + }) + }); + }); + + + describe('end', function () { + it("should return the promise", function (done) { + var p = new MPromise; + var p1 = p.end(); + assert.equal(p, p1); + done(); + }); + + + it("should throw for chain", function (done) { + var p = new MPromise; + 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 MPromise; + 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 MPromise; + p1.chain(new MPromise(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 MPromise; + p1.chain(new MPromise(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 MPromise; + p1.chain(new MPromise(function (err) { + assert.equal(err, e); + done(); + })); + p1.resolve(e); + }); + + + it('should propagate resolution val', function (done) { + var varSentinel = {a: 'a'}; + var p1 = new MPromise; + p1.chain(new MPromise(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 MPromise; + var p2 = p.all(function () { + return [ + (function () { + var p = new MPromise(); + count++; + p.resolve(); + return p; + })() + , (function () { + var p = new MPromise(); + 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 MPromise; + var p2 = p.all(function () { + return [ + (function () { + var p = new MPromise(); + count++; + p.resolve(); + return p; + })() + , (function () { + 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 = MPromise.deferred(); + assert.ok(d.promise instanceof MPromise); + assert.ok(d.reject instanceof Function); + assert.ok(d.resolve 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(); + }; + MPromise.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(); + }; + MPromise.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); + }; + MPromise.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") + }; + MPromise.hook([l1, l2, l1]).end(function (err) { + assert(run, 2); + done(); + }); + }); + }); +}); diff --git a/5-3/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js b/5-3/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js new file mode 100644 index 0000000..d30bb32 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js @@ -0,0 +1,15 @@ +/** + * Module dependencies. + */ +var Promise = require('../lib/promise'); +var aplus = require('promises-aplus-tests'); + +// tests +describe("run A+ suite", function () { + aplus.mocha({ + fulfilled: Promise.fulfilled, + rejected: Promise.rejected, + deferred: Promise.deferred + }); +}); + diff --git a/5-3/node_modules/mongoose/node_modules/mquery/.npmignore b/5-3/node_modules/mongoose/node_modules/mquery/.npmignore new file mode 100644 index 0000000..5a14ae1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/.npmignore @@ -0,0 +1,3 @@ +*.sw* +node_modules/ +coverage/ diff --git a/5-3/node_modules/mongoose/node_modules/mquery/.travis.yml b/5-3/node_modules/mongoose/node_modules/mquery/.travis.yml new file mode 100644 index 0000000..4dc3a7d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + - 0.11 +services: + - mongodb diff --git a/5-3/node_modules/mongoose/node_modules/mquery/History.md b/5-3/node_modules/mongoose/node_modules/mquery/History.md new file mode 100644 index 0000000..9972664 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/History.md @@ -0,0 +1,230 @@ + +1.6.2 / 2015-07-12 +================== + + * fixed; support exec cb being called synchronously #66 + +1.6.1 / 2015-06-16 +================== + + * fixed; do not treat $meta projection as inclusive [vkarpov15](https://github.com/vkarpov15) + +1.6.0 / 2015-05-27 +================== + + * update dependencies #65 [bachp](https://github.com/bachp) + +1.5.0 / 2015-03-31 +================== + + * fixed; debug output + * fixed; allow hint usage with count #61 [trueinsider](https://github.com/trueinsider) + +1.4.0 / 2015-03-29 +================== + + * added; object support to slice() #60 [vkarpov15](https://github.com/vkarpov15) + * debug; improved output #57 [flyvictor](https://github.com/flyvictor) + +1.3.0 / 2014-11-06 +================== + + * added; setTraceFunction() #53 from [jlai](https://github.com/jlai) + +1.2.1 / 2014-09-26 +================== + + * fixed; distinct assignment in toConstructor() #51 from [esco](https://github.com/esco) + +1.2.0 / 2014-09-18 +================== + + * added; stream() support for find() + +1.1.0 / 2014-09-15 +================== + + * add #then for co / koa support + * start checking code coverage + +1.0.0 / 2014-07-07 +================== + + * Remove broken require() calls until they're actually implemented #48 [vkarpov15](https://github.com/vkarpov15) + +0.9.0 / 2014-05-22 +================== + + * added; thunk() support + * release 0.8.0 + +0.8.0 / 2014-05-15 +================== + + * added; support for maxTimeMS #44 [yoitsro](https://github.com/yoitsro) + * updated; devDependency (driver to 1.4.4) + +0.7.0 / 2014-05-02 +================== + + * fixed; pass $maxDistance in $near object as described in docs #43 [vkarpov15](https://github.com/vkarpov15) + * fixed; cloning buffers #42 [gjohnson](https://github.com/gjohnson) + * tests; a little bit more `mongodb` agnostic #34 [refack](https://github.com/refack) + +0.6.0 / 2014-04-01 +================== + + * fixed; Allow $meta args in sort() so text search sorting works #37 [vkarpov15](https://github.com/vkarpov15) + +0.5.3 / 2014-02-22 +================== + + * fixed; cloning mongodb.Binary + +0.5.2 / 2014-01-30 +================== + + * fixed; cloning ObjectId constructors + * fixed; cloning of ReadPreferences #30 [ashtuchkin](https://github.com/ashtuchkin) + * tests; use specific mongodb version #29 [AvianFlu](https://github.com/AvianFlu) + * tests; remove dependency on ObjectId #28 [refack](https://github.com/refack) + * tests; add failing ReadPref test + +0.5.1 / 2014-01-17 +================== + + * added; deprecation notice to tags parameter #27 [ashtuchkin](https://github.com/ashtuchkin) + * readme; add links + +0.5.0 / 2014-01-16 +================== + + * removed; mongodb driver dependency #26 [ashtuchkin](https://github.com/ashtuchkin) + * removed; first class support of read preference tags #26 (still supported though) [ashtuchkin](https://github.com/ashtuchkin) + * added; better ObjectId clone support + * fixed; cloning objects that have no constructor #21 + * docs; cleaned up [ashtuchkin](https://github.com/ashtuchkin) + +0.4.2 / 2014-01-08 +================== + + * updated; debug module 0.7.4 [refack](https://github.com/refack) + +0.4.1 / 2014-01-07 +================== + + * fixed; inclusive/exclusive logic + +0.4.0 / 2014-01-06 +================== + + * added; selected() + * added; selectedInclusively() + * added; selectedExclusively() + +0.3.3 / 2013-11-14 +================== + + * Fix Mongo DB Dependency #20 [rschmukler](https://github.com/rschmukler) + +0.3.2 / 2013-09-06 +================== + + * added; geometry support for near() + +0.3.1 / 2013-08-22 +================== + + * fixed; update retains key order #19 + +0.3.0 / 2013-08-22 +================== + + * less hardcoded isNode env detection #18 [vshulyak](https://github.com/vshulyak) + * added; validation of findAndModify varients + * clone update doc before execution + * stricter env checks + +0.2.7 / 2013-08-2 +================== + + * Now support GeoJSON point values for Query#near + +0.2.6 / 2013-07-30 +================== + + * internally, 'asc' and 'desc' for sorts are now converted into 1 and -1, respectively + +0.2.5 / 2013-07-30 +================== + + * updated docs + * changed internal representation of `sort` to use objects instead of arrays + +0.2.4 / 2013-07-25 +================== + + * updated; sliced to 0.0.5 + +0.2.3 / 2013-07-09 +================== + + * now using a callback in collection.find instead of directly calling toArray() on the cursor [ebensing](https://github.com/ebensing) + +0.2.2 / 2013-07-09 +================== + + * now exposing mongodb export to allow for better testing [ebensing](https://github.com/ebensing) + +0.2.1 / 2013-07-08 +================== + + * select no longer accepts arrays as parameters [ebensing](https://github.com/ebensing) + +0.2.0 / 2013-07-05 +================== + + * use $geoWithin by default + +0.1.2 / 2013-07-02 +================== + + * added use$geoWithin flag [ebensing](https://github.com/ebensing) + * fix read preferences typo [ebensing](https://github.com/ebensing) + * fix reference to old param name in exists() [ebensing](https://github.com/ebensing) + +0.1.1 / 2013-06-24 +================== + + * fixed; $intersects -> $geoIntersects #14 [ebensing](https://github.com/ebensing) + * fixed; Retain key order when copying objects #15 [ebensing](https://github.com/ebensing) + * bump mongodb dev dep + +0.1.0 / 2013-05-06 +================== + + * findAndModify; return the query + * move mquery.proto.canMerge to mquery.canMerge + * overwrite option now works with non-empty objects + * use strict mode + * validate count options + * validate distinct options + * add aggregate to base collection methods + * clone merge arguments + * clone merged update arguments + * move subclass to mquery.prototype.toConstructor + * fixed; maxScan casing + * use regexp-clone + * added; geometry/intersects support + * support $and + * near: do not use "radius" + * callbacks always fire on next turn of loop + * defined collection interface + * remove time from tests + * clarify goals + * updated docs; + +0.0.1 / 2012-12-15 +================== + + * initial release diff --git a/5-3/node_modules/mongoose/node_modules/mquery/LICENSE b/5-3/node_modules/mongoose/node_modules/mquery/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/LICENSE @@ -0,0 +1,22 @@ +(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/5-3/node_modules/mongoose/node_modules/mquery/Makefile b/5-3/node_modules/mongoose/node_modules/mquery/Makefile new file mode 100644 index 0000000..dbb2831 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/Makefile @@ -0,0 +1,22 @@ + +test: + @NODE_ENV=test ./node_modules/.bin/mocha $(T) $(TESTS) + +test-cov: + @NODE_ENV=test node \ + node_modules/.bin/istanbul cover \ + ./node_modules/.bin/_mocha \ + -- -u exports \ + +open-cov: + open coverage/lcov-report/index.html + +test-travis: + @NODE_ENV=test node \ + node_modules/.bin/istanbul cover \ + ./node_modules/.bin/_mocha \ + --report lcovonly \ + -- -u exports \ + --bail + +.PHONY: test test-cov open-cov test-travis diff --git a/5-3/node_modules/mongoose/node_modules/mquery/README.md b/5-3/node_modules/mongoose/node_modules/mquery/README.md new file mode 100644 index 0000000..f7bf7f4 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/README.md @@ -0,0 +1,1220 @@ +#mquery +=========== + +`mquery` is a fluent mongodb query builder designed to run in multiple environments. As of v0.1, `mquery` runs on `Node.js` only with support for the MongoDB shell and browser environments planned for upcoming releases. + +##Features + + - fluent query builder api + - custom base query support + - MongoDB 2.4 geoJSON support + - method + option combinations validation + - node.js driver compatibility + - environment detection + - [debug](https://github.com/visionmedia/debug) support + - separated collection implementations for maximum flexibility + +[![Build Status](https://travis-ci.org/aheckmann/mquery.png)](https://travis-ci.org/aheckmann/mquery) + +##Use + +```js +require('mongodb').connect(uri, function (err, db) { + if (err) return handleError(err); + + // get a collection + var collection = db.collection('artists'); + + // pass it to the constructor + mquery(collection).find({..}, callback); + + // or pass it to the collection method + mquery().find({..}).collection(collection).exec(callback) + + // or better yet, create a custom query constructor that has it always set + var Artist = mquery(collection).toConstructor(); + Artist().find(..).where(..).exec(callback) +}) +``` + +`mquery` requires a collection object to work with. In the example above we just pass the collection object created using the official [MongoDB driver](https://github.com/mongodb/node-mongodb-native). + + +##Fluent API + +- [find](#find) +- [findOne](#findOne) +- [count](#count) +- [remove](#remove) +- [update](#update) +- [findOneAndUpdate](#findoneandupdate) +- [findOneAndRemove](#findoneandremove) +- [distinct](#distinct) +- [exec](#exec) +- [stream](#stream) +- [all](#all) +- [and](#and) +- [box](#box) +- [circle](#circle) +- [elemMatch](#elemmatch) +- [equals](#equals) +- [exists](#exists) +- [geometry](#geometry) +- [gt](#gt) +- [gte](#gte) +- [in](#in) +- [intersects](#intersects) +- [lt](#lt) +- [lte](#lte) +- [maxDistance](#maxdistance) +- [mod](#mod) +- [ne](#ne) +- [nin](#nin) +- [nor](#nor) +- [near](#near) +- [or](#or) +- [polygon](#polygon) +- [regex](#regex) +- [select](#select) +- [selected](#selected) +- [selectedInclusively](#selectedinclusively) +- [selectedExclusively](#selectedexclusively) +- [size](#size) +- [slice](#slice) +- [within](#within) +- [where](#where) +- [$where](#where-1) +- [batchSize](#batchsize) +- [comment](#comment) +- [hint](#hint) +- [limit](#limit) +- [maxScan](#maxscan) +- [maxTime](#maxtime) +- [skip](#skip) +- [sort](#sort) +- [read](#read) +- [slaveOk](#slaveok) +- [snapshot](#snapshot) +- [tailable](#tailable) + +## Helpers + +- [collection](#collection) +- [then](#then) +- [thunk](#thunk) +- [merge](#mergeobject) +- [setOptions](#setoptionsoptions) +- [setTraceFunction](#settracefunctionfunc) +- [mquery.setGlobalTraceFunction](#mquerysetglobaltracefunctionfunc) +- [mquery.canMerge](#mquerycanmerge) +- [mquery.use$geoWithin](#mqueryusegeowithin) + +###find() + +Declares this query a _find_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().find() +mquery().find(match) +mquery().find(callback) +mquery().find(match, function (err, docs) { + assert(Array.isArray(docs)); +}) +``` + +###findOne() + +Declares this query a _findOne_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().findOne() +mquery().findOne(match) +mquery().findOne(callback) +mquery().findOne(match, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) +``` + +###count() + +Declares this query a _count_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().count() +mquery().count(match) +mquery().count(callback) +mquery().count(match, function (err, number){ + console.log('we found %d matching documents', number); +}) +``` + +###remove() + +Declares this query a _remove_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. + +```js +mquery().remove() +mquery().remove(match) +mquery().remove(callback) +mquery().remove(match, function (err){}) +``` + +###update() + +Declares this query an _update_ query. Optionally pass an update document, match clause, options or callback. If a callback is passed, the query is executed. To force execution without passing a callback, run `update(true)`. + +```js +mquery().update() +mquery().update(match, updateDocument) +mquery().update(match, updateDocument, options) + +// the following all execute the command +mquery().update(callback) +mquery().update({$set: updateDocument, callback) +mquery().update(match, updateDocument, callback) +mquery().update(match, updateDocument, options, function (err, result){}) +mquery().update(true) // executes (unsafe write) +``` + +#####the update document + +All paths passed that are not `$atomic` operations will become `$set` ops. For example: + +```js +mquery(collection).where({ _id: id }).update({ title: 'words' }, callback) +``` + +becomes + +```js +collection.update({ _id: id }, { $set: { title: 'words' }}, callback) +``` + +This behavior can be overridden using the `overwrite` option (see below). + +#####options + +Options are passed to the `setOptions()` method. + +- overwrite + +Passing an empty object `{ }` as the update document will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option, the update operation will be ignored and the callback executed without sending the command to MongoDB to prevent accidently overwritting documents in the collection. + +```js +var q = mquery(collection).where({ _id: id }).setOptions({ overwrite: true }); +q.update({ }, callback); // overwrite with an empty doc +``` + +The `overwrite` option isn't just for empty objects, it also provides a means to override the default `$set` conversion and send the update document as is. + +```js +// create a base query +var base = mquery({ _id: 108 }).collection(collection).toConstructor(); + +base().findOne(function (err, doc) { + console.log(doc); // { _id: 108, name: 'cajon' }) + + base().setOptions({ overwrite: true }).update({ changed: true }, function (err) { + base.findOne(function (err, doc) { + console.log(doc); // { _id: 108, changed: true }) - the doc was overwritten + }); + }); +}) +``` + +- multi + +Updates only modify a single document by default. To update multiple documents, set the `multi` option to `true`. + +```js +mquery() + .collection(coll) + .update({ name: /^match/ }, { $addToSet: { arr: 4 }}, { multi: true }, callback) + +// another way of doing it +mquery({ name: /^match/ }) + .collection(coll) + .setOptions({ multi: true }) + .update({ $addToSet: { arr: 4 }}, callback) + +// update multiple documents with an empty doc +var q = mquery(collection).where({ name: /^match/ }); +q.setOptions({ multi: true, overwrite: true }) +q.update({ }); +q.update(function (err, result) { + console.log(arguments); +}); +``` + +###findOneAndUpdate() + +Declares this query a _findAndModify_ with update query. Optionally pass a match clause, update document, options, or callback. If a callback is passed, the query is executed. + +When executed, the first matching document (if found) is modified according to the update document and passed back to the callback. + +#####options + +Options are passed to the `setOptions()` method. + +- `new`: boolean - true to return the modified document rather than the original. defaults to true +- `upsert`: boolean - creates the object if it doesn't exist. defaults to false +- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to update + +```js +query.findOneAndUpdate() +query.findOneAndUpdate(updateDocument) +query.findOneAndUpdate(match, updateDocument) +query.findOneAndUpdate(match, updateDocument, options) + +// the following all execute the command +query.findOneAndUpdate(callback) +query.findOneAndUpdate(updateDocument, callback) +query.findOneAndUpdate(match, updateDocument, callback) +query.findOneAndUpdate(match, updateDocument, options, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) + ``` + +###findOneAndRemove() + +Declares this query a _findAndModify_ with remove query. Optionally pass a match clause, options, or callback. If a callback is passed, the query is executed. + +When executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed to the callback. + +#####options + +Options are passed to the `setOptions()` method. + +- `sort`: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove + +```js +A.where().findOneAndRemove() +A.where().findOneAndRemove(match) +A.where().findOneAndRemove(match, options) + +// the following all execute the command +A.where().findOneAndRemove(callback) +A.where().findOneAndRemove(match, callback) +A.where().findOneAndRemove(match, options, function (err, doc) { + if (doc) { + // the document may not be found + console.log(doc); + } +}) + ``` + +###distinct() + +Declares this query a _distinct_ query. Optionally pass the distinct field, a match clause or callback. If a callback is passed the query is executed. + +```js +mquery().distinct() +mquery().distinct(match) +mquery().distinct(match, field) +mquery().distinct(field) + +// the following all execute the command +mquery().distinct(callback) +mquery().distinct(field, callback) +mquery().distinct(match, callback) +mquery().distinct(match, field, function (err, result) { + console.log(result); +}) +``` + +###exec() + +Executes the query. + +```js +mquery().findOne().where('route').intersects(polygon).exec(function (err, docs){}) +``` + +###stream() + +Executes the query and returns a stream. + +```js +var stream = mquery().find().stream(options); +stream.on('data', cb); +stream.on('close', fn); +``` + +Note: this only works with `find()` operations. + +Note: returns the stream object directly from the node-mongodb-native driver. (currently streams1 type stream). Any options will be passed along to the [driver method](http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#stream). + +------------- + +###all() + +Specifies an `$all` query condition + +```js +mquery().where('permission').all(['read', 'write']) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/all/) + +###and() + +Specifies arguments for an `$and` condition + +```js +mquery().and([{ color: 'green' }, { status: 'ok' }]) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/and/) + +###box() + +Specifies a `$box` condition + +```js +var lowerLeft = [40.73083, -73.99756] +var upperRight= [40.741404, -73.988135] + +mquery().where('location').within().box(lowerLeft, upperRight) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/box/) + +###circle() + +Specifies a `$center` or `$centerSphere` condition. + +```js +var area = { center: [50, 50], radius: 10, unique: true } +query.where('loc').within().circle(area) +query.circle('loc', area); + +// for spherical calculations +var area = { center: [50, 50], radius: 10, unique: true, spherical: true } +query.where('loc').within().circle(area) +query.circle('loc', area); +``` + +- [MongoDB Documentation - center](http://docs.mongodb.org/manual/reference/operator/center/) +- [MongoDB Documentation - centerSphere](http://docs.mongodb.org/manual/reference/operator/centerSphere/) + +###elemMatch() + +Specifies an `$elemMatch` condition + +```js +query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + +query.elemMatch('comment', function (elem) { + elem.where('author').equals('autobot'); + elem.where('votes').gte(5); +}) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/elemMatch/) + +###equals() + +Specifies the complementary comparison value for the path specified with `where()`. + +```js +mquery().where('age').equals(49); + +// is the same as + +mquery().where({ 'age': 49 }); +``` + +###exists() + +Specifies an `$exists` condition + +```js +// { name: { $exists: true }} +mquery().where('name').exists() +mquery().where('name').exists(true) +mquery().exists('name') + +// { name: { $exists: false }} +mquery().where('name').exists(false); +mquery().exists('name', false); +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/exists/) + +###geometry() + +Specifies a `$geometry` condition + +```js +var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] +query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + +// or +var polyB = [[ 0, 0 ], [ 1, 1 ]] +query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + +// or +var polyC = [ 0, 0 ] +query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + +// or +query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + +// or +query.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] }) +``` + +`geometry()` **must** come after `intersects()`, `within()`, or `near()`. + +The `object` argument must contain `type` and `coordinates` properties. + +- type `String` +- coordinates `Array` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geometry/) + +###gt() + +Specifies a `$gt` query condition. + +```js +mquery().where('clicks').gt(999) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gt/) + +###gte() + +Specifies a `$gte` query condition. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gte/) + +```js +mquery().where('clicks').gte(1000) +``` + +###in() + +Specifies an `$in` query condition. + +```js +mquery().where('author_id').in([3, 48901, 761]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/in/) + +###intersects() + +Declares an `$geoIntersects` query for `geometry()`. + +```js +query.where('path').intersects().geometry({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}) + +// geometry arguments are supported +query.where('path').intersects({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}) +``` + +**Must** be used after `where()`. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoIntersects/) + +###lt() + +Specifies a `$lt` query condition. + +```js +mquery().where('clicks').lt(50) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lt/) + +###lte() + +Specifies a `$lte` query condition. + +```js +mquery().where('clicks').lte(49) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lte/) + +###maxDistance() + +Specifies a `$maxDistance` query condition. + +```js +mquery().where('location').near({ center: [139, 74.3] }).maxDistance(5) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/maxDistance/) + +###mod() + +Specifies a `$mod` condition + +```js +mquery().where('count').mod(2, 0) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/mod/) + +###ne() + +Specifies a `$ne` query condition. + +```js +mquery().where('status').ne('ok') +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/ne/) + +###nin() + +Specifies an `$nin` query condition. + +```js +mquery().where('author_id').nin([3, 48901, 761]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nin/) + +###nor() + +Specifies arguments for an `$nor` condition. + +```js +mquery().nor([{ color: 'green' }, { status: 'ok' }]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nor/) + +###near() + +Specifies arguments for a `$near` or `$nearSphere` condition. + +These operators return documents sorted by distance. + +####Example + +```js +query.where('loc').near({ center: [10, 10] }); +query.where('loc').near({ center: [10, 10], maxDistance: 5 }); +query.near('loc', { center: [10, 10], maxDistance: 5 }); + +// GeoJSON +query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }}); +query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true }); +query.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] }); + +// For a $nearSphere condition, pass the `spherical` option. +query.near({ center: [10, 10], maxDistance: 5, spherical: true }); +``` + +[MongoDB Documentation](http://www.mongodb.org/display/DOCS/Geospatial+Indexing) + +###or() + +Specifies arguments for an `$or` condition. + +```js +mquery().or([{ color: 'red' }, { status: 'emergency' }]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/or/) + +###polygon() + +Specifies a `$polygon` condition + +```js +mquery().where('loc').within().polygon([10,20], [13, 25], [7,15]) +mquery().polygon('loc', [10,20], [13, 25], [7,15]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/polygon/) + +###regex() + +Specifies a `$regex` query condition. + +```js +mquery().where('name').regex(/^sixstepsrecords/) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/regex/) + +###select() + +Specifies which document fields to include or exclude + +```js +// 1 means include, 0 means exclude +mquery().select({ name: 1, address: 1, _id: 0 }) + +// or + +mquery().select('name address -_id') +``` + +#####String syntax + +When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. + +```js +// include a and b, exclude c +query.select('a b -c'); + +// or you may use object notation, useful when +// you have keys already prefixed with a "-" +query.select({a: 1, b: 1, c: 0}); +``` + +_Cannot be used with `distinct()`._ + +###selected() + +Determines if the query has selected any fields. + +```js +var query = mquery(); +query.selected() // false +query.select('-name'); +query.selected() // true +``` + +###selectedInclusively() + +Determines if the query has selected any fields inclusively. + +```js +var query = mquery().select('name'); +query.selectedInclusively() // true + +var query = mquery(); +query.selected() // false +query.select('-name'); +query.selectedInclusively() // false +query.selectedExclusively() // true +``` + +###selectedExclusively() + +Determines if the query has selected any fields exclusively. + +```js +var query = mquery().select('-name'); +query.selectedExclusively() // true + +var query = mquery(); +query.selected() // false +query.select('name'); +query.selectedExclusively() // false +query.selectedInclusively() // true +``` + +###size() + +Specifies a `$size` query condition. + +```js +mquery().where('someArray').size(6) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/size/) + +###slice() + +Specifies a `$slice` projection for a `path` + +```js +mquery().where('comments').slice(5) +mquery().where('comments').slice(-5) +mquery().where('comments').slice([-10, 5]) +``` + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/projection/slice/) + +###within() + +Sets a `$geoWithin` or `$within` argument for geo-spatial queries. + +```js +mquery().within().box() +mquery().within().circle() +mquery().within().geometry() + +mquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); +mquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); +mquery().where('loc').within({ polygon: [[],[],[],[]] }); + +mquery().where('loc').within([], [], []) // polygon +mquery().where('loc').within([], []) // box +mquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry +``` + +As of mquery 2.0, `$geoWithin` is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see [mquery.use$geoWithin](#mqueryusegeowithin). + +**Must** be used after `where()`. + +[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoWithin/) + +###where() + +Specifies a `path` for use with chaining + +```js +// instead of writing: +mquery().find({age: {$gte: 21, $lte: 65}}); + +// we can instead write: +mquery().where('age').gte(21).lte(65); + +// passing query conditions is permitted too +mquery().find().where({ name: 'vonderful' }) + +// chaining +mquery() +.where('age').gte(21).lte(65) +.where({ 'name': /^vonderful/i }) +.where('friends').slice(10) +.exec(callback) +``` + +###$where() + +Specifies a `$where` condition. + +Use `$where` when you need to select documents using a JavaScript expression. + +```js +query.$where('this.comments.length > 10 || this.name.length > 5').exec(callback) + +query.$where(function () { + return this.comments.length > 10 || this.name.length > 5; +}) +``` + +Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using. + +----------- + +###batchSize() + +Specifies the batchSize option. + +```js +query.batchSize(100) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.batchSize/) + +###comment() + +Specifies the comment option. + +```js +query.comment('login query'); +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/) + +###hint() + +Sets query hints. + +```js +mquery().hint({ indexA: 1, indexB: -1 }) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/hint/) + +###limit() + +Specifies the limit option. + +```js +query.limit(20) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.limit/) + +###maxScan() + +Specifies the maxScan option. + +```js +query.maxScan(100) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/maxScan/) + +###maxTime() + +Specifies the maxTimeMS option. + +```js +query.maxTime(100) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.maxTimeMS/) + + +###skip() + +Specifies the skip option. + +```js +query.skip(100).limit(20) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.skip/) + +###sort() + +Sets the query sort order. + +If an object is passed, key values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. + +If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + +```js +// these are equivalent +query.sort({ field: 'asc', test: -1 }); +query.sort('field -test'); +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.sort/) + +###read() + +Sets the readPreference option for the query. + +```js +mquery().read('primary') +mquery().read('p') // same as primary + +mquery().read('primaryPreferred') +mquery().read('pp') // same as primaryPreferred + +mquery().read('secondary') +mquery().read('s') // same as secondary + +mquery().read('secondaryPreferred') +mquery().read('sp') // same as secondaryPreferred + +mquery().read('nearest') +mquery().read('n') // same as nearest +``` + +#####Preferences: + +- `primary` - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. +- `secondary` - Read from secondary if available, otherwise error. +- `primaryPreferred` - Read from primary if available, otherwise a secondary. +- `secondaryPreferred` - Read from a secondary if available, otherwise read from the primary. +- `nearest` - All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + +Aliases + +- `p` primary +- `pp` primaryPreferred +- `s` secondary +- `sp` secondaryPreferred +- `n` nearest + +#####Preference Tags: + +To keep the separation of concerns between `mquery` and your driver +clean, `mquery#read()` no longer handles specifying a second `tags` argument as of version 0.5. +If you need to specify tags, pass any non-string argument as the first argument. +`mquery` will pass this argument untouched to your collections methods later. +For example: + +```js +// example of specifying tags using the Node.js driver +var ReadPref = require('mongodb').ReadPreference; +var preference = new ReadPref('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); +mquery(..).read(preference).exec(); +``` + +Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + +###slaveOk() + +Sets the slaveOk option. `true` allows reading from secondaries. + +**deprecated** use [read()](#read) preferences instead if on mongodb >= 2.2 + +```js +query.slaveOk() // true +query.slaveOk(true) +query.slaveOk(false) +``` + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/) + +###snapshot() + +Specifies this query as a snapshot query. + +```js +mquery().snapshot() // true +mquery().snapshot(true) +mquery().snapshot(false) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/snapshot/) + +###tailable() + +Sets tailable option. + +```js +mquery().tailable() <== true +mquery().tailable(true) +mquery().tailable(false) +``` + +_Cannot be used with `distinct()`._ + +[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/) + +##Helpers + +###collection() + +Sets the querys collection. + +```js +mquery().collection(aCollection) +``` + +###then() + +Executes the query and returns a promise which will be resolved with the query results or rejected if the query responds with an error. + +```js +mquery().find(..).then(success, error); +``` + +This is very useful when combined with [co](https://github.com/visionmedia/co) or [koa](https://github.com/koajs/koa), which automatically resolve promise-like objects for you. + +```js +co(function*(){ + var doc = yield mquery().findOne({ _id: 499 }); + console.log(doc); // { _id: 499, name: 'amazing', .. } +})(); +``` + +_NOTE_: +The returned promise is a [bluebird](https://github.com/petkaantonov/bluebird/) promise but this is customizable. If you want to +use your favorite promise library, simply set `mquery.Promise = YourPromiseConstructor`. +Your `Promise` must be [promises A+](http://promisesaplus.com/) compliant. + +###thunk() + +Returns a thunk which when called runs the query's `exec` method passing the results to the callback. + +```js +var thunk = mquery(collection).find({..}).thunk(); + +thunk(function(err, results) { + +}) +``` + +###merge(object) + +Merges other mquery or match condition objects into this one. When an muery instance is passed, its match conditions, field selection and options are merged. + +```js +var drum = mquery({ type: 'drum' }).collection(instruments); +var redDrum = mqery({ color: 'red' }).merge(drum); +redDrum.count(function (err, n) { + console.log('there are %d red drums', n); +}) +``` + +Internally uses `mquery.canMerge` to determine validity. + +###setOptions(options) + +Sets query options. + +```js +mquery().setOptions({ collection: coll, limit: 20 }) +``` + +#####options + +- [tailable](#tailable) * +- [sort](#sort) * +- [limit](#limit) * +- [skip](#skip) * +- [maxScan](#maxscan) * +- [maxTime](#maxtime) * +- [batchSize](#batchSize) * +- [comment](#comment) * +- [snapshot](#snapshot) * +- [hint](#hint) * +- [slaveOk](#slaveOk) * +- [safe](http://docs.mongodb.org/manual/reference/write-concern/): Boolean - passed through to the collection. Setting to `true` is equivalent to `{ w: 1 }` +- [collection](#collection): the collection to query against + +_* denotes a query helper method is also available_ + +###setTraceFunction(func) + +Set a function to trace this query. Useful for profiling or logging. + +```js +function traceFunction (method, queryInfo, query) { + console.log('starting ' + method + ' query'); + + return function (err, result, millis) { + console.log('finished ' + method + ' query in ' + millis + 'ms'); + }; +} + +mquery().setTraceFunction(traceFunction).findOne({name: 'Joe'}, cb); +``` + +The trace function is passed (method, queryInfo, query) + +- method is the name of the method being called (e.g. findOne) +- queryInfo contains information about the query: + - conditions: query conditions/criteria + - options: options such as sort, fields, etc + - doc: document being updated +- query is the query object + +The trace function should return a callback function which accepts: +- err: error, if any +- result: result, if any +- millis: time spent waiting for query result + +NOTE: stream requests are not traced. + +###mquery.setGlobalTraceFunction(func) + +Similar to `setTraceFunction()` but automatically applied to all queries. + +```js +mquery.setTraceFunction(traceFunction); +``` + +###mquery.canMerge(conditions) + +Determines if `conditions` can be merged using `mquery().merge()`. + +```js +var query = mquery({ type: 'drum' }); +var okToMerge = mquery.canMerge(anObject) +if (okToMerge) { + query.merge(anObject); +} +``` + +##mquery.use$geoWithin + +MongoDB 2.4 introduced the `$geoWithin` operator which replaces and is 100% backward compatible with `$within`. As of mquery 0.2, we default to using `$geoWithin` for all `within()` calls. + +If you are running MongoDB < 2.4 this will be problematic. To force `mquery` to be backward compatible and always use `$within`, set the `mquery.use$geoWithin` flag to `false`. + +```js +mquery.use$geoWithin = false; +``` + +##Custom Base Queries + +Often times we want custom base queries that encapsulate predefined criteria. With `mquery` this is easy. First create the query you want to reuse and call its `toConstructor()` method which returns a new subclass of `mquery` that retains all options and criteria of the original. + +```js +var greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor(); + +// use it! +greatMovies().count(function (err, n) { + console.log('There are %d great movies', n); +}); + +greatMovies().where({ name: /^Life/ }).select('name').find(function (err, docs) { + console.log(docs); +}); +``` + +##Validation + +Method and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a `distinct` query does not support specifying options like `hint` or field selection. In this case an error will be thrown so you can catch these mistakes in development. + +##Debug support + +Debug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable: + + DEBUG=mquery node yourprogram.js + +Read the debug module documentation for more details. + +## General compatibility + +#### ObjectIds + +`mquery` clones query arguments before passing them to a `collection` method for execution. +This prevents accidental side-affects to the objects you pass. +To clone `ObjectIds` we need to make some assumptions. + +First, to check if an object is an `ObjectId`, we check its constructors name. If it matches either +`ObjectId` or `ObjectID` we clone it. + +To clone `ObjectIds`, we call its optional `clone` method. If a `clone` method does not exist, we fall +back to calling `new obj.constructor(obj.id)`. We assume, for compatibility with the +Node.js driver, that the `ObjectId` instance has a public `id` property and that +when creating an `ObjectId` instance we can pass that `id` as an argument. + +#### Read Preferences + +`mquery` supports specifying [Read Preferences]() to control from which MongoDB node your query will read. +The Read Preferences spec also support specifying tags. To pass tags, some +drivers (Node.js driver) require passing a special constructor that handles both the read preference and its tags. +If you need to specify tags, pass an instance of your drivers ReadPreference constructor or roll your own. `mquery` will store whatever you provide and pass later to your collection during execution. + +##Future goals + + - mongo shell compatibility + - browser compatibility + +## Installation + + $ npm install mquery + +## License + +[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE) + diff --git a/5-3/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js b/5-3/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js new file mode 100644 index 0000000..bce3c38 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * methods a collection must implement + */ + +var methods = [ + 'find' + , 'findOne' + , 'update' + , 'remove' + , 'count' + , 'distinct' + , 'findAndModify' + , 'aggregate' + , 'findStream' +]; + +/** + * Collection base class from which implementations inherit + */ + +function Collection () {} + +for (var i = 0, len = methods.length; i < len; ++i) { + var method = methods[i]; + Collection.prototype[method] = notImplemented(method); +} + +module.exports = exports = Collection; +Collection.methods = methods; + +/** + * creates a function which throws an implementation error + */ + +function notImplemented (method) { + return function () { + throw new Error('collection.' + method + ' not implemented'); + } +} + diff --git a/5-3/node_modules/mongoose/node_modules/mquery/lib/collection/index.js b/5-3/node_modules/mongoose/node_modules/mquery/lib/collection/index.js new file mode 100644 index 0000000..e3cf44d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/lib/collection/index.js @@ -0,0 +1,13 @@ +'use strict'; + +var env = require('../env') + +if ('unknown' == env.type) { + throw new Error('Unknown environment') +} + +module.exports = + env.isNode ? require('./node') : + env.isMongo ? require('./collection') : + require('./collection'); + diff --git a/5-3/node_modules/mongoose/node_modules/mquery/lib/collection/node.js b/5-3/node_modules/mongoose/node_modules/mquery/lib/collection/node.js new file mode 100644 index 0000000..f254456 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/lib/collection/node.js @@ -0,0 +1,100 @@ +'use strict'; + +/** + * Module dependencies + */ + +var Collection = require('./collection'); +var utils = require('../utils'); + +function NodeCollection (col) { + this.collection = col; + this.collectionName = col.collectionName; +} + +/** + * inherit from collection base class + */ + +utils.inherits(NodeCollection, Collection); + +/** + * find(match, options, function(err, docs)) + */ + +NodeCollection.prototype.find = function (match, options, cb) { + this.collection.find(match, options, function (err, cursor) { + if (err) return cb(err); + + cursor.toArray(cb); + }); +} + +/** + * findOne(match, options, function(err, doc)) + */ + +NodeCollection.prototype.findOne = function (match, options, cb) { + this.collection.findOne(match, options, cb); +} + +/** + * count(match, options, function(err, count)) + */ + +NodeCollection.prototype.count = function (match, options, cb) { + this.collection.count(match, options, cb); +} + +/** + * distinct(prop, match, options, function(err, count)) + */ + +NodeCollection.prototype.distinct = function (prop, match, options, cb) { + this.collection.distinct(prop, match, options, cb); +} + +/** + * update(match, update, options, function(err[, result])) + */ + +NodeCollection.prototype.update = function (match, update, options, cb) { + this.collection.update(match, update, options, cb); +} + +/** + * remove(match, options, function(err[, result]) + */ + +NodeCollection.prototype.remove = function (match, options, cb) { + this.collection.remove(match, options, cb); +} + +/** + * findAndModify(match, update, options, function(err, doc)) + */ + +NodeCollection.prototype.findAndModify = function (match, update, options, cb) { + var sort = Array.isArray(options.sort) ? options.sort : []; + this.collection.findAndModify(match, sort, update, options, cb); +} + +/** + * var stream = findStream(match, findOptions, streamOptions) + */ + +NodeCollection.prototype.findStream = function(match, findOptions, streamOptions) { + return this.collection.find(match, findOptions).stream(streamOptions); +} + +/** + * aggregation(operators..., function(err, doc)) + * TODO + */ + +/** + * Expose + */ + +module.exports = exports = NodeCollection; + diff --git a/5-3/node_modules/mongoose/node_modules/mquery/lib/env.js b/5-3/node_modules/mongoose/node_modules/mquery/lib/env.js new file mode 100644 index 0000000..3313b46 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/lib/env.js @@ -0,0 +1,22 @@ +'use strict'; + +exports.isNode = 'undefined' != typeof process + && 'object' == typeof module + && 'object' == typeof global + && 'function' == typeof Buffer + && process.argv + +exports.isMongo = !exports.isNode + && 'function' == typeof printjson + && 'function' == typeof ObjectId + && 'function' == typeof rs + && 'function' == typeof sh; + +exports.isBrowser = !exports.isNode + && !exports.isMongo + && 'undefined' != typeof window; + +exports.type = exports.isNode ? 'node' + : exports.isMongo ? 'mongo' + : exports.isBrowser ? 'browser' + : 'unknown' diff --git a/5-3/node_modules/mongoose/node_modules/mquery/lib/mquery.js b/5-3/node_modules/mongoose/node_modules/mquery/lib/mquery.js new file mode 100644 index 0000000..ca07867 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/lib/mquery.js @@ -0,0 +1,2612 @@ +'use strict'; + +/** + * Dependencies + */ + +var slice = require('sliced') +var assert = require('assert') +var util = require('util') +var utils = require('./utils') +var debug = require('debug')('mquery'); + +/** + * Query constructor used for building queries. + * + * ####Example: + * + * var query = new Query({ name: 'mquery' }); + * query.setOptions({ collection: moduleCollection }) + * query.where('age').gte(21).exec(callback); + * + * @param {Object} [criteria] + * @param {Object} [options] + * @api public + */ + +function Query (criteria, options) { + if (!(this instanceof Query)) + return new Query(criteria, options); + + var proto = this.constructor.prototype; + + this.op = proto.op || undefined; + + this.options = {}; + this.setOptions(proto.options); + + this._conditions = proto._conditions + ? utils.clone(proto._conditions) + : {}; + + this._fields = proto._fields + ? utils.clone(proto._fields) + : undefined; + + this._update = proto._update + ? utils.clone(proto._update) + : undefined; + + this._path = proto._path || undefined; + this._distinct = proto._distinct || undefined; + this._collection = proto._collection || undefined; + this._traceFunction = proto._traceFunction || undefined; + + if (options) { + this.setOptions(options); + } + + if (criteria) { + if (criteria.find && criteria.remove && criteria.update) { + // quack quack! + this.collection(criteria); + } else { + this.find(criteria); + } + } +} + +/** + * This is a parameter that the user can set which determines if mquery + * uses $within or $geoWithin for queries. It defaults to true which + * means $geoWithin will be used. If using MongoDB < 2.4 you should + * set this to false. + * + * @api public + * @property use$geoWithin + */ + +var $withinCmd = '$geoWithin'; +Object.defineProperty(Query, 'use$geoWithin', { + get: function ( ) { return $withinCmd == '$geoWithin' } + , set: function (v) { + if (true === v) { + // mongodb >= 2.4 + $withinCmd = '$geoWithin'; + } else { + $withinCmd = '$within'; + } + } +}); + +/** + * Converts this query to a constructor function with all arguments and options retained. + * + * ####Example + * + * // Create a query that will read documents with a "video" category from + * // `aCollection` on the primary node in the replica-set unless it is down, + * // in which case we'll read from a secondary node. + * var query = mquery({ category: 'video' }) + * query.setOptions({ collection: aCollection, read: 'primaryPreferred' }); + * + * // create a constructor based off these settings + * var Video = query.toConstructor(); + * + * // Video is now a subclass of mquery() and works the same way but with the + * // default query parameters and options set. + * + * // run a query with the previous settings but filter for movies with names + * // that start with "Life". + * Video().where({ name: /^Life/ }).exec(cb); + * + * @return {Query} new Query + * @api public + */ + +Query.prototype.toConstructor = function toConstructor () { + function CustomQuery (criteria, options) { + if (!(this instanceof CustomQuery)) + return new CustomQuery(criteria, options); + Query.call(this, criteria, options); + } + + utils.inherits(CustomQuery, Query); + + // set inherited defaults + var p = CustomQuery.prototype; + + p.options = {}; + p.setOptions(this.options); + + p.op = this.op; + p._conditions = utils.clone(this._conditions); + p._fields = utils.clone(this._fields); + p._update = utils.clone(this._update); + p._path = this._path; + p._distinct = this._distinct; + p._collection = this._collection; + p._traceFunction = this._traceFunction; + + return CustomQuery; +} + +/** + * Sets query options. + * + * ####Options: + * + * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * + * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * + * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * + * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * + * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * + * - [maxTime](http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS) * + * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * + * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * + * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * + * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * + * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * + * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) + * - collection the collection to query against + * + * _* denotes a query helper method is also available_ + * + * @param {Object} options + * @api public + */ + +Query.prototype.setOptions = function (options) { + if (!(options && utils.isObject(options))) + return this; + + // set arbitrary options + var methods = utils.keys(options) + , method + + for (var i = 0; i < methods.length; ++i) { + method = methods[i]; + + // use methods if exist (safer option manipulation) + if ('function' == typeof this[method]) { + var args = utils.isArray(options[method]) + ? options[method] + : [options[method]]; + this[method].apply(this, args) + } else { + this.options[method] = options[method]; + } + } + + return this; +} + +/** + * Sets this Querys collection. + * + * @param {Collection} coll + * @return {Query} this + */ + +Query.prototype.collection = function collection (coll) { + this._collection = new Query.Collection(coll); + + return this; +} + +/** + * Specifies a `$where` condition + * + * Use `$where` when you need to select documents using a JavaScript expression. + * + * ####Example + * + * query.$where('this.comments.length > 10 || this.name.length > 5') + * + * query.$where(function () { + * return this.comments.length > 10 || this.name.length > 5; + * }) + * + * @param {String|Function} js javascript string or function + * @return {Query} this + * @memberOf Query + * @method $where + * @api public + */ + +Query.prototype.$where = function (js) { + this._conditions.$where = js; + return this; +} + +/** + * Specifies a `path` for use with chaining. + * + * ####Example + * + * // instead of writing: + * User.find({age: {$gte: 21, $lte: 65}}, callback); + * + * // we can instead write: + * User.where('age').gte(21).lte(65); + * + * // passing query conditions is permitted + * User.find().where({ name: 'vonderful' }) + * + * // chaining + * User + * .where('age').gte(21).lte(65) + * .where('name', /^vonderful/i) + * .where('friends').slice(10) + * .exec(callback) + * + * @param {String} [path] + * @param {Object} [val] + * @return {Query} this + * @api public + */ + +Query.prototype.where = function () { + if (!arguments.length) return this; + if (!this.op) this.op = 'find'; + + var type = typeof arguments[0]; + + if ('string' == type) { + this._path = arguments[0]; + + if (2 === arguments.length) { + this._conditions[this._path] = arguments[1]; + } + + return this; + } + + if ('object' == type && !Array.isArray(arguments[0])) { + return this.merge(arguments[0]); + } + + throw new TypeError('path must be a string or object'); +} + +/** + * Specifies the complementary comparison value for paths specified with `where()` + * + * ####Example + * + * User.where('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @param {Object} val + * @return {Query} this + * @api public + */ + +Query.prototype.equals = function equals (val) { + this._ensurePath('equals'); + var path = this._path; + this._conditions[path] = val; + return this; +} + +/** + * Specifies arguments for an `$or` condition. + * + * ####Example + * + * query.or([{ color: 'red' }, { status: 'emergency' }]) + * + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.or = function or (array) { + var or = this._conditions.$or || (this._conditions.$or = []); + if (!utils.isArray(array)) array = [array]; + or.push.apply(or, array); + return this; +} + +/** + * Specifies arguments for a `$nor` condition. + * + * ####Example + * + * query.nor([{ color: 'green' }, { status: 'ok' }]) + * + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.nor = function nor (array) { + var nor = this._conditions.$nor || (this._conditions.$nor = []); + if (!utils.isArray(array)) array = [array]; + nor.push.apply(nor, array); + return this; +} + +/** + * Specifies arguments for a `$and` condition. + * + * ####Example + * + * query.and([{ color: 'green' }, { status: 'ok' }]) + * + * @see $and http://docs.mongodb.org/manual/reference/operator/and/ + * @param {Array} array array of conditions + * @return {Query} this + * @api public + */ + +Query.prototype.and = function and (array) { + var and = this._conditions.$and || (this._conditions.$and = []); + if (!Array.isArray(array)) array = [array]; + and.push.apply(and, array); + return this; +} + +/** + * Specifies a $gt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * ####Example + * + * Thing.find().where('age').gt(21) + * + * // or + * Thing.find().gt('age', 21) + * + * @method gt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $gte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method gte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $lt query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lt + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $lte query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method lte + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $ne query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method ne + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $in query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method in + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $nin query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method nin + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies an $all query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method all + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $size query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method size + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $regex query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method regex + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/** + * Specifies a $maxDistance query condition. + * + * When called with one argument, the most recent path passed to `where()` is used. + * + * @method maxDistance + * @memberOf Query + * @param {String} [path] + * @param {Number} val + * @api public + */ + +/*! + * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance + * + * Thing.where('type').nin(array) + */ + +'gt gte lt lte ne in nin all regex size maxDistance'.split(' ').forEach(function ($conditional) { + Query.prototype[$conditional] = function () { + var path, val; + + if (1 === arguments.length) { + this._ensurePath($conditional); + val = arguments[0]; + path = this._path; + } else { + val = arguments[1]; + path = arguments[0]; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds['$' + $conditional] = val; + return this; + }; +}) + +/** + * Specifies a `$mod` condition + * + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @api public + */ + +Query.prototype.mod = function () { + var val, path; + + if (1 === arguments.length) { + this._ensurePath('mod') + val = arguments[0]; + path = this._path; + } else if (2 === arguments.length && !utils.isArray(arguments[1])) { + this._ensurePath('mod') + val = slice(arguments); + path = this._path; + } else if (3 === arguments.length) { + val = slice(arguments, 1); + path = arguments[0]; + } else { + val = arguments[1]; + path = arguments[0]; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$mod = val; + return this; +} + +/** + * Specifies an `$exists` condition + * + * ####Example + * + * // { name: { $exists: true }} + * Thing.where('name').exists() + * Thing.where('name').exists(true) + * Thing.find().exists('name') + * + * // { name: { $exists: false }} + * Thing.where('name').exists(false); + * Thing.find().exists('name', false); + * + * @param {String} [path] + * @param {Number} val + * @return {Query} this + * @api public + */ + +Query.prototype.exists = function () { + var path, val; + + if (0 === arguments.length) { + this._ensurePath('exists'); + path = this._path; + val = true; + } else if (1 === arguments.length) { + if ('boolean' === typeof arguments[0]) { + this._ensurePath('exists'); + path = this._path; + val = arguments[0]; + } else { + path = arguments[0]; + val = true; + } + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$exists = val; + return this; +} + +/** + * Specifies an `$elemMatch` condition + * + * ####Example + * + * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) + * + * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) + * + * query.elemMatch('comment', function (elem) { + * elem.where('author').equals('autobot'); + * elem.where('votes').gte(5); + * }) + * + * query.where('comment').elemMatch(function (elem) { + * elem.where({ author: 'autobot' }); + * elem.where('votes').gte(5); + * }) + * + * @param {String|Object|Function} path + * @param {Object|Function} criteria + * @return {Query} this + * @api public + */ + +Query.prototype.elemMatch = function () { + if (null == arguments[0]) + throw new TypeError("Invalid argument"); + + var fn, path, criteria; + + if ('function' === typeof arguments[0]) { + this._ensurePath('elemMatch'); + path = this._path; + fn = arguments[0]; + } else if (utils.isObject(arguments[0])) { + this._ensurePath('elemMatch'); + path = this._path; + criteria = arguments[0]; + } else if ('function' === typeof arguments[1]) { + path = arguments[0]; + fn = arguments[1]; + } else if (arguments[1] && utils.isObject(arguments[1])) { + path = arguments[0]; + criteria = arguments[1]; + } else { + throw new TypeError("Invalid argument"); + } + + if (fn) { + criteria = new Query; + fn(criteria); + criteria = criteria._conditions; + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds.$elemMatch = criteria; + return this; +} + +// Spatial queries + +/** + * Sugar for geo-spatial queries. + * + * ####Example + * + * query.within().box() + * query.within().circle() + * query.within().geometry() + * + * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); + * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); + * query.where('loc').within({ polygon: [[],[],[],[]] }); + * + * query.where('loc').within([], [], []) // polygon + * query.where('loc').within([], []) // box + * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry + * + * ####NOTE: + * + * Must be used after `where()`. + * + * @memberOf Query + * @return {Query} this + * @api public + */ + +Query.prototype.within = function within () { + // opinionated, must be used after where + this._ensurePath('within'); + this._geoComparison = $withinCmd; + + if (0 === arguments.length) { + return this; + } + + if (2 === arguments.length) { + return this.box.apply(this, arguments); + } else if (2 < arguments.length) { + return this.polygon.apply(this, arguments); + } + + var area = arguments[0]; + + if (!area) + throw new TypeError('Invalid argument'); + + if (area.center) + return this.circle(area); + + if (area.box) + return this.box.apply(this, area.box); + + if (area.polygon) + return this.polygon.apply(this, area.polygon); + + if (area.type && area.coordinates) + return this.geometry(area); + + throw new TypeError('Invalid argument'); +} + +/** + * Specifies a $box condition + * + * ####Example + * + * var lowerLeft = [40.73083, -73.99756] + * var upperRight= [40.741404, -73.988135] + * + * query.where('loc').within().box(lowerLeft, upperRight) + * query.box('loc', lowerLeft, upperRight ) + * + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see Query#within #query_Query-within + * @param {String} path + * @param {Object} val + * @return {Query} this + * @api public + */ + +Query.prototype.box = function () { + var path, box; + + if (3 === arguments.length) { + // box('loc', [], []) + path = arguments[0]; + box = [arguments[1], arguments[2]]; + } else if (2 === arguments.length) { + // box([], []) + this._ensurePath('box'); + path = this._path; + box = [arguments[0], arguments[1]]; + } else { + throw new TypeError("Invalid argument"); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison || $withinCmd] = { '$box': box }; + return this; +} + +/** + * Specifies a $polygon condition + * + * ####Example + * + * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) + * query.polygon('loc', [10,20], [13, 25], [7,15]) + * + * @param {String|Array} [path] + * @param {Array|Object} [val] + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.polygon = function () { + var val, path; + + if ('string' == typeof arguments[0]) { + // polygon('loc', [],[],[]) + path = arguments[0]; + val = slice(arguments, 1); + } else { + // polygon([],[],[]) + this._ensurePath('polygon'); + path = this._path; + val = slice(arguments); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison || $withinCmd] = { '$polygon': val }; + return this; +} + +/** + * Specifies a $center or $centerSphere condition. + * + * ####Example + * + * var area = { center: [50, 50], radius: 10, unique: true } + * query.where('loc').within().circle(area) + * query.center('loc', area); + * + * // for spherical calculations + * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } + * query.where('loc').within().circle(area) + * query.center('loc', area); + * + * @param {String} [path] + * @param {Object} area + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.circle = function () { + var path, val; + + if (1 === arguments.length) { + this._ensurePath('circle'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } else { + throw new TypeError("Invalid argument"); + } + + if (!('radius' in val && val.center)) + throw new Error('center and radius are required'); + + var conds = this._conditions[path] || (this._conditions[path] = {}); + + var type = val.spherical + ? '$centerSphere' + : '$center'; + + var wKey = this._geoComparison || $withinCmd; + conds[wKey] = {}; + conds[wKey][type] = [val.center, val.radius]; + + if ('unique' in val) + conds[wKey].$uniqueDocs = !! val.unique; + + return this; +} + +/** + * Specifies a `$near` or `$nearSphere` condition + * + * These operators return documents sorted by distance. + * + * ####Example + * + * query.where('loc').near({ center: [10, 10] }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); + * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); + * query.near('loc', { center: [10, 10], maxDistance: 5 }); + * query.near({ center: { type: 'Point', coordinates: [..] }}) + * query.near().geometry({ type: 'Point', coordinates: [..] }) + * + * @param {String} [path] + * @param {Object} val + * @return {Query} this + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @api public + */ + +Query.prototype.near = function near () { + var path, val; + + this._geoComparison = '$near'; + + if (0 === arguments.length) { + return this; + } else if (1 === arguments.length) { + this._ensurePath('near'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + path = arguments[0]; + val = arguments[1]; + } else { + throw new TypeError("Invalid argument"); + } + + if (!val.center) { + throw new Error('center is required'); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + + var type = val.spherical + ? '$nearSphere' + : '$near'; + + // center could be a GeoJSON object or an Array + if (Array.isArray(val.center)) { + conds[type] = val.center; + + var radius = 'maxDistance' in val + ? val.maxDistance + : null; + + if (null != radius) { + conds.$maxDistance = radius; + } + } else { + // GeoJSON? + if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) { + throw new Error(util.format("Invalid GeoJSON specified for %s", type)); + } + conds[type] = { $geometry : val.center }; + + // MongoDB 2.6 insists on maxDistance being in $near / $nearSphere + if ('maxDistance' in val) { + conds[type]['$maxDistance'] = val.maxDistance; + } + } + + return this; +} + +/** + * Declares an intersects query for `geometry()`. + * + * ####Example + * + * query.where('path').intersects().geometry({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * query.where('path').intersects({ + * type: 'LineString' + * , coordinates: [[180.0, 11.0], [180, 9.0]] + * }) + * + * @param {Object} [arg] + * @return {Query} this + * @api public + */ + +Query.prototype.intersects = function intersects () { + // opinionated, must be used after where + this._ensurePath('intersects'); + + this._geoComparison = '$geoIntersects'; + + if (0 === arguments.length) { + return this; + } + + var area = arguments[0]; + + if (null != area && area.type && area.coordinates) + return this.geometry(area); + + throw new TypeError('Invalid argument'); +} + +/** + * Specifies a `$geometry` condition + * + * ####Example + * + * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] + * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) + * + * // or + * var polyB = [[ 0, 0 ], [ 1, 1 ]] + * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) + * + * // or + * var polyC = [ 0, 0 ] + * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) + * + * // or + * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) + * + * ####NOTE: + * + * `geometry()` **must** come after either `intersects()` or `within()`. + * + * The `object` argument must contain `type` and `coordinates` properties. + * - type {String} + * - coordinates {Array} + * + * The most recent path passed to `where()` is used. + * + * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. + * @return {Query} this + * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry + * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing + * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ + * @api public + */ + +Query.prototype.geometry = function geometry () { + if (!('$within' == this._geoComparison || + '$geoWithin' == this._geoComparison || + '$near' == this._geoComparison || + '$geoIntersects' == this._geoComparison)) { + throw new Error('geometry() must come after `within()`, `intersects()`, or `near()'); + } + + var val, path; + + if (1 === arguments.length) { + this._ensurePath('geometry'); + path = this._path; + val = arguments[0]; + } else { + throw new TypeError("Invalid argument"); + } + + if (!(val.type && Array.isArray(val.coordinates))) { + throw new TypeError('Invalid argument'); + } + + var conds = this._conditions[path] || (this._conditions[path] = {}); + conds[this._geoComparison] = { $geometry: val }; + + return this; +} + +// end spatial + +/** + * Specifies which document fields to include or exclude + * + * ####String syntax + * + * When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. + * + * ####Example + * + * // include a and b, exclude c + * query.select('a b -c'); + * + * // or you may use object notation, useful when + * // you have keys already prefixed with a "-" + * query.select({a: 1, b: 1, c: 0}); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @see SchemaType + * @api public + */ + +Query.prototype.select = function select () { + var arg = arguments[0]; + if (!arg) return this; + + if (arguments.length !== 1) { + throw new Error("Invalid select: select only takes 1 argument"); + } + + this._validate('select'); + + var fields = this._fields || (this._fields = {}); + var type = typeof arg; + + if ('string' == type || 'object' == type && 'number' == typeof arg.length && !Array.isArray(arg)) { + if ('string' == type) + arg = arg.split(/\s+/); + + for (var i = 0, len = arg.length; i < len; ++i) { + var field = arg[i]; + if (!field) continue; + var include = '-' == field[0] ? 0 : 1; + if (include === 0) field = field.substring(1); + fields[field] = include; + } + + return this; + } + + if (utils.isObject(arg) && !Array.isArray(arg)) { + var keys = utils.keys(arg); + for (var i = 0; i < keys.length; ++i) { + fields[keys[i]] = arg[keys[i]]; + } + return this; + } + + throw new TypeError('Invalid select() argument. Must be string or object.'); +} + +/** + * Specifies a $slice condition for a `path` + * + * ####Example + * + * query.slice('comments', 5) + * query.slice('comments', -5) + * query.slice('comments', [10, 5]) + * query.where('comments').slice(5) + * query.where('comments').slice([-10, 5]) + * + * @param {String} [path] + * @param {Number} val number/range of elements to slice + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements + * @api public + */ + +Query.prototype.slice = function () { + if (0 === arguments.length) + return this; + + this._validate('slice'); + + var path, val; + + if (1 === arguments.length) { + var arg = arguments[0]; + if (typeof arg === 'object' && !Array.isArray(arg)) { + var keys = Object.keys(arg); + var numKeys = keys.length; + for (var i = 0; i < numKeys; ++i) { + this.slice(keys[i], arg[keys[i]]); + } + return this; + } + this._ensurePath('slice'); + path = this._path; + val = arguments[0]; + } else if (2 === arguments.length) { + if ('number' === typeof arguments[0]) { + this._ensurePath('slice'); + path = this._path; + val = slice(arguments); + } else { + path = arguments[0]; + val = arguments[1]; + } + } else if (3 === arguments.length) { + path = arguments[0]; + val = slice(arguments, 1); + } + + var myFields = this._fields || (this._fields = {}); + myFields[path] = { '$slice': val }; + return this; +} + +/** + * Sets the sort order + * + * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1. + * + * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. + * + * ####Example + * + * // these are equivalent + * query.sort({ field: 'asc', test: -1 }); + * query.sort('field -test'); + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object|String} arg + * @return {Query} this + * @api public + */ + +Query.prototype.sort = function (arg) { + if (!arg) return this; + + this._validate('sort'); + + var type = typeof arg; + + if (1 === arguments.length && 'string' == type) { + arg = arg.split(/\s+/); + + for (var i = 0, len = arg.length; i < len; ++i) { + var field = arg[i]; + if (!field) continue; + var ascend = '-' == field[0] ? -1 : 1; + if (ascend === -1) field = field.substring(1); + push(this.options, field, ascend); + } + + return this; + } + + if (utils.isObject(arg)) { + var keys = utils.keys(arg); + for (var i = 0; i < keys.length; ++i) { + var field = keys[i]; + push(this.options, field, arg[field]); + } + + return this; + } + + throw new TypeError('Invalid sort() argument. Must be a string or object.'); +} + +/*! + * @ignore + */ + +function push (opts, field, value) { + if (value && value.$meta) { + var s = opts.sort || (opts.sort = {}); + s[field] = { $meta : value.$meta }; + return; + } + + var val = String(value || 1).toLowerCase(); + if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) { + if (utils.isArray(value)) value = '['+value+']'; + throw new TypeError('Invalid sort value: {' + field + ': ' + value + ' }'); + } + // store `sort` in a sane format + var s = opts.sort || (opts.sort = {}); + var valueStr = value.toString() + .replace("asc", "1") + .replace("ascending", "1") + .replace("desc", "-1") + .replace("descending", "-1"); + s[field] = parseInt(valueStr, 10); +} + +/** + * Specifies the limit option. + * + * ####Example + * + * query.limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method limit + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D + * @api public + */ +/** + * Specifies the skip option. + * + * ####Example + * + * query.skip(100).limit(20) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method skip + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D + * @api public + */ +/** + * Specifies the maxScan option. + * + * ####Example + * + * query.maxScan(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method maxScan + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan + * @api public + */ +/** + * Specifies the batchSize option. + * + * ####Example + * + * query.batchSize(100) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method batchSize + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D + * @api public + */ +/** + * Specifies the `comment` option. + * + * ####Example + * + * query.comment('login query') + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @method comment + * @memberOf Query + * @param {Number} val + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment + * @api public + */ + +/*! + * limit, skip, maxScan, batchSize, comment + * + * Sets these associated options. + * + * query.comment('feed query'); + */ + +;['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function (method) { + Query.prototype[method] = function (v) { + this._validate(method); + this.options[method] = v; + return this; + }; +}) + +/** + * Specifies the maxTimeMS option. + * + * ####Example + * + * query.maxTime(100) + * + * @method maxTime + * @memberOf Query + * @param {Number} val + * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS + * @api public + */ + +Query.prototype.maxTime = function (v) { + this._validate('maxTime'); + this.options.maxTimeMS = v; + return this; +}; + +/** + * Specifies this query as a `snapshot` query. + * + * ####Example + * + * mquery().snapshot() // true + * mquery().snapshot(true) + * mquery().snapshot(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D + * @return {Query} this + * @api public + */ + +Query.prototype.snapshot = function () { + this._validate('snapshot'); + + this.options.snapshot = arguments.length + ? !! arguments[0] + : true + + return this; +} + +/** + * Sets query hints. + * + * ####Example + * + * query.hint({ indexA: 1, indexB: -1}) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Object} val a hint object + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint + * @api public + */ + +Query.prototype.hint = function () { + if (0 === arguments.length) return this; + + this._validate('hint'); + + var arg = arguments[0]; + if (utils.isObject(arg)) { + var hint = this.options.hint || (this.options.hint = {}); + + // must keep object keys in order so don't use Object.keys() + for (var k in arg) { + hint[k] = arg[k]; + } + + return this; + } + + throw new TypeError('Invalid hint. ' + arg); +} + +/** + * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences. + * + * ####Example: + * + * query.slaveOk() // true + * query.slaveOk(true) + * query.slaveOk(false) + * + * @deprecated use read() preferences instead if on mongodb >= 2.2 + * @param {Boolean} v defaults to true + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see read() + * @return {Query} this + * @api public + */ + +Query.prototype.slaveOk = function (v) { + this.options.slaveOk = arguments.length ? !!v : true; + return this; +} + +/** + * Sets the readPreference option for the query. + * + * ####Example: + * + * new Query().read('primary') + * new Query().read('p') // same as primary + * + * new Query().read('primaryPreferred') + * new Query().read('pp') // same as primaryPreferred + * + * new Query().read('secondary') + * new Query().read('s') // same as secondary + * + * new Query().read('secondaryPreferred') + * new Query().read('sp') // same as secondaryPreferred + * + * new Query().read('nearest') + * new Query().read('n') // same as nearest + * + * // you can also use mongodb.ReadPreference class to also specify tags + * new Query().read(mongodb.ReadPreference('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])) + * + * ####Preferences: + * + * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. + * secondary Read from secondary if available, otherwise error. + * primaryPreferred Read from primary if available, otherwise a secondary. + * secondaryPreferred Read from a secondary if available, otherwise read from the primary. + * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. + * + * Aliases + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). + * + * @param {String|ReadPreference} pref one of the listed preference options or their aliases + * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference + * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences + * @return {Query} this + * @api public + */ + +Query.prototype.read = function (pref) { + if (arguments.length > 1 && !Query.prototype.read.deprecationWarningIssued) { + console.error("Deprecation warning: 'tags' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead."); + Query.prototype.read.deprecationWarningIssued = true; + } + this.options.readPreference = utils.readPref(pref); + return this; +} + +/** + * Sets tailable option. + * + * ####Example + * + * query.tailable() <== true + * query.tailable(true) + * query.tailable(false) + * + * ####Note + * + * Cannot be used with `distinct()` + * + * @param {Boolean} v defaults to true + * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors + * @api public + */ + +Query.prototype.tailable = function () { + this._validate('tailable'); + + this.options.tailable = arguments.length + ? !! arguments[0] + : true; + + return this; +} + +/** + * Merges another Query or conditions object into this one. + * + * When a Query is passed, conditions, field selection and options are merged. + * + * @param {Query|Object} source + * @return {Query} this + */ + +Query.prototype.merge = function (source) { + if (!source) + return this; + + if (!Query.canMerge(source)) + throw new TypeError('Invalid argument. Expected instanceof mquery or plain object'); + + if (source instanceof Query) { + // if source has a feature, apply it to ourselves + + if (source._conditions) { + utils.merge(this._conditions, source._conditions); + } + + if (source._fields) { + this._fields || (this._fields = {}); + utils.merge(this._fields, source._fields); + } + + if (source.options) { + this.options || (this.options = {}); + utils.merge(this.options, source.options); + } + + if (source._update) { + this._update || (this._update = {}); + utils.mergeClone(this._update, source._update); + } + + if (source._distinct) { + this._distinct = source._distinct; + } + + return this; + } + + // plain object + utils.merge(this._conditions, source); + + return this; +} + +/** + * Finds documents. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.find() + * query.find(callback) + * query.find({ name: 'Burning Lights' }, callback) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.find = function (criteria, callback) { + this.op = 'find'; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + var self = this + , conds = this._conditions + , options = this._optionsForExec() + + options.fields = this._fieldsForExec() + + debug('find', this._collection.collectionName, conds, options); + callback = this._wrapCallback('find', callback, { + conditions: conds + , options: options + }); + + this._collection.find(conds, options, utils.tick(callback)); + return this; +} + +/** + * Executes the query as a findOne() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.findOne().where('name', /^Burning/); + * + * query.findOne({ name: /^Burning/ }) + * + * query.findOne({ name: /^Burning/ }, callback); // executes + * + * query.findOne(function (err, doc) { + * if (err) return handleError(err); + * if (doc) { + * // doc may be null if no document matched + * + * } + * }); + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.findOne = function (criteria, callback) { + this.op = 'findOne'; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + var self = this + , conds = this._conditions + , options = this._optionsForExec() + + options.fields = this._fieldsForExec(); + + debug('findOne', this._collection.collectionName, conds, options); + callback = this._wrapCallback('findOne', callback, { + conditions: conds + , options: options + }); + + this._collection.findOne(conds, options, utils.tick(callback)); + + return this; +} + +/** + * Exectues the query as a count() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * query.count().where('color', 'black').exec(callback); + * + * query.count({ color: 'black' }).count(callback) + * + * query.count({ color: 'black' }, callback) + * + * query.where('color', 'black').count(function (err, count) { + * if (err) return handleError(err); + * console.log('there are %d kittens', count); + * }) + * + * @param {Object} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count + * @api public + */ + +Query.prototype.count = function (criteria, callback) { + this.op = 'count'; + this._validate(); + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) return this; + + var conds = this._conditions + , options = this._optionsForExec() + + debug('count', this._collection.collectionName, conds, options); + callback = this._wrapCallback('count', callback, { + conditions: conds + , options: options + }); + + this._collection.count(conds, options, utils.tick(callback)); + return this; +} + +/** + * Declares or executes a distinct() operation. + * + * Passing a `callback` executes the query. + * + * ####Example + * + * distinct(criteria, field, fn) + * distinct(criteria, field) + * distinct(field, fn) + * distinct(field) + * distinct(fn) + * distinct() + * + * @param {Object|Query} [criteria] + * @param {String} [field] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct + * @api public + */ + +Query.prototype.distinct = function (criteria, field, callback) { + this.op = 'distinct'; + this._validate(); + + if (!callback) { + switch (typeof field) { + case 'function': + callback = field; + if ('string' == typeof criteria) { + field = criteria; + criteria = undefined; + } + break; + case 'undefined': + case 'string': + break; + default: + throw new TypeError('Invalid `field` argument. Must be string or function') + break; + } + + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = field = undefined; + break; + case 'string': + field = criteria; + criteria = undefined; + break; + } + } + + if ('string' == typeof field) { + this._distinct = field; + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (!callback) { + return this; + } + + if (!this._distinct) { + throw new Error('No value for `distinct` has been declared'); + } + + var conds = this._conditions + , options = this._optionsForExec() + + debug('distinct', this._collection.collectionName, conds, options); + callback = this._wrapCallback('distinct', callback, { + conditions: conds + , options: options + }); + + this._collection.distinct(this._distinct, conds, options, utils.tick(callback)); + + return this; +} + +/** + * Declare and/or execute this query as an update() operation. + * + * _All paths passed that are not $atomic operations will become $set ops._ + * + * ####Example + * + * mquery({ _id: id }).update({ title: 'words' }, ...) + * + * becomes + * + * collection.update({ _id: id }, { $set: { title: 'words' }}, ...) + * + * ####Note + * + * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. + * + * var q = mquery(collection).where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).update(); // not executed + * + * var q = mquery(collection).where({ _id: id }); + * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe + * + * // keys that are not $atomic ops become $set. + * // this executes the same command as the previous example. + * q.update({ name: 'bob' }).where({ _id: id }).exec(); + * + * var q = mquery(collection).update(); // not executed + * + * // overwriting with empty docs + * var q.where({ _id: id }).setOptions({ overwrite: true }) + * q.update({ }, callback); // executes + * + * // multi update with overwrite to empty doc + * var q = mquery(collection).where({ _id: id }); + * q.setOptions({ multi: true, overwrite: true }) + * q.update({ }); + * q.update(callback); // executed + * + * // multi updates + * mquery() + * .collection(coll) + * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) + * // more multi updates + * mquery({ }) + * .collection(coll) + * .setOptions({ multi: true }) + * .update({ $set: { arr: [] }}, callback) + * + * // single update by default + * mquery({ email: 'address@example.com' }) + * .collection(coll) + * .update({ $inc: { counter: 1 }}, callback) + * + * // summary + * update(criteria, doc, opts, cb) // executes + * update(criteria, doc, opts) + * update(criteria, doc, cb) // executes + * update(criteria, doc) + * update(doc, cb) // executes + * update(doc) + * update(cb) // executes + * update(true) // executes (unsafe write) + * update() + * + * @param {Object} [criteria] + * @param {Object} [doc] the update command + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.update = function update (criteria, doc, options, callback) { + this.op = 'update'; + var force; + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = undefined; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + break; + case 1: + switch (typeof criteria) { + case 'function': + callback = criteria; + criteria = options = doc = undefined; + break; + case 'boolean': + // execution with no callback (unsafe write) + force = criteria; + criteria = undefined; + break; + default: + doc = criteria; + criteria = options = undefined; + break; + } + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + if (doc) { + this._mergeUpdate(doc); + } + + if (utils.isObject(options)) { + // { overwrite: true } + this.setOptions(options); + } + + // we are done if we don't have callback and they are + // not forcing an unsafe write. + if (!(force || callback)) + return this; + + if (!this._update || + !this.options.overwrite && 0 === utils.keys(this._update).length) { + callback && utils.soon(callback.bind(null, null, 0)); + return this; + } + + options = this._optionsForExec(); + if (!callback) options.safe = false; + + var criteria = this._conditions; + doc = this._updateForExec(); + + debug('update', this._collection.collectionName, criteria, doc, options); + callback = this._wrapCallback('update', callback, { + conditions: criteria + , doc: doc + , options: options + }); + + this._collection.update(criteria, doc, options, utils.tick(callback)); + + return this; +} + +/** + * Declare and/or execute this query as a remove() operation. + * + * ####Example + * + * mquery(collection).remove({ artist: 'Anne Murray' }, callback) + * + * ####Note + * + * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. + * + * // not executed + * var query = mquery(collection).remove({ name: 'Anne Murray' }) + * + * // executed + * mquery(collection).remove({ name: 'Anne Murray' }, callback) + * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback) + * + * // executed without a callback (unsafe write) + * query.exec() + * + * // summary + * query.remove(conds, fn); // executes + * query.remove(conds) + * query.remove(fn) // executes + * query.remove() + * + * @param {Object|Query} [criteria] mongodb selector + * @param {Function} [callback] + * @return {Query} this + * @api public + */ + +Query.prototype.remove = function (criteria, callback) { + this.op = 'remove'; + var force; + + if ('function' === typeof criteria) { + callback = criteria; + criteria = undefined; + } else if (Query.canMerge(criteria)) { + this.merge(criteria); + } else if (true === criteria) { + force = criteria; + criteria = undefined; + } + + if (!(force || callback)) + return this; + + var options = this._optionsForExec() + if (!callback) options.safe = false; + + var conds = this._conditions; + + debug('remove', this._collection.collectionName, conds, options); + callback = this._wrapCallback('remove', callback, { + conditions: conds + , options: options + }); + + this._collection.remove(conds, options, utils.tick(callback)); + + return this; +} + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. + * + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. + * + * ####Available options + * + * - `new`: bool - true to return the modified document rather than the original. defaults to true + * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * + * ####Examples + * + * query.findOneAndUpdate(conditions, update, options, callback) // executes + * query.findOneAndUpdate(conditions, update, options) // returns Query + * query.findOneAndUpdate(conditions, update, callback) // executes + * query.findOneAndUpdate(conditions, update) // returns Query + * query.findOneAndUpdate(update, callback) // returns Query + * query.findOneAndUpdate(update) // returns Query + * query.findOneAndUpdate(callback) // executes + * query.findOneAndUpdate() // returns Query + * + * @param {Object|Query} [query] + * @param {Object} [doc] + * @param {Object} [options] + * @param {Function} [callback] + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @return {Query} this + * @api public + */ + +Query.prototype.findOneAndUpdate = function (criteria, doc, options, callback) { + this.op = 'findOneAndUpdate'; + this._validate(); + + switch (arguments.length) { + case 3: + if ('function' == typeof options) { + callback = options; + options = {}; + } + break; + case 2: + if ('function' == typeof doc) { + callback = doc; + doc = criteria; + criteria = undefined; + } + options = undefined; + break; + case 1: + if ('function' == typeof criteria) { + callback = criteria; + criteria = options = doc = undefined; + } else { + doc = criteria; + criteria = options = undefined; + } + } + + if (Query.canMerge(criteria)) { + this.merge(criteria); + } + + // apply doc + if (doc) { + this._mergeUpdate(doc); + } + + options && this.setOptions(options); + + if (!callback) return this; + return this._findAndModify('update', callback); +} + +/** + * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. + * + * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. + * + * ####Available options + * + * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update + * + * ####Examples + * + * A.where().findOneAndRemove(conditions, options, callback) // executes + * A.where().findOneAndRemove(conditions, options) // return Query + * A.where().findOneAndRemove(conditions, callback) // executes + * A.where().findOneAndRemove(conditions) // returns Query + * A.where().findOneAndRemove(callback) // executes + * A.where().findOneAndRemove() // returns Query + * + * @param {Object} [conditions] + * @param {Object} [options] + * @param {Function} [callback] + * @return {Query} this + * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command + * @api public + */ + +Query.prototype.findOneAndRemove = function (conditions, options, callback) { + this.op = 'findOneAndRemove'; + this._validate(); + + if ('function' == typeof options) { + callback = options; + options = undefined; + } else if ('function' == typeof conditions) { + callback = conditions; + conditions = undefined; + } + + // apply conditions + if (Query.canMerge(conditions)) { + this.merge(conditions); + } + + // apply options + options && this.setOptions(options); + + if (!callback) return this; + + return this._findAndModify('remove', callback); +} + +/** + * _findAndModify + * + * @param {String} type - either "remove" or "update" + * @param {Function} callback + * @api private + */ + +Query.prototype._findAndModify = function (type, callback) { + assert.equal('function', typeof callback); + + var opts = this._optionsForExec() + , self = this + , fields + , sort + , doc + + if ('remove' == type) { + opts.remove = true; + } else { + if (!('new' in opts)) opts.new = true; + if (!('upsert' in opts)) opts.upsert = false; + + doc = this._updateForExec() + if (!doc) { + if (opts.upsert) { + // still need to do the upsert to empty doc + doc = { $set: {} }; + } else { + return this.findOne(callback); + } + } + } + + var fields = this._fieldsForExec(); + if (fields) { + opts.fields = fields; + } + + var conds = this._conditions; + + debug('findAndModify', this._collection.collectionName, conds, doc, opts); + callback = this._wrapCallback('findAndModify', callback, { + conditions: conds + , doc: doc + , options: opts + }); + + this._collection + .findAndModify(conds, doc, opts, utils.tick(callback)); + + return this; +} + +/** + * Wrap callback to add tracing + * + * @param {Function} callback + * @param {Object} [queryInfo] + * @api private + */ +Query.prototype._wrapCallback = function (method, callback, queryInfo) { + var traceFunction = this._traceFunction || Query.traceFunction; + + if (traceFunction) { + queryInfo.collectionName = this._collection.collectionName; + + var traceCallback = traceFunction && + traceFunction.call(null, method, queryInfo, this); + + var startTime = new Date().getTime(); + + return function wrapperCallback (err, result) { + if (traceCallback) { + var millis = new Date().getTime() - startTime; + traceCallback.call(null, err, result, millis); + } + + if (callback) { + callback.apply(null, arguments); + } + }; + } + + return callback; +} + +/** + * Add trace function that gets called when the query is executed. + * The function will be called with (method, queryInfo, query) and + * should return a callback function which will be called + * with (err, result, millis) when the query is complete. + * + * queryInfo is an object containing: { + * collectionName: , + * conditions: , + * options: , + * doc: [document to update, if applicable] + * } + * + * NOTE: Does not trace stream queries. + * + * @param {Function} traceFunction + * @return {Query} this + * @api public + */ +Query.prototype.setTraceFunction = function (traceFunction) { + this._traceFunction = traceFunction; + return this; +} + +/** + * Executes the query + * + * ####Examples + * + * query.exec(); + * query.exec(callback); + * query.exec('update'); + * query.exec('find', callback); + * + * @param {String|Function} [operation] + * @param {Function} [callback] + * @api public + */ + +Query.prototype.exec = function exec (op, callback) { + switch (typeof op) { + case 'function': + callback = op; + op = null; + break; + case 'string': + this.op = op; + break; + } + + assert.ok(this.op, "Missing query type: (find, update, etc)"); + + if ('update' == this.op || 'remove' == this.op) { + callback || (callback = true); + } + + this[this.op](callback); +} + +/** + * Returns a thunk which when called runs this.exec() + * + * The thunk receives a callback function which will be + * passed to `this.exec()` + * + * @return {Function} + * @api public + */ + +Query.prototype.thunk = function() { + var self = this; + return function(cb) { + self.exec(cb); + } +} + +/** + * Executes the query returning a `Promise` which will be + * resolved with either the doc(s) or rejected with the error. + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @return {Promise} + * @api public + */ + +Query.prototype.then = function(resolve, reject) { + var self = this; + var promise = new Query.Promise(function(success, error) { + self.exec(function(err, val) { + if (err) error(err); + else success(val); + self = success = error = null; + }); + }); + return promise.then(resolve, reject); +} + +/** + * Returns a stream for the given find query. + * + * @throws Error if operation is not a find + * @returns {Stream} Node 0.8 style + */ + +Query.prototype.stream = function(streamOptions) { + if ('find' != this.op) + throw new Error('stream() is only available for find'); + + var conds = this._conditions; + + var options = this._optionsForExec() + options.fields = this._fieldsForExec() + + debug('stream', this._collection.collectionName, conds, options, streamOptions); + + return this._collection.findStream(conds, options, streamOptions); +} + +/** + * Determines if field selection has been made. + * + * @return {Boolean} + * @api public + */ + +Query.prototype.selected = function selected () { + return !! (this._fields && Object.keys(this._fields).length > 0); +} + +/** + * Determines if inclusive field selection has been made. + * + * query.selectedInclusively() // false + * query.select('name') + * query.selectedInclusively() // true + * query.selectedExlusively() // false + * + * @returns {Boolean} + */ + +Query.prototype.selectedInclusively = function selectedInclusively () { + if (!this._fields) return false; + + var keys = Object.keys(this._fields); + if (0 === keys.length) return false; + + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (0 === this._fields[key]) return false; + if (this._fields[key] && + typeof this._fields[key] === 'object' && + this._fields[key].$meta) { + return false; + } + } + + return true; +} + +/** + * Determines if exclusive field selection has been made. + * + * query.selectedExlusively() // false + * query.select('-name') + * query.selectedExlusively() // true + * query.selectedInclusively() // false + * + * @returns {Boolean} + */ + +Query.prototype.selectedExclusively = function selectedExclusively () { + if (!this._fields) return false; + + var keys = Object.keys(this._fields); + if (0 === keys.length) return false; + + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (0 === this._fields[key]) return true; + } + + return false; +} + +/** + * Merges `doc` with the current update object. + * + * @param {Object} doc + */ + +Query.prototype._mergeUpdate = function (doc) { + if (!this._update) this._update = {}; + if (doc instanceof Query) { + if (doc._update) { + utils.mergeClone(this._update, doc._update); + } + } else { + utils.mergeClone(this._update, doc); + } +} + +/** + * Returns default options. + * + * @return {Object} + * @api private + */ + +Query.prototype._optionsForExec = function () { + var options = utils.clone(this.options, { retainKeyOrder: true }); + return options; +} + +/** + * Returns fields selection for this query. + * + * @return {Object} + * @api private + */ + +Query.prototype._fieldsForExec = function () { + return utils.clone(this._fields, { retainKeyOrder: true }); +} + +/** + * Return an update document with corrected $set operations. + * + * @api private + */ + +Query.prototype._updateForExec = function () { + var update = utils.clone(this._update, { retainKeyOrder: true }) + , ops = utils.keys(update) + , i = ops.length + , ret = {} + , hasKeys + , val + + while (i--) { + var op = ops[i]; + + if (this.options.overwrite) { + ret[op] = update[op]; + continue; + } + + if ('$' !== op[0]) { + // fix up $set sugar + if (!ret.$set) { + if (update.$set) { + ret.$set = update.$set; + } else { + ret.$set = {}; + } + } + ret.$set[op] = update[op]; + ops.splice(i, 1); + if (!~ops.indexOf('$set')) ops.push('$set'); + } else if ('$set' === op) { + if (!ret.$set) { + ret[op] = update[op]; + } + } else { + ret[op] = update[op]; + } + } + + return ret; +} + +/** + * Make sure _path is set. + * + * @parmam {String} method + */ + +Query.prototype._ensurePath = function (method) { + if (!this._path) { + var msg = method + '() must be used after where() ' + + 'when called with these arguments' + throw new Error(msg); + } +} + +/*! + * Permissions + */ + +Query.permissions = require('./permissions'); + +Query._isPermitted = function (a, b) { + var denied = Query.permissions[b]; + if (!denied) return true; + return true !== denied[a]; +} + +Query.prototype._validate = function (action) { + var fail; + var validator; + + if (undefined === action) { + + validator = Query.permissions[this.op]; + if ('function' != typeof validator) return true; + + fail = validator(this); + + } else if (!Query._isPermitted(action, this.op)) { + fail = action; + } + + if (fail) { + throw new Error(fail + ' cannot be used with ' + this.op); + } +} + +/** + * Determines if `conds` can be merged using `mquery().merge()` + * + * @param {Object} conds + * @return {Boolean} + */ + +Query.canMerge = function (conds) { + return conds instanceof Query || utils.isObject(conds); +} + +/** + * Set a trace function that will get called whenever a + * query is executed. + * + * See `setTraceFunction()` for details. + * + * @param {Object} conds + * @return {Boolean} + */ +Query.setGlobalTraceFunction = function (traceFunction) { + Query.traceFunction = traceFunction; +} + +/*! + * Exports. + */ + +Query.utils = utils; +Query.env = require('./env') +Query.Collection = require('./collection'); +Query.BaseCollection = require('./collection/collection'); +Query.Promise = require('bluebird'); +module.exports = exports = Query; + +// TODO +// test utils diff --git a/5-3/node_modules/mongoose/node_modules/mquery/lib/permissions.js b/5-3/node_modules/mongoose/node_modules/mquery/lib/permissions.js new file mode 100644 index 0000000..5008a97 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/lib/permissions.js @@ -0,0 +1,90 @@ +'use strict'; + +var denied = exports; + +denied.distinct = function (self) { + if (self._fields && Object.keys(self._fields).length > 0) { + return 'field selection and slice' + } + + var keys = Object.keys(denied.distinct); + var err; + + keys.every(function (option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +}; +denied.distinct.select = +denied.distinct.slice = +denied.distinct.sort = +denied.distinct.limit = +denied.distinct.skip = +denied.distinct.batchSize = +denied.distinct.comment = +denied.distinct.maxScan = +denied.distinct.snapshot = +denied.distinct.hint = +denied.distinct.tailable = true; + + +// aggregation integration + + +denied.findOneAndUpdate = +denied.findOneAndRemove = function (self) { + var keys = Object.keys(denied.findOneAndUpdate); + var err; + + keys.every(function (option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +} +denied.findOneAndUpdate.limit = +denied.findOneAndUpdate.skip = +denied.findOneAndUpdate.batchSize = +denied.findOneAndUpdate.maxScan = +denied.findOneAndUpdate.snapshot = +denied.findOneAndUpdate.hint = +denied.findOneAndUpdate.tailable = +denied.findOneAndUpdate.comment = true; + + +denied.count = function (self) { + if (self._fields && Object.keys(self._fields).length > 0) { + return 'field selection and slice' + } + + var keys = Object.keys(denied.count); + var err; + + keys.every(function (option) { + if (self.options[option]) { + err = option; + return false; + } + return true; + }); + + return err; +} + +denied.count.select = +denied.count.slice = +denied.count.sort = +denied.count.batchSize = +denied.count.comment = +denied.count.maxScan = +denied.count.snapshot = +denied.count.tailable = true; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/lib/utils.js b/5-3/node_modules/mongoose/node_modules/mquery/lib/utils.js new file mode 100644 index 0000000..6707ce2 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/lib/utils.js @@ -0,0 +1,331 @@ +'use strict'; + +/*! + * Module dependencies. + */ + +var RegExpClone = require('regexp-clone') + +/** + * Clones objects + * + * @param {Object} obj the object to clone + * @param {Object} options + * @return {Object} the cloned object + * @api private + */ + +var clone = exports.clone = function clone (obj, options) { + if (obj === undefined || obj === null) + return obj; + + if (Array.isArray(obj)) + return exports.cloneArray(obj, options); + + if (obj.constructor) { + if (/ObjectI[dD]$/.test(obj.constructor.name)) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.id); + } + + if ('ReadPreference' === obj._type && obj.isValid && obj.toObject) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.mode, clone(obj.tags, options)); + } + + if ('Binary' == obj._bsontype && obj.buffer && obj.value) { + return 'function' == typeof obj.clone + ? obj.clone() + : new obj.constructor(obj.value(true), obj.sub_type); + } + + if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) + return new obj.constructor(+obj); + + if ('RegExp' === obj.constructor.name) + return RegExpClone(obj); + + if ('Buffer' === obj.constructor.name) + return exports.cloneBuffer(obj); + } + + if (isObject(obj)) + return exports.cloneObject(obj, options); + + if (obj.valueOf) + return obj.valueOf(); +}; + +/*! + * ignore + */ + +var cloneObject = exports.cloneObject = function cloneObject (obj, options) { + var retainKeyOrder = options && options.retainKeyOrder + , minimize = options && options.minimize + , ret = {} + , hasKeys + , keys + , val + , k + , i + + if (retainKeyOrder) { + for (k in obj) { + val = clone(obj[k], options); + + if (!minimize || ('undefined' !== typeof val)) { + hasKeys || (hasKeys = true); + ret[k] = val; + } + } + } else { + // faster + + keys = Object.keys(obj); + i = keys.length; + + while (i--) { + k = keys[i]; + val = clone(obj[k], options); + + if (!minimize || ('undefined' !== typeof val)) { + if (!hasKeys) hasKeys = true; + ret[k] = val; + } + } + } + + return minimize + ? hasKeys && ret + : ret; +}; + +var cloneArray = exports.cloneArray = function cloneArray (arr, options) { + var ret = []; + for (var i = 0, l = arr.length; i < l; i++) + ret.push(clone(arr[i], options)); + return ret; +}; + +/** + * process.nextTick helper. + * + * Wraps the given `callback` in a try/catch. If an error is + * caught it will be thrown on nextTick. + * + * node-mongodb-native had a habit of state corruption when + * an error was immediately thrown from within a collection + * method (find, update, etc) callback. + * + * @param {Function} [callback] + * @api private + */ + +var tick = exports.tick = function tick (callback) { + if ('function' !== typeof callback) return; + return function () { + // callbacks should always be fired on the next + // turn of the event loop. A side benefit is + // errors thrown from executing the callback + // will not cause drivers state to be corrupted + // which has historically been a problem. + var args = arguments; + soon(function(){ + callback.apply(this, args); + }); + } +} + +/** + * Merges `from` into `to` without overwriting existing properties. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +var merge = exports.merge = function merge (to, from) { + var keys = Object.keys(from) + , i = keys.length + , key + + while (i--) { + key = keys[i]; + if ('undefined' === typeof to[key]) { + to[key] = from[key]; + } else { + if (exports.isObject(from[key])) { + merge(to[key], from[key]); + } else { + to[key] = from[key]; + } + } + } +} + +/** + * Same as merge but clones the assigned values. + * + * @param {Object} to + * @param {Object} from + * @api private + */ + +var mergeClone = exports.mergeClone = function mergeClone (to, from) { + var keys = Object.keys(from) + , i = keys.length + , key + + while (i--) { + key = keys[i]; + if ('undefined' === typeof to[key]) { + // make sure to retain key order here because of a bug handling the $each + // operator in mongodb 2.4.4 + to[key] = clone(from[key], { retainKeyOrder : 1}); + } else { + if (exports.isObject(from[key])) { + mergeClone(to[key], from[key]); + } else { + // make sure to retain key order here because of a bug handling the + // $each operator in mongodb 2.4.4 + to[key] = clone(from[key], { retainKeyOrder : 1}); + } + } + } +} + +/** + * Read pref helper (mongo 2.2 drivers support this) + * + * Allows using aliases instead of full preference names: + * + * p primary + * pp primaryPreferred + * s secondary + * sp secondaryPreferred + * n nearest + * + * @param {String} pref + */ + +exports.readPref = function readPref (pref) { + switch (pref) { + case 'p': + pref = 'primary'; + break; + case 'pp': + pref = 'primaryPreferred'; + break; + case 's': + pref = 'secondary'; + break; + case 'sp': + pref = 'secondaryPreferred'; + break; + case 'n': + pref = 'nearest'; + break; + } + + return pref; +} + +/** + * Object.prototype.toString.call helper + */ + +var _toString = Object.prototype.toString; +var toString = exports.toString = function (arg) { + return _toString.call(arg); +} + +/** + * Determines if `arg` is an object. + * + * @param {Object|Array|String|Function|RegExp|any} arg + * @return {Boolean} + */ + +var isObject = exports.isObject = function (arg) { + return '[object Object]' == exports.toString(arg); +} + +/** + * Determines if `arg` is an array. + * + * @param {Object} + * @return {Boolean} + * @see nodejs utils + */ + +var isArray = exports.isArray = function (arg) { + return Array.isArray(arg) || + 'object' == typeof arg && '[object Array]' == exports.toString(arg); +} + +/** + * Object.keys helper + */ + +exports.keys = Object.keys || function (obj) { + var keys = []; + for (var k in obj) if (obj.hasOwnProperty(k)) { + keys.push(k); + } + return keys; +} + +/** + * Basic Object.create polyfill. + * Only one argument is supported. + * + * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create + */ + +exports.create = 'function' == typeof Object.create + ? Object.create + : create; + +function create (proto) { + if (arguments.length > 1) { + throw new Error("Adding properties is not supported") + } + + function F () {} + F.prototype = proto; + return new F; +} + +/** + * inheritance + */ + +exports.inherits = function (ctor, superCtor) { + ctor.prototype = exports.create(superCtor.prototype); + ctor.prototype.constructor = ctor; +} + +/** + * nextTick helper + * compat with node 0.10 which behaves differently than previous versions + */ + +var soon = exports.soon = 'function' == typeof setImmediate + ? setImmediate + : process.nextTick; + +/** + * Clones the contents of a buffer. + * + * @param {Buffer} buff + * @return {Buffer} + */ + +exports.cloneBuffer = function (buff) { + var dupe = new Buffer(buff.length); + buff.copy(dupe, 0, 0, buff.length); + return dupe; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE new file mode 100644 index 0000000..a3966cf --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Petka Antonov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions:

+ +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md new file mode 100644 index 0000000..5e92095 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md @@ -0,0 +1,676 @@ + + Promises/A+ logo + +[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) +[![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) + + +# Introduction + +Bluebird is a fully featured [promise](#what-are-promises-and-why-should-i-use-them) library with focus on innovative features and performance + + + +# Topics + +- [Features](#features) +- [Quick start](#quick-start) +- [API Reference and examples](API.md) +- [Support](#support) +- [What are promises and why should I use them?](#what-are-promises-and-why-should-i-use-them) +- [Questions and issues](#questions-and-issues) +- [Error handling](#error-handling) +- [Development](#development) + - [Testing](#testing) + - [Benchmarking](#benchmarks) + - [Custom builds](#custom-builds) + - [For library authors](#for-library-authors) +- [What is the sync build?](#what-is-the-sync-build) +- [License](#license) +- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets) +- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) +- [Changelog](changelog.md) +- [Optimization guide](#optimization-guide) + +# Features +bluebird logo + +- [Promises A+](http://promisesaplus.com) +- [Synchronous inspection](API.md#synchronous-inspection) +- [Concurrency coordination](API.md#collections) +- [Promisification on steroids](API.md#promisification) +- [Resource management through a parallel of python `with`/C# `using`](API.md#resource-management) +- [Cancellation and timeouts](API.md#cancellation) +- [Parallel for C# `async` and `await`](API.md#generators) +- Mind blowing utilities such as + - [`.bind()`](API.md#binddynamic-thisarg---promise) + - [`.call()`](API.md#callstring-propertyname--dynamic-arg---promise) + - [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) + - [And](API.md#core) [much](API.md#timers) [more](API.md#utility)! +- [Practical debugging solutions and sane defaults](#error-handling) +- [Sick performance](benchmark/) + +
+ +# Quick start + +## Node.js + + npm install bluebird + +Then: + +```js +var Promise = require("bluebird"); +``` + +## Browsers + +There are many ways to use bluebird in browsers: + +- Direct downloads + - Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js) + - Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js) +- You may use browserify on the main export +- You may use the [bower](http://bower.io) package. + +When using script tags the global variables `Promise` and `P` (alias for `Promise`) become available. + +A [minimal bluebird browser build](#custom-builds) is ≈38.92KB minified*, 11.65KB gzipped and has no external dependencies. + +*Google Closure Compiler using Simple. + +#### Browser support + +Browsers that [implement ECMA-262, edition 3](http://en.wikipedia.org/wiki/Ecmascript#Implementations) and later are supported. + +[![Selenium Test Status](https://saucelabs.com/browser-matrix/petka_antonov.svg)](https://saucelabs.com/u/petka_antonov) + +**Note** that in ECMA-262, edition 3 (IE7, IE8 etc.) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`. + +Also, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome, Firefox and Internet Explorer 10+. + +After quick start, see [API Reference and examples](API.md) + +
+ +# Support + +- Mailing list: [bluebird-js@googlegroups.com](https://groups.google.com/forum/#!forum/bluebird-js) +- IRC: #promises @freenode +- StackOverflow: [bluebird tag](http://stackoverflow.com/questions/tagged/bluebird) +- Bugs and feature requests: [github issue tracker](https://github.com/petkaantonov/bluebird/issues?state=open) + +
+ +# What are promises and why should I use them? + +You should use promises to turn this: + +```js +fs.readFile("file.json", function(err, val) { + if( err ) { + console.error("unable to read file"); + } + else { + try { + val = JSON.parse(val); + console.log(val.success); + } + catch( e ) { + console.error("invalid json in file"); + } + } +}); +``` + +Into this: + +```js +fs.readFileAsync("file.json").then(JSON.parse).then(function(val) { + console.log(val.success); +}) +.catch(SyntaxError, function(e) { + console.error("invalid json in file"); +}) +.catch(function(e) { + console.error("unable to read file") +}); +``` + +*If you are wondering "there is no `readFileAsync` method on `fs` that returns a promise", see [promisification](API.md#promisification)* + +Actually you might notice the latter has a lot in common with code that would do the same using synchronous I/O: + +```js +try { + var val = JSON.parse(fs.readFileSync("file.json")); + console.log(val.success); +} +//Syntax actually not supported in JS but drives the point +catch(SyntaxError e) { + console.error("invalid json in file"); +} +catch(Error e) { + console.error("unable to read file") +} +``` + +And that is the point - being able to have something that is a lot like `return` and `throw` in synchronous code. + +You can also use promises to improve code that was written with callback helpers: + + +```js +//Copyright Plato http://stackoverflow.com/a/19385911/995876 +//CC BY-SA 2.5 +mapSeries(URLs, function (URL, done) { + var options = {}; + needle.get(URL, options, function (error, response, body) { + if (error) { + return done(error) + } + try { + var ret = JSON.parse(body); + return done(null, ret); + } + catch (e) { + done(e); + } + }); +}, function (err, results) { + if (err) { + console.log(err) + } else { + console.log('All Needle requests successful'); + // results is a 1 to 1 mapping in order of URLs > needle.body + processAndSaveAllInDB(results, function (err) { + if (err) { + return done(err) + } + console.log('All Needle requests saved'); + done(null); + }); + } +}); +``` + +Is more pleasing to the eye when done with promises: + +```js +Promise.promisifyAll(needle); +var options = {}; + +var current = Promise.resolve(); +Promise.map(URLs, function(URL) { + current = current.then(function () { + return needle.getAsync(URL, options); + }); + return current; +}).map(function(responseAndBody){ + return JSON.parse(responseAndBody[1]); +}).then(function (results) { + return processAndSaveAllInDB(results); +}).then(function(){ + console.log('All Needle requests saved'); +}).catch(function (e) { + console.log(e); +}); +``` + +Also promises don't just give you correspondences for synchronous features but can also be used as limited event emitters or callback aggregators. + +More reading: + + - [Promise nuggets](https://promise-nuggets.github.io/) + - [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html) + - [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1) + - [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets) + - [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) + +# Questions and issues + +If you find a bug in bluebird or have a feature request, file an issue in the [github issue tracker](https://github.com/petkaantonov/bluebird/issues). Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. + +# Error handling + +This is a problem every promise library needs to handle in some way. Unhandled rejections/exceptions don't really have a good agreed-on asynchronous correspondence. The problem is that it is impossible to predict the future and know if a rejected promise will eventually be handled. + +There are two common pragmatic attempts at solving the problem that promise libraries do. + +The more popular one is to have the user explicitly communicate that they are done and any unhandled rejections should be thrown, like so: + +```js +download().then(...).then(...).done(); +``` + +For handling this problem, in my opinion, this is completely unacceptable and pointless. The user must remember to explicitly call `.done` and that cannot be justified when the problem is forgetting to create an error handler in the first place. + +The second approach, which is what bluebird by default takes, is to call a registered handler if a rejection is unhandled by the start of a second turn. The default handler is to write the stack trace to `stderr` or `console.error` in browsers. This is close to what happens with synchronous code - your code doesn't work as expected and you open console and see a stack trace. Nice. + +Of course this is not perfect, if your code for some reason needs to swoop in and attach error handler to some promise after the promise has been hanging around a while then you will see annoying messages. In that case you can use the `.done()` method to signal that any hanging exceptions should be thrown. + +If you want to override the default handler for these possibly unhandled rejections, you can pass yours like so: + +```js +Promise.onPossiblyUnhandledRejection(function(error){ + throw error; +}); +``` + +If you want to also enable long stack traces, call: + +```js +Promise.longStackTraces(); +``` + +right after the library is loaded. + +In node.js use the environment flag `BLUEBIRD_DEBUG`: + +``` +BLUEBIRD_DEBUG=1 node server.js +``` + +to enable long stack traces in all instances of bluebird. + +Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, even after using every trick to optimize them. + +Long stack traces are enabled by default in the debug build. + +#### Expected and unexpected errors + +A practical problem with Promises/A+ is that it models Javascript `try-catch` too closely for its own good. Therefore by default promises inherit `try-catch` warts such as the inability to specify the error types that the catch block is eligible for. It is an anti-pattern in every other language to use catch-all handlers because they swallow exceptions that you might not know about. + +Now, Javascript does have a perfectly fine and working way of creating error type hierarchies. It is still quite awkward to use them with the built-in `try-catch` however: + +```js +try { + //code +} +catch(e) { + if( e instanceof WhatIWantError) { + //handle + } + else { + throw e; + } +} +``` + +Without such checking, unexpected errors would be silently swallowed. However, with promises, bluebird brings the future (hopefully) here now and extends the `.catch` to [accept potential error type eligibility](API.md#catchfunction-errorclass-function-handler---promise). + +For instance here it is expected that some evil or incompetent entity will try to crash our server from `SyntaxError` by providing syntactically invalid JSON: + +```js +getJSONFromSomewhere().then(function(jsonString) { + return JSON.parse(jsonString); +}).then(function(object) { + console.log("it was valid json: ", object); +}).catch(SyntaxError, function(e){ + console.log("don't be evil"); +}); +``` + +Here any kind of unexpected error will automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`. + +Ok, so, that's pretty neat. But actually not many libraries define error types and it is in fact a complete ghetto out there with ad hoc strings being attached as some arbitrary property name like `.name`, `.type`, `.code`, not having any property at all or even throwing strings as errors and so on. So how can we still listen for expected errors? + +Bluebird defines a special error type `OperationalError` (you can get a reference from `Promise.OperationalError`). This type of error is given as rejection reason by promisified methods when +their underlying library gives an untyped, but expected error. Primitives such as strings, and error objects that are directly created like `new Error("database didn't respond")` are considered untyped. + +Example of such library is the node core library `fs`. So if we promisify it, we can catch just the errors we want pretty easily and have programmer errors be redirected to unhandled rejection handler so that we notice them: + +```js +//Read more about promisification in the API Reference: +//API.md +var fs = Promise.promisifyAll(require("fs")); + +fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) { + console.log("Successful json") +}).catch(SyntaxError, function (e) { + console.error("file contains invalid json"); +}).catch(Promise.OperationalError, function (e) { + console.error("unable to read file, because: ", e.message); +}); +``` + +The last `catch` handler is only invoked when the `fs` module explicitly used the `err` argument convention of async callbacks to inform of an expected error. The `OperationalError` instance will contain the original error in its `.cause` property but it does have a direct copy of the `.message` and `.stack` too. In this code any unexpected error - be it in our code or the `fs` module - would not be caught by these handlers and therefore not swallowed. + +Since a `catch` handler typed to `Promise.OperationalError` is expected to be used very often, it has a neat shorthand: + +```js +.error(function (e) { + console.error("unable to read file, because: ", e.message); +}); +``` + +See [API documentation for `.error()`](API.md#error-rejectedhandler----promise) + +Finally, Bluebird also supports predicate-based filters. If you pass a +predicate function instead of an error type, the predicate will receive +the error as an argument. The return result will be used to determine whether +the error handler should be called. + +Predicates should allow for very fine grained control over caught errors: +pattern matching, error typesets with set operations and many other techniques +can be implemented on top of them. + +Example of using a predicate-based filter: + +```js +var Promise = require("bluebird"); +var request = Promise.promisify(require("request")); + +function clientError(e) { + return e.code >= 400 && e.code < 500; +} + +request("http://www.google.com").then(function(contents){ + console.log(contents); +}).catch(clientError, function(e){ + //A client error like 400 Bad Request happened +}); +``` + +**Danger:** The JavaScript language allows throwing primitive values like strings. Throwing primitives can lead to worse or no stack traces. Primitives [are not exceptions](http://www.devthought.com/2011/12/22/a-string-is-not-an-error/). You should consider always throwing Error objects when handling exceptions. + +
+ +#### How do long stack traces differ from e.g. Q? + +Bluebird attempts to have more elaborate traces. Consider: + +```js +Error.stackTraceLimit = 25; +Q.longStackSupport = true; +Q().then(function outer() { + return Q().then(function inner() { + return Q().then(function evenMoreInner() { + a.b.c.d(); + }).catch(function catcher(e){ + console.error(e.stack); + }); + }) +}); +``` + +You will see + + ReferenceError: a is not defined + at evenMoreInner (:7:13) + From previous event: + at inner (:6:20) + +Compare to: + +```js +Error.stackTraceLimit = 25; +Promise.longStackTraces(); +Promise.resolve().then(function outer() { + return Promise.resolve().then(function inner() { + return Promise.resolve().then(function evenMoreInner() { + a.b.c.d() + }).catch(function catcher(e){ + console.error(e.stack); + }); + }); +}); +``` + + ReferenceError: a is not defined + at evenMoreInner (:7:13) + From previous event: + at inner (:6:36) + From previous event: + at outer (:5:32) + From previous event: + at :4:21 + at Object.InjectedScript._evaluateOn (:572:39) + at Object.InjectedScript._evaluateAndWrap (:531:52) + at Object.InjectedScript.evaluate (:450:21) + + +A better and more practical example of the differences can be seen in gorgikosev's [debuggability competition](https://github.com/spion/async-compare#debuggability). + +
+ +# Development + +For development tasks such as running benchmarks or testing, you need to clone the repository and install dev-dependencies. + +Install [node](http://nodejs.org/) and [npm](https://npmjs.org/) + + git clone git@github.com:petkaantonov/bluebird.git + cd bluebird + npm install + +## Testing + +To run all tests, run + + node tools/test + +If you need to run generator tests run the `tool/test.js` script with `--harmony` argument and node 0.11+: + + node-dev --harmony tools/test + +You may specify an individual test file to run with the `--run` script flag: + + node tools/test --run=cancel.js + + +This enables output from the test and may give a better idea where the test is failing. The paramter to `--run` can be any file name located in `test/mocha` folder. + +#### Testing in browsers + +To run the test in a browser instead of node, pass the flag `--browser` to the test tool + + node tools/test --run=cancel.js --browser + +This will automatically create a server (default port 9999) and open it in your default browser once the tests have been compiled. + +Keep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active. + +#### Supported options by the test tool + +The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-browser`. + + - `--run=String`. Which tests to run (or compile when testing in browser). Default `"all"`. Can also be a glob string (relative to ./test/mocha folder) + - `--cover=String`. Create code coverage using the String as istanbul reporter. Coverage is created in the ./coverage folder. No coverage is created by default, default reporter is `"html"` (use `--cover` to use default reporter). + - `--browser` - Whether to compile tests for browsers. Default `false`. + - `--port=Number` - Whe port where local server is hosted when testing in browser. Default `9999` + - `--execute-browser-tests` - Whether to execute the compiled tests for browser when using `--browser`. Default `true`. + - `--open-browser` - Whether to open the default browser when executing browser tests. Default `true`. + - `--fake-timers` - Whether to use fake timers (`setTimeout` etc) when running tests in node. Default `true`. + - `--js-hint` - Whether to run JSHint on source files. Default `true`. + - `--saucelabs` Wheter to create a tunnel to sauce labs and run tests in their VMs instead of your browser when compiling tests for browser.Default `false`. + +## Benchmarks + +To run a benchmark, run the given command for a benchmark while on the project root. Requires bash (on windows the mingw32 that comes with git works fine too). + +Node 0.11.2+ is required to run the generator examples. + +### 1\. DoxBee sequential + +Currently the most relevant benchmark is @gorkikosev's benchmark in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where n amount of users are making a request in parallel to execute some mixed async/sync action. The benchmark has been modified to include a warm-up phase to minimize any JITing during timed sections. + +Command: `bench doxbee` + +### 2\. Made-up parallel + +This made-up scenario runs 15 shimmed queries in parallel. + +Command: `bench parallel` + +## Custom builds + +Custom builds for browsers are supported through a command-line utility. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
The following features can be disabled
Feature(s)Command line identifier
.any and Promise.anyany
.race and Promise.racerace
.call and .getcall_get
.filter and Promise.filterfilter
.map and Promise.mapmap
.reduce and Promise.reducereduce
.props and Promise.propsprops
.settle and Promise.settlesettle
.some and Promise.somesome
.nodeifynodeify
Promise.coroutine and Promise.spawngenerators
Progressionprogress
Promisificationpromisify
Cancellationcancel
Timerstimers
Resource managementusing
+ + +Make sure you have cloned the repo somewhere and did `npm install` successfully. + +After that you can run: + + node tools/build --features="core" + + +The above builds the most minimal build you can get. You can add more features separated by spaces from the above list: + + node tools/build --features="core filter map reduce" + +The custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features. + +Note that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build +a full version afterwards (after having taken a copy of the bluebird.js somewhere): + + node tools/build --debug --main --zalgo --browser --minify + +#### Supported options by the build tool + +The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`. + + - `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`. + - `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`. + - `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`. + - `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`. + - `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`. + - `--features=String` - See [custom builds](#custom-builds) + +
+ +## For library authors + +Building a library that depends on bluebird? You should know about a few features. + +If your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require("bluebird")`. Instead you should create a file +that creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains: + +```js + //NOTE the function call right after +module.exports = require("bluebird/js/main/promise")(); +``` + +Your library can then use `var Promise = require("bluebird-extended");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic. + +You should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---promise) which makes it easy to provide a dual callback/promise API. + +
+ +## What is the sync build? + +You may now use sync build by: + + var Promise = require("bluebird/zalgo"); + +The sync build is provided to see how forced asynchronity affects benchmarks. It should not be used in real code due to the implied hazards. + +The normal async build gives Promises/A+ guarantees about asynchronous resolution of promises. Some people think this affects performance or just plain love their code having a possibility +of stack overflow errors and non-deterministic behavior. + +The sync build skips the async call trampoline completely, e.g code like: + + async.invoke( this.fn, this, val ); + +Appears as this in the sync build: + + this.fn(val); + +This should pressure the CPU slightly less and thus the sync build should perform better. Indeed it does, but only marginally. The biggest performance boosts are from writing efficient Javascript, not from compromising determinism. + +Note that while some benchmarks are waiting for the next event tick, the CPU is actually not in use during that time. So the resulting benchmark result is not completely accurate because on node.js you only care about how much the CPU is taxed. Any time spent on CPU is time the whole process (or server) is paralyzed. And it is not graceful like it would be with threads. + + +```js +var cache = new Map(); //ES6 Map or DataStructures/Map or whatever... +function getResult(url) { + var resolver = Promise.pending(); + if (cache.has(url)) { + resolver.resolve(cache.get(url)); + } + else { + http.get(url, function(err, content) { + if (err) resolver.reject(err); + else { + cache.set(url, content); + resolver.resolve(content); + } + }); + } + return resolver.promise; +} + + + +//The result of console.log is truly random without async guarantees +function guessWhatItPrints( url ) { + var i = 3; + getResult(url).then(function(){ + i = 4; + }); + console.log(i); +} +``` + +# Optimization guide + +Articles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome. + +A single cohesive guide compiled from the articles will probably be done eventually. + +# License + +The MIT License (MIT) + +Copyright (c) 2014 Petka Antonov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..46729e1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md @@ -0,0 +1,1643 @@ +## 2.9.26 (2015-05-25) + +Bugfixes: + + - Fix crash in NW [#624](.) + - Fix [`.return()`](.) not supporting `undefined` as return value [#627](.) + +## 2.9.25 (2015-04-28) + +Bugfixes: + + - Fix crash in node 0.8 + +## 2.9.24 (2015-04-02) + +Bugfixes: + + - Fix not being able to load multiple bluebird copies introduced in 2.9.22 ([#559](.), [#561](.), [#560](.)). + +## 2.9.23 (2015-04-02) + +Bugfixes: + + - Fix node.js domain propagation ([#521](.)). + +## 2.9.22 (2015-04-02) + + - Fix `.promisify` crashing in phantom JS ([#556](.)) + +## 2.9.21 (2015-03-30) + + - Fix error object's `'stack'`' overwriting causing an error when its defined to be a setter that throws an error ([#552](.)). + +## 2.9.20 (2015-03-29) + +Bugfixes: + + - Fix regression where there is a long delay between calling `.cancel()` and promise actually getting cancelled in Chrome when long stack traces are enabled + +## 2.9.19 (2015-03-29) + +Bugfixes: + + - Fix crashing in Chrome when long stack traces are disabled + +## 2.9.18 (2015-03-29) + +Bugfixes: + + - Fix settlePromises using trampoline + +## 2.9.17 (2015-03-29) + + +Bugfixes: + + - Fix Chrome DevTools async stack traceability ([#542](.)). + +## 2.9.16 (2015-03-28) + +Features: + + - Use setImmediate if available + +## 2.9.15 (2015-03-26) + +Features: + + - Added `.asCallback` alias for `.nodeify`. + +Bugfixes: + + - Don't always use nextTick, but try to pick up setImmediate or setTimeout in NW. Fixes [#534](.), [#525](.) + - Make progress a core feature. Fixes [#535](.) Note that progress has been removed in 3.x - this is only a fix necessary for 2.x custom builds. + +## 2.9.14 (2015-03-12) + +Bugfixes: + + - Always use process.nextTick. Fixes [#525](.) + +## 2.9.13 (2015-02-27) + +Bugfixes: + + - Fix .each, .filter, .reduce and .map callbacks being called synchornously if the input is immediate. ([#513](.)) + +## 2.9.12 (2015-02-19) + +Bugfixes: + + - Fix memory leak introduced in 2.9.0 ([#502](.)) + +## 2.9.11 (2015-02-19) + +Bugfixes: + + - Fix [#503](.) + +## 2.9.10 (2015-02-18) + +Bugfixes: + + - Fix [#501](.) + +## 2.9.9 (2015-02-12) + +Bugfixes: + + - Fix `TypeError: Cannot assign to read only property 'length'` when jsdom has declared a read-only length for all objects to inherit. + +## 2.9.8 (2015-02-10) + +Bugfixes: + + - Fix regression introduced in 2.9.7 where promisify didn't properly dynamically look up methods on `this` + +## 2.9.7 (2015-02-08) + +Bugfixes: + + - Fix `promisify` not retaining custom properties of the function. This enables promisifying the `"request"` module's export function and its methods at the same time. + - Fix `promisifyAll` methods being dependent on `this` when they are not originally dependent on `this`. This enables e.g. passing promisified `fs` functions directly as callbacks without having to bind them to `fs`. + - Fix `process.nextTick` being used over `setImmediate` in node. + +## 2.9.6 (2015-02-02) + +Bugfixes: + + - Node environment detection can no longer be fooled + +## 2.9.5 (2015-02-02) + +Misc: + + - Warn when [`.then()`](.) is passed non-functions + +## 2.9.4 (2015-01-30) + +Bugfixes: + + - Fix [.timeout()](.) not calling `clearTimeout` with the proper handle in node causing the process to wait for unneeded timeout. This was a regression introduced in 2.9.1. + +## 2.9.3 (2015-01-27) + +Bugfixes: + + - Fix node-webkit compatibility issue ([#467](https://github.com/petkaantonov/bluebird/pull/467)) + - Fix long stack trace support in recent firefox versions + +## 2.9.2 (2015-01-26) + +Bugfixes: + + - Fix critical bug regarding to using promisifyAll in browser that was introduced in 2.9.0 ([#466](https://github.com/petkaantonov/bluebird/issues/466)). + +Misc: + + - Add `"browser"` entry point to package.json + +## 2.9.1 (2015-01-24) + +Features: + + - If a bound promise is returned by the callback to [`Promise.method`](#promisemethodfunction-fn---function) and [`Promise.try`](#promisetryfunction-fn--arraydynamicdynamic-arguments--dynamic-ctx----promise), the returned promise will be bound to the same value + +## 2.9.0 (2015-01-24) + +Features: + + - Add [`Promise.fromNode`](API.md#promisefromnodefunction-resolver---promise) + - Add new paramter `value` for [`Promise.bind`](API.md#promisebinddynamic-thisarg--dynamic-value---promise) + +Bugfixes: + + - Fix several issues with [`cancellation`](API.md#cancellation) and [`.bind()`](API.md#binddynamic-thisarg---promise) interoperation when `thisArg` is a promise or thenable + - Fix promises created in [`disposers`](API#disposerfunction-disposer---disposer) not having proper long stack trace context + - Fix [`Promise.join`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) sometimes passing the passed in callback function as the last argument to itself. + +Misc: + + - Reduce minified full browser build file size by not including unused code generation functionality. + - Major internal refactoring related to testing code and source code file layout + +## 2.8.2 (2015-01-20) + +Features: + + - [Global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) are now fired both as DOM3 events and as legacy events in browsers + +## 2.8.1 (2015-01-20) + +Bugfixes: + + - Fix long stack trace stiching consistency when rejected from thenables + +## 2.8.0 (2015-01-19) + +Features: + + - Major debuggability improvements: + - Long stack traces have been re-designed. They are now much more readable, + succint, relevant and consistent across bluebird features. + - Long stack traces are supported now in IE10+ + +## 2.7.1 (2015-01-15) + +Bugfixes: + + - Fix [#447](https://github.com/petkaantonov/bluebird/issues/447) + +## 2.7.0 (2015-01-15) + +Features: + + - Added more context to stack traces originating from coroutines ([#421](https://github.com/petkaantonov/bluebird/issues/421)) + - Implemented [global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) ([#428](https://github.com/petkaantonov/bluebird/issues/428), [#357](https://github.com/petkaantonov/bluebird/issues/357)) + - [Custom promisifiers](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-promisifier) are now passed the default promisifier which can be used to add enhancements on top of normal node promisification + - [Promisification filters](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-filter) are now passed `passesDefaultFilter` boolean + +Bugfixes: + + - Fix `.noConflict()` call signature ([#446]()) + - Fix `Promise.method`ified functions being called with `undefined` when they were called with no arguments + +## 2.6.4 (2015-01-12) + +Bugfixes: + + - `OperationalErrors` thrown by promisified functions retain custom properties, such as `.code` and `.path`. + +## 2.6.3 (2015-01-12) + +Bugfixes: + + - Fix [#429](https://github.com/petkaantonov/bluebird/issues/429) + - Fix [#432](https://github.com/petkaantonov/bluebird/issues/432) + - Fix [#433](https://github.com/petkaantonov/bluebird/issues/433) + +## 2.6.2 (2015-01-07) + +Bugfixes: + + - Fix [#426](https://github.com/petkaantonov/bluebird/issues/426) + +## 2.6.1 (2015-01-07) + +Bugfixes: + + - Fixed built browser files not being included in the git tag release for bower + +## 2.6.0 (2015-01-06) + +Features: + + - Significantly improve parallel promise performance and memory usage (+50% faster, -50% less memory) + + +## 2.5.3 (2014-12-30) + +## 2.5.2 (2014-12-29) + +Bugfixes: + + - Fix bug where already resolved promise gets attached more handlers while calling its handlers resulting in some handlers not being called + - Fix bug where then handlers are not called in the same order as they would run if Promises/A+ 2.3.2 was implemented as adoption + - Fix bug where using `Object.create(null)` as a rejection reason would crash bluebird + +## 2.5.1 (2014-12-29) + +Bugfixes: + + - Fix `.finally` throwing null error when it is derived from a promise that is resolved with a promise that is resolved with a promise + +## 2.5.0 (2014-12-28) + +Features: + + - [`.get`](#API.md#https://github.com/petkaantonov/bluebird/blob/master/API.md#getstring-propertyname---promise) now supports negative indexing. + +Bugfixes: + + - Fix bug with `Promise.method` wrapped function returning a promise that never resolves if the function returns a promise that is resolved with another promise + - Fix bug with `Promise.delay` never resolving if the value is a promise that is resolved with another promise + +## 2.4.3 (2014-12-28) + +Bugfixes: + + - Fix memory leak as described in [this Promises/A+ spec issue](https://github.com/promises-aplus/promises-spec/issues/179). + +## 2.4.2 (2014-12-21) + +Bugfixes: + + - Fix bug where spread rejected handler is ignored in case of rejection + - Fix synchronous scheduler passed to `setScheduler` causing infinite loop + +## 2.4.1 (2014-12-20) + +Features: + + - Error messages now have links to wiki pages for additional information + - Promises now clean up all references (to handlers, child promises etc) as soon as possible. + +## 2.4.0 (2014-12-18) + +Features: + + - Better filtering of bluebird internal calls in long stack traces, especially when using minified file in browsers + - Small performance improvements for all collection methods + - Promises now delete references to handlers attached to them as soon as possible + - Additional stack traces are now output on stderr/`console.warn` for errors that are thrown in the process/window from rejected `.done()` promises. See [#411](https://github.com/petkaantonov/bluebird/issues/411) + +## 2.3.11 (2014-10-31) + +Bugfixes: + + - Fix [#371](https://github.com/petkaantonov/bluebird/issues/371), [#373](https://github.com/petkaantonov/bluebird/issues/373) + + +## 2.3.10 (2014-10-28) + +Features: + + - `Promise.method` no longer wraps primitive errors + - `Promise.try` no longer wraps primitive errors + +## 2.3.7 (2014-10-25) + +Bugfixes: + + - Fix [#359](https://github.com/petkaantonov/bluebird/issues/359), [#362](https://github.com/petkaantonov/bluebird/issues/362) and [#364](https://github.com/petkaantonov/bluebird/issues/364) + +## 2.3.6 (2014-10-15) + +Features: + + - Implement [`.reflect()`](API.md#reflect---promisepromiseinspection) + +## 2.3.5 (2014-10-06) + +Bugfixes: + + - Fix issue when promisifying methods whose names contain the string 'args' + +## 2.3.4 (2014-09-27) + + - `P` alias was not declared inside WebWorkers + +## 2.3.3 (2014-09-27) + +Bugfixes: + + - Fix [#318](https://github.com/petkaantonov/bluebird/issues/318), [#314](https://github.com/petkaantonov/bluebird/issues/#314) + +## 2.3.2 (2014-08-25) + +Bugfixes: + + - `P` alias for `Promise` now exists in global scope when using browser builds without a module loader, fixing an issue with firefox extensions + +## 2.3.1 (2014-08-23) + +Features: + + - `.using` can now be used with disposers created from different bluebird copy + +## 2.3.0 (2014-08-13) + +Features: + + - [`.bind()`](API.md#binddynamic-thisarg---promise) and [`Promise.bind()`](API.md#promisebinddynamic-thisarg---promise) now await for the resolution of the `thisArg` if it's a promise or a thenable + +Bugfixes: + + - Fix [#276](https://github.com/petkaantonov/bluebird/issues/276) + +## 2.2.2 (2014-07-14) + + - Fix [#259](https://github.com/petkaantonov/bluebird/issues/259) + +## 2.2.1 (2014-07-07) + + - Fix multiline error messages only showing the first line + +## 2.2.0 (2014-07-07) + +Bugfixes: + + - `.any` and `.some` now consistently reject with RangeError when input array contains too few promises + - Fix iteration bug with `.reduce` when input array contains already fulfilled promises + +## 2.1.3 (2014-06-18) + +Bugfixes: + + - Fix [#235](https://github.com/petkaantonov/bluebird/issues/235) + +## 2.1.2 (2014-06-15) + +Bugfixes: + + - Fix [#232](https://github.com/petkaantonov/bluebird/issues/232) + +## 2.1.1 (2014-06-11) + +## 2.1.0 (2014-06-11) + +Features: + + - Add [`promisifier`](API.md#option-promisifier) option to `Promise.promisifyAll()` + - Improve performance of `.props()` and collection methods when used with immediate values + + +Bugfixes: + + - Fix a bug where .reduce calls the callback for an already visited item + - Fix a bug where stack trace limit is calculated to be too small, which resulted in too short stack traces + +Add undocumented experimental `yieldHandler` option to `Promise.coroutine` + +## 2.0.7 (2014-06-08) +## 2.0.6 (2014-06-07) +## 2.0.5 (2014-06-05) +## 2.0.4 (2014-06-05) +## 2.0.3 (2014-06-05) +## 2.0.2 (2014-06-04) +## 2.0.1 (2014-06-04) + +## 2.0.0 (2014-06-04) + +#What's new in 2.0 + +- [Resource management](API.md#resource-management) - never leak resources again +- [Promisification](API.md#promisification) on steroids - entire modules can now be promisified with one line of code +- [`.map()`](API.md#mapfunction-mapper--object-options---promise), [`.each()`](API.md#eachfunction-iterator---promise), [`.filter()`](API.md#filterfunction-filterer--object-options---promise), [`.reduce()`](API.md#reducefunction-reducer--dynamic-initialvalue---promise) reimagined from simple sugar to powerful concurrency coordination tools +- [API Documentation](API.md) has been reorganized and more elaborate examples added +- Deprecated [progression](#progression-migration) and [deferreds](#deferred-migration) +- Improved performance and readability + +Features: + +- Added [`using()`](API.md#promiseusingpromisedisposer-promise-promisedisposer-promise--function-handler---promise) and [`disposer()`](API.md#disposerfunction-disposer---disposer) +- [`.map()`](API.md#mapfunction-mapper--object-options---promise) now calls the handler as soon as items in the input array become fulfilled +- Added a concurrency option to [`.map()`](API.md#mapfunction-mapper--object-options---promise) +- [`.filter()`](API.md#filterfunction-filterer--object-options---promise) now calls the handler as soon as items in the input array become fulfilled +- Added a concurrency option to [`.filter()`](API.md#filterfunction-filterer--object-options---promise) +- [`.reduce()`](API.md#reducefunction-reducer--dynamic-initialvalue---promise) now calls the handler as soon as items in the input array become fulfilled, but in-order +- Added [`.each()`](API.md#eachfunction-iterator---promise) +- [`Promise.resolve()`](API.md#promiseresolvedynamic-value---promise) behaves like `Promise.cast`. `Promise.cast` deprecated. +- [Synchronous inspection](API.md#synchronous-inspection): Removed `.inspect()`, added [`.value()`](API.md#value---dynamic) and [`.reason()`](API.md#reason---dynamic) +- [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) now takes a function as the last argument +- Added [`Promise.setScheduler()`](API.md#promisesetschedulerfunction-scheduler---void) +- [`.cancel()`](API.md#cancelerror-reason---promise) supports a custom cancellation reason +- [`.timeout()`](API.md#timeoutint-ms--string-message---promise) now cancels the promise instead of rejecting it +- [`.nodeify()`](API.md#nodeifyfunction-callback--object-options---promise) now supports passing multiple success results when mapping promises to nodebacks +- Added `suffix` and `filter` options to [`Promise.promisifyAll()`](API.md#promisepromisifyallobject-target--object-options---object) + +Breaking changes: + +- Sparse array holes are not skipped by collection methods but treated as existing elements with `undefined` value +- `.map()` and `.filter()` do not call the given mapper or filterer function in any specific order +- Removed the `.inspect()` method +- Yielding an array from a coroutine is not supported by default. You can use [`coroutine.addYieldHandler()`](API.md#promisecoroutineaddyieldhandlerfunction-handler---void) to configure the old behavior (or any behavior you want). +- [`.any()`](API.md#any---promise) and [`.some()`](API.md#someint-count---promise) no longer use an array as the rejection reason. [`AggregateError`](API.md#aggregateerror) is used instead. + + +## 1.2.4 (2014-04-27) + +Bugfixes: + + - Fix promisifyAll causing a syntax error when a method name is not a valid identifier + - Fix syntax error when es5.js is used in strict mode + +## 1.2.3 (2014-04-17) + +Bugfixes: + + - Fix [#179](https://github.com/petkaantonov/bluebird/issues/179) + +## 1.2.2 (2014-04-09) + +Bugfixes: + + - Promisified methods from promisifyAll no longer call the original method when it is overriden + - Nodeify doesn't pass second argument to the callback if the promise is fulfilled with `undefined` + +## 1.2.1 (2014-03-31) + +Bugfixes: + + - Fix [#168](https://github.com/petkaantonov/bluebird/issues/168) + +## 1.2.0 (2014-03-29) + +Features: + + - New method: [`.value()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#value---dynamic) + - New method: [`.reason()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#reason---dynamic) + - New method: [`Promise.onUnhandledRejectionHandled()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promiseonunhandledrejectionhandledfunction-handler---undefined) + - `Promise.map()`, `.map()`, `Promise.filter()` and `.filter()` start calling their callbacks as soon as possible while retaining a correct order. See [`8085922f`](https://github.com/petkaantonov/bluebird/commit/8085922fb95a9987fda0cf2337598ab4a98dc315). + +Bugfixes: + + - Fix [#165](https://github.com/petkaantonov/bluebird/issues/165) + - Fix [#166](https://github.com/petkaantonov/bluebird/issues/166) + +## 1.1.1 (2014-03-18) + +Bugfixes: + + - [#138](https://github.com/petkaantonov/bluebird/issues/138) + - [#144](https://github.com/petkaantonov/bluebird/issues/144) + - [#148](https://github.com/petkaantonov/bluebird/issues/148) + - [#151](https://github.com/petkaantonov/bluebird/issues/151) + +## 1.1.0 (2014-03-08) + +Features: + + - Implement [`Promise.prototype.tap()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#tapfunction-handler---promise) + - Implement [`Promise.coroutine.addYieldHandler()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisecoroutineaddyieldhandlerfunction-handler---void) + - Deprecate `Promise.prototype.spawn` + +Bugfixes: + + - Fix already rejected promises being reported as unhandled when handled through collection methods + - Fix browserisfy crashing from checking `process.version.indexOf` + +## 1.0.8 (2014-03-03) + +Bugfixes: + + - Fix active domain being lost across asynchronous boundaries in Node.JS 10.xx + +## 1.0.7 (2014-02-25) + +Bugfixes: + + - Fix handled errors being reported + +## 1.0.6 (2014-02-17) + +Bugfixes: + + - Fix bug with unhandled rejections not being reported + when using `Promise.try` or `Promise.method` without + attaching further handlers + +## 1.0.5 (2014-02-15) + +Features: + + - Node.js performance: promisified functions try to check amount of passed arguments in most optimal order + - Node.js promisified functions will have same `.length` as the original function minus one (for the callback parameter) + +## 1.0.4 (2014-02-09) + +Features: + + - Possibly unhandled rejection handler will always get a stack trace, even if the rejection or thrown error was not an error + - Unhandled rejections are tracked per promise, not per error. So if you create multiple branches from a single ancestor and that ancestor gets rejected, each branch with no error handler with the end will cause a possibly unhandled rejection handler invocation + +Bugfixes: + + - Fix unhandled non-writable objects or primitives not reported by possibly unhandled rejection handler + +## 1.0.3 (2014-02-05) + +Bugfixes: + + - [#93](https://github.com/petkaantonov/bluebird/issues/88) + +## 1.0.2 (2014-02-04) + +Features: + + - Significantly improve performance of foreign bluebird thenables + +Bugfixes: + + - [#88](https://github.com/petkaantonov/bluebird/issues/88) + +## 1.0.1 (2014-01-28) + +Features: + + - Error objects that have property `.isAsync = true` will now be caught by `.error()` + +Bugfixes: + + - Fix TypeError and RangeError shims not working without `new` operator + +## 1.0.0 (2014-01-12) + +Features: + + - `.filter`, `.map`, and `.reduce` no longer skip sparse array holes. This is a backwards incompatible change. + - Like `.map` and `.filter`, `.reduce` now allows returning promises and thenables from the iteration function. + +Bugfixes: + + - [#58](https://github.com/petkaantonov/bluebird/issues/58) + - [#61](https://github.com/petkaantonov/bluebird/issues/61) + - [#64](https://github.com/petkaantonov/bluebird/issues/64) + - [#60](https://github.com/petkaantonov/bluebird/issues/60) + +## 0.11.6-1 (2013-12-29) + +## 0.11.6-0 (2013-12-29) + +Features: + + - You may now return promises and thenables from the filterer function used in `Promise.filter` and `Promise.prototype.filter`. + + - `.error()` now catches additional sources of rejections: + + - Rejections originating from `Promise.reject` + + - Rejections originating from thenables using + the `reject` callback + + - Rejections originating from promisified callbacks + which use the `errback` argument + + - Rejections originating from `new Promise` constructor + where the `reject` callback is called explicitly + + - Rejections originating from `PromiseResolver` where + `.reject()` method is called explicitly + +Bugfixes: + + - Fix `captureStackTrace` being called when it was `null` + - Fix `Promise.map` not unwrapping thenables + +## 0.11.5-1 (2013-12-15) + +## 0.11.5-0 (2013-12-03) + +Features: + + - Improve performance of collection methods + - Improve performance of promise chains + +## 0.11.4-1 (2013-12-02) + +## 0.11.4-0 (2013-12-02) + +Bugfixes: + + - Fix `Promise.some` behavior with arguments like negative integers, 0... + - Fix stack traces of synchronously throwing promisified functions' + +## 0.11.3-0 (2013-12-02) + +Features: + + - Improve performance of generators + +Bugfixes: + + - Fix critical bug with collection methods. + +## 0.11.2-0 (2013-12-02) + +Features: + + - Improve performance of all collection methods + +## 0.11.1-0 (2013-12-02) + +Features: + +- Improve overall performance. +- Improve performance of promisified functions. +- Improve performance of catch filters. +- Improve performance of .finally. + +Bugfixes: + +- Fix `.finally()` rejecting if passed non-function. It will now ignore non-functions like `.then`. +- Fix `.finally()` not converting thenables returned from the handler to promises. +- `.spread()` now rejects if the ultimate value given to it is not spreadable. + +## 0.11.0-0 (2013-12-02) + +Features: + + - Improve overall performance when not using `.bind()` or cancellation. + - Promises are now not cancellable by default. This is backwards incompatible change - see [`.cancellable()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#cancellable---promise) + - [`Promise.delay`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisedelaydynamic-value-int-ms---promise) + - [`.delay()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#delayint-ms---promise) + - [`.timeout()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#timeoutint-ms--string-message---promise) + +## 0.10.14-0 (2013-12-01) + +Bugfixes: + + - Fix race condition when mixing 3rd party asynchrony. + +## 0.10.13-1 (2013-11-30) + +## 0.10.13-0 (2013-11-30) + +Bugfixes: + + - Fix another bug with progression. + +## 0.10.12-0 (2013-11-30) + +Bugfixes: + + - Fix bug with progression. + +## 0.10.11-4 (2013-11-29) + +## 0.10.11-2 (2013-11-29) + +Bugfixes: + + - Fix `.race()` not propagating bound values. + +## 0.10.11-1 (2013-11-29) + +Features: + + - Improve performance of `Promise.race` + +## 0.10.11-0 (2013-11-29) + +Bugfixes: + + - Fixed `Promise.promisifyAll` invoking property accessors. Only data properties with function values are considered. + +## 0.10.10-0 (2013-11-28) + +Features: + + - Disable long stack traces in browsers by default. Call `Promise.longStackTraces()` to enable them. + +## 0.10.9-1 (2013-11-27) + +Bugfixes: + + - Fail early when `new Promise` is constructed incorrectly + +## 0.10.9-0 (2013-11-27) + +Bugfixes: + + - Promise.props now takes a [thenable-for-collection](https://github.com/petkaantonov/bluebird/blob/f41edac61b7c421608ff439bb5a09b7cffeadcf9/test/mocha/props.js#L197-L217) + - All promise collection methods now reject when a promise-or-thenable-for-collection turns out not to give a collection + +## 0.10.8-0 (2013-11-25) + +Features: + + - All static collection methods take thenable-for-collection + +## 0.10.7-0 (2013-11-25) + +Features: + + - throw TypeError when thenable resolves with itself + - Make .race() and Promise.race() forever pending on empty collections + +## 0.10.6-0 (2013-11-25) + +Bugfixes: + + - Promise.resolve and PromiseResolver.resolve follow thenables too. + +## 0.10.5-0 (2013-11-24) + +Bugfixes: + + - Fix infinite loop when thenable resolves with itself + +## 0.10.4-1 (2013-11-24) + +Bugfixes: + + - Fix a file missing from build. (Critical fix) + +## 0.10.4-0 (2013-11-24) + +Features: + + - Remove dependency of es5-shim and es5-sham when using ES3. + +## 0.10.3-0 (2013-11-24) + +Features: + + - Improve performance of `Promise.method` + +## 0.10.2-1 (2013-11-24) + +Features: + + - Rename PromiseResolver#asCallback to PromiseResolver#callback + +## 0.10.2-0 (2013-11-24) + +Features: + + - Remove memoization of thenables + +## 0.10.1-0 (2013-11-21) + +Features: + + - Add methods `Promise.resolve()`, `Promise.reject()`, `Promise.defer()` and `.resolve()`. + +## 0.10.0-1 (2013-11-17) + +## 0.10.0-0 (2013-11-17) + +Features: + + - Implement `Promise.method()` + - Implement `.return()` + - Implement `.throw()` + +Bugfixes: + + - Fix promises being able to use themselves as resolution or follower value + +## 0.9.11-1 (2013-11-14) + +Features: + + - Implicit `Promise.all()` when yielding an array from generators + +## 0.9.11-0 (2013-11-13) + +Bugfixes: + + - Fix `.spread` not unwrapping thenables + +## 0.9.10-2 (2013-11-13) + +Features: + + - Improve performance of promisified functions on V8 + +Bugfixes: + + - Report unhandled rejections even when long stack traces are disabled + - Fix `.error()` showing up in stack traces + +## 0.9.10-1 (2013-11-05) + +Bugfixes: + + - Catch filter method calls showing in stack traces + +## 0.9.10-0 (2013-11-05) + +Bugfixes: + + - Support primitives in catch filters + +## 0.9.9-0 (2013-11-05) + +Features: + + - Add `Promise.race()` and `.race()` + +## 0.9.8-0 (2013-11-01) + +Bugfixes: + + - Fix bug with `Promise.try` not unwrapping returned promises and thenables + +## 0.9.7-0 (2013-10-29) + +Bugfixes: + + - Fix bug with build files containing duplicated code for promise.js + +## 0.9.6-0 (2013-10-28) + +Features: + + - Improve output of reporting unhandled non-errors + - Implement RejectionError wrapping and `.error()` method + +## 0.9.5-0 (2013-10-27) + +Features: + + - Allow fresh copies of the library to be made + +## 0.9.4-1 (2013-10-27) + +## 0.9.4-0 (2013-10-27) + +Bugfixes: + + - Rollback non-working multiple fresh copies feature + +## 0.9.3-0 (2013-10-27) + +Features: + + - Allow fresh copies of the library to be made + - Add more components to customized builds + +## 0.9.2-1 (2013-10-25) + +## 0.9.2-0 (2013-10-25) + +Features: + + - Allow custom builds + +## 0.9.1-1 (2013-10-22) + +Bugfixes: + + - Fix unhandled rethrown exceptions not reported + +## 0.9.1-0 (2013-10-22) + +Features: + + - Improve performance of `Promise.try` + - Extend `Promise.try` to accept arguments and ctx to make it more usable in promisification of synchronous functions. + +## 0.9.0-0 (2013-10-18) + +Features: + + - Implement `.bind` and `Promise.bind` + +Bugfixes: + + - Fix `.some()` when argument is a pending promise that later resolves to an array + +## 0.8.5-1 (2013-10-17) + +Features: + + - Enable process wide long stack traces through BLUEBIRD_DEBUG environment variable + +## 0.8.5-0 (2013-10-16) + +Features: + + - Improve performance of all collection methods + +Bugfixes: + + - Fix .finally passing the value to handlers + - Remove kew from benchmarks due to bugs in the library breaking the benchmark + - Fix some bluebird library calls potentially appearing in stack traces + +## 0.8.4-1 (2013-10-15) + +Bugfixes: + + - Fix .pending() call showing in long stack traces + +## 0.8.4-0 (2013-10-15) + +Bugfixes: + + - Fix PromiseArray and its sub-classes swallowing possibly unhandled rejections + +## 0.8.3-3 (2013-10-14) + +Bugfixes: + + - Fix AMD-declaration using named module. + +## 0.8.3-2 (2013-10-14) + +Features: + + - The mortals that can handle it may now release Zalgo by `require("bluebird/zalgo");` + +## 0.8.3-1 (2013-10-14) + +Bugfixes: + + - Fix memory leak when using the same promise to attach handlers over and over again + +## 0.8.3-0 (2013-10-13) + +Features: + + - Add `Promise.props()` and `Promise.prototype.props()`. They work like `.all()` for object properties. + +Bugfixes: + + - Fix bug with .some returning garbage when sparse arrays have rejections + +## 0.8.2-2 (2013-10-13) + +Features: + + - Improve performance of `.reduce()` when `initialValue` can be synchronously cast to a value + +## 0.8.2-1 (2013-10-12) + +Bugfixes: + + - Fix .npmignore having irrelevant files + +## 0.8.2-0 (2013-10-12) + +Features: + + - Improve performance of `.some()` + +## 0.8.1-0 (2013-10-11) + +Bugfixes: + + - Remove uses of dynamic evaluation (`new Function`, `eval` etc) when strictly not necessary. Use feature detection to use static evaluation to avoid errors when dynamic evaluation is prohibited. + +## 0.8.0-3 (2013-10-10) + +Features: + + - Add `.asCallback` property to `PromiseResolver`s + +## 0.8.0-2 (2013-10-10) + +## 0.8.0-1 (2013-10-09) + +Features: + + - Improve overall performance. Be able to sustain infinite recursion when using promises. + +## 0.8.0-0 (2013-10-09) + +Bugfixes: + + - Fix stackoverflow error when function calls itself "synchronously" from a promise handler + +## 0.7.12-2 (2013-10-09) + +Bugfixes: + + - Fix safari 6 not using `MutationObserver` as a scheduler + - Fix process exceptions interfering with internal queue flushing + +## 0.7.12-1 (2013-10-09) + +Bugfixes: + + - Don't try to detect if generators are available to allow shims to be used + +## 0.7.12-0 (2013-10-08) + +Features: + + - Promisification now consider all functions on the object and its prototype chain + - Individual promisifcation uses current `this` if no explicit receiver is given + - Give better stack traces when promisified callbacks throw or errback primitives such as strings by wrapping them in an `Error` object. + +Bugfixes: + + - Fix runtime APIs throwing synchronous errors + +## 0.7.11-0 (2013-10-08) + +Features: + + - Deprecate `Promise.promisify(Object target)` in favor of `Promise.promisifyAll(Object target)` to avoid confusion with function objects + - Coroutines now throw error when a non-promise is `yielded` + +## 0.7.10-1 (2013-10-05) + +Features: + + - Make tests pass Internet Explorer 8 + +## 0.7.10-0 (2013-10-05) + +Features: + + - Create browser tests + +## 0.7.9-1 (2013-10-03) + +Bugfixes: + + - Fix promise cast bug when thenable fulfills using itself as the fulfillment value + +## 0.7.9-0 (2013-10-03) + +Features: + + - More performance improvements when long stack traces are enabled + +## 0.7.8-1 (2013-10-02) + +Features: + + - Performance improvements when long stack traces are enabled + +## 0.7.8-0 (2013-10-02) + +Bugfixes: + + - Fix promisified methods not turning synchronous exceptions into rejections + +## 0.7.7-1 (2013-10-02) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.7-0 (2013-10-01) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.6-0 (2013-09-29) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.5-0 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.4-1 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.4-0 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.3-1 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.3-0 (2013-09-27) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.2-0 (2013-09-27) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-5 (2013-09-26) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-4 (2013-09-25) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-3 (2013-09-25) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-2 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-1 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-0 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.0-1 (2013-09-23) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.0-0 (2013-09-23) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-2 (2013-09-20) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-1 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-0 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.4-1 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.4-0 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-4 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-3 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-2 (2013-09-16) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-1 (2013-09-16) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-0 (2013-09-15) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.2-1 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.2-0 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.1-0 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.0-0 (2013-09-13) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-6 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-5 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-4 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-3 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-2 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-1 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.8-1 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.8-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.7-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.6-1 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.6-0 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.5-1 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.5-0 (2013-09-09) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.4-1 (2013-09-08) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.4-0 (2013-09-08) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.3-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.2-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.1-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.0-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.4.0-0 (2013-09-06) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.3.0-1 (2013-09-06) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.3.0 (2013-09-06) diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js new file mode 100644 index 0000000..69a6ffd --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js @@ -0,0 +1,5105 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2014 Petka Antonov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions:

+ * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +/** + * bluebird build version 2.9.26 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers +*/ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + } +}; + +Async.prototype._getDomain = function() {}; + +if (!true) { +if (util.isNode) { + var EventsModule = _dereq_("events"); + + var domainGetter = function() { + var domain = process.domain; + if (domain === null) return undefined; + return domain; + }; + + if (EventsModule.usingDomains) { + Async.prototype._getDomain = domainGetter; + } else { + var descriptor = + Object.getOwnPropertyDescriptor(EventsModule, "usingDomains"); + + if (descriptor) { + if (!descriptor.configurable) { + process.on("domainsActivated", function() { + Async.prototype._getDomain = domainGetter; + }); + } else { + var usingDomains = false; + Object.defineProperty(EventsModule, "usingDomains", { + configurable: false, + enumerable: true, + get: function() { + return usingDomains; + }, + set: function(value) { + if (usingDomains || !value) return; + usingDomains = true; + Async.prototype._getDomain = domainGetter; + util.toFastProperties(process); + process.emit("domainsActivated"); + } + }); + } + } + } +} +} + +function AsyncInvokeLater(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + var domain = this._getDomain(); + if (domain !== undefined) { + var fn = domain.bind(promise._settlePromises); + this._normalQueue.push(fn, promise, undefined); + } else { + this._normalQueue._pushOne(promise); + } + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 0); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + setTimeout(function() { + promise._settlePromises(); + }, 0); + } + }; +} + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = new Async(); +module.exports.firstLineError = firstLineError; + +},{"./queue.js":28,"./schedule.js":31,"./util.js":38,"events":39}],3:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + this._setBoundTo(thisArg); + if (this._isPending()) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, ret._progress, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, ret._progress, ret, context); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 131072; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~131072); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.bind = function (thisArg, value) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + + if (maybePromise instanceof Promise) { + maybePromise._then(function(thisArg) { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + }, ret._reject, ret._progress, ret, null); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + } + return ret; +}; +}; + +},{}],4:[function(_dereq_,module,exports){ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = _dereq_("./promise.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; + +},{"./promise.js":23}],5:[function(_dereq_,module,exports){ +"use strict"; +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} + +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!true) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; + } + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; + } + } + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + if (!true) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } + } + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; + +function namedGetter(obj) { + return obj[this]; +} +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; + +},{"./util.js":38}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var errors = _dereq_("./errors.js"); +var async = _dereq_("./async.js"); +var CancellationError = errors.CancellationError; + +Promise.prototype._cancel = function (reason) { + if (!this.isCancellable()) return this; + var parent; + var promiseToReject = this; + while ((parent = promiseToReject._cancellationParent) !== undefined && + parent.isCancellable()) { + promiseToReject = parent; + } + this._unsetCancellable(); + promiseToReject._target()._rejectCallback(reason, false, true); +}; + +Promise.prototype.cancel = function (reason) { + if (!this.isCancellable()) return this; + if (reason === undefined) reason = new CancellationError(); + async.invokeLater(this._cancel, this, reason); + return this; +}; + +Promise.prototype.cancellable = function () { + if (this._cancellable()) return this; + async.enableTrampoline(); + this._setCancellable(); + this._cancellationParent = undefined; + return this; +}; + +Promise.prototype.uncancellable = function () { + var ret = this.then(); + ret._unsetCancellable(); + return ret; +}; + +Promise.prototype.fork = function (didFulfill, didReject, didProgress) { + var ret = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + + ret._setCancellable(); + ret._cancellationParent = undefined; + return ret; +}; +}; + +},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var warn; + +function CapturedTrace(parent) { + this._parent = parent; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.parent = function() { + return this._parent; +}; + +CapturedTrace.prototype.hasParent = function() { + return this._parent !== undefined; +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = CapturedTrace.parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = stackFramePattern.test(line) || + " (No stack trace)" === line; + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +CapturedTrace.parseStackAndMessage = function(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +}; + +CapturedTrace.formatAndLogError = function(error, title) { + if (typeof console !== "undefined") { + var message; + if (typeof error === "object" || typeof error === "function") { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof warn === "function") { + warn(message); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +}; + +CapturedTrace.unhandledRejection = function (reason) { + CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: "); +}; + +CapturedTrace.isSupported = function () { + return typeof captureStackTrace === "function"; +}; + +CapturedTrace.fireRejectionEvent = +function(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); + } + } + + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + } +}; + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj.toString(); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} +CapturedTrace.setBounds = function(firstLineError, lastLineError) { + if (!CapturedTrace.isSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow) { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); + } + }; + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; + } + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); + } + return true; + }; + } +})(); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + warn = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + warn = function(message) { + process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + warn = function(message) { + console.warn("%c" + message, "color: red"); + }; + } +} + +return CapturedTrace; +}; + +},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util.js"); +var errors = _dereq_("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = _dereq_("./es5.js").keys; +var TypeError = errors.TypeError; + +function CatchFilter(instances, callback, promise) { + this._instances = instances; + this._callback = callback; + this._promise = promise; +} + +function safePredicate(predicate, e) { + var safeObject = {}; + var retfilter = tryCatch(predicate).call(safeObject, e); + + if (retfilter === errorObj) return retfilter; + + var safeKeys = keys(safeObject); + if (safeKeys.length) { + errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); + return errorObj; + } + return retfilter; +} + +CatchFilter.prototype.doFilter = function (e) { + var cb = this._callback; + var promise = this._promise; + var boundTo = promise._boundTo; + for (var i = 0, len = this._instances.length; i < len; ++i) { + var item = this._instances[i]; + var itemIsErrorType = item === Error || + (item != null && item.prototype instanceof Error); + + if (itemIsErrorType && e instanceof item) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } else if (typeof item === "function" && !itemIsErrorType) { + var shouldHandle = safePredicate(item, e); + if (shouldHandle === errorObj) { + e = errorObj.e; + break; + } else if (shouldHandle) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } + } + } + NEXT_FILTER.e = e; + return NEXT_FILTER; +}; + +return CatchFilter; +}; + +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace, isDebugging) { +var contextStack = []; +function Context() { + this._trace = new CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.pop(); + } +}; + +function createContext() { + if (isDebugging()) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} + +Promise.prototype._peekContext = peekContext; +Promise.prototype._pushContext = Context.prototype._pushContext; +Promise.prototype._popContext = Context.prototype._popContext; + +return createContext; +}; + +},{}],10:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var async = _dereq_("./async.js"); +var Warning = _dereq_("./errors.js").Warning; +var util = _dereq_("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +if (debugging) { + async.disableTrampolineIfNecessary(); +} + +Promise.prototype._ensurePossibleRejectionHandled = function () { + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + CapturedTrace.fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._getCarriedStackTrace() || this._settledValue; + this._setUnhandledRejectionIsNotified(); + CapturedTrace.fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 524288; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~524288); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 524288) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 2097152; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~2097152); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 2097152) > 0; +}; + +Promise.prototype._setCarriedStackTrace = function (capturedTrace) { + this._bitField = this._bitField | 1048576; + this._fulfillmentHandler0 = capturedTrace; +}; + +Promise.prototype._isCarryingStackTrace = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._getCarriedStackTrace = function () { + return this._isCarryingStackTrace() + ? this._fulfillmentHandler0 + : undefined; +}; + +Promise.prototype._captureStackTrace = function () { + if (debugging) { + this._trace = new CapturedTrace(this._peekContext()); + } + return this; +}; + +Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { + if (debugging && canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = CapturedTrace.parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +}; + +Promise.prototype._warn = function(message) { + var warning = new Warning(message); + var ctx = this._peekContext(); + if (ctx) { + ctx.attachExtraTrace(warning); + } else { + var parsed = CapturedTrace.parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + CapturedTrace.formatAndLogError(warning, ""); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + unhandledRejectionHandled = typeof fn === "function" ? fn : undefined; +}; + +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && + debugging === false + ) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); + } + debugging = CapturedTrace.isSupported(); + if (debugging) { + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; + +},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util.js"); +var isPrimitive = util.isPrimitive; +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; + +module.exports = function(Promise) { +var returner = function () { + return this; +}; +var thrower = function () { + throw this; +}; +var returnUndefined = function() {}; +var throwUndefined = function() { + throw undefined; +}; + +var wrapper = function (value, action) { + if (action === 1) { + return function () { + throw value; + }; + } else if (action === 2) { + return function () { + return value; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value === undefined) return this.then(returnUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; + +},{"./util.js":38}],12:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, null, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, null, INTERNAL); +}; +}; + +},{}],13:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util.js"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} + +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; + + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + +} +inherits(OperationalError, Error); + +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; + +},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} + +},{}],15:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseMap = Promise.map; + +Promise.prototype.filter = function (fn, options) { + return PromiseMap(this, fn, options, INTERNAL); +}; + +Promise.filter = function (promises, fn, options) { + return PromiseMap(promises, fn, options, INTERNAL); +}; +}; + +},{}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = _dereq_("./util.js"); +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, reasonOrValue, + promise.isFulfilled()); + } + } + + if (promise.isRejected()) { + NEXT_FILTER.e = reasonOrValue; + return NEXT_FILTER; + } else { + return reasonOrValue; + } +} + +function tapHandler(value) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo, value) + : handler(value); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, value, true); + } + } + return value; +} + +Promise.prototype._passThroughHandler = function (handler, isFinally) { + if (typeof handler !== "function") return this.then(); + + var promiseAndHandler = { + promise: this, + handler: handler + }; + + return this._then( + isFinally ? finallyHandler : tapHandler, + isFinally ? finallyHandler : undefined, undefined, + promiseAndHandler, undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThroughHandler(handler, true); +}; + +Promise.prototype.tap = function (handler) { + return this._passThroughHandler(handler, false); +}; +}; + +},{"./util.js":38}],17:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = _dereq_("./errors.js"); +var TypeError = errors.TypeError; +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; +} + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._next(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + if (result === errorObj) { + return this._promise._rejectCallback(result.e, false, true); + } + + var value = result.value; + if (result.done === true) { + this._promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._throw( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise._then( + this._next, + this._throw, + undefined, + this, + null + ); + } +}; + +PromiseSpawn.prototype._throw = function (reason) { + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._next = function (value) { + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + spawn._generator = generator; + spawn._next(undefined); + return spawn.promise(); + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; + +},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!true) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var caller = function(count) { + var values = []; + for (var i = 1; i <= count; ++i) values.push("holder.p" + i); + return new Function("holder", " \n\ + 'use strict'; \n\ + var callback = holder.fn; \n\ + return callback(values); \n\ + ".replace(/values/g, values.join(", "))); + }; + var thenCallbacks = []; + var callers = [undefined]; + for (var i = 1; i <= 5; ++i) { + thenCallbacks.push(thenCallback(i)); + callers.push(caller(i)); + } + + var Holder = function(total, fn) { + this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; + this.fn = fn; + this.total = total; + this.now = 0; + }; + + Holder.prototype.callers = callers; + Holder.prototype.checkFulfillment = function(promise) { + var now = this.now; + now++; + var total = this.total; + if (now >= total) { + var handler = this.callers[total]; + promise._pushContext(); + var ret = tryCatch(handler)(this); + promise._popContext(); + if (ret === errorObj) { + promise._rejectCallback(ret.e, false, true); + } else { + promise._resolveCallback(ret); + } + } else { + this.now = now; + } + }; + + var reject = function (reason) { + this._reject(reason); + }; +} +} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!true) { + if (last < 6 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var holder = new Holder(last, fn); + var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + } else if (maybePromise._isFulfilled()) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else { + ret._reject(maybePromise._reason()); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + return ret; + } + } + } + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; + +},{"./util.js":38}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var PENDING = {}; +var EMPTY_ARRAY = []; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._callback = fn; + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + async.invoke(init, this, undefined); +} +util.inherits(MappingPromiseArray, PromiseArray); +function init() {this._init$(undefined, -2);} + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + if (values[index] === PENDING) { + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return; + } + if (preservedValues !== null) preservedValues[index] = value; + + var callback = this._callback; + var receiver = this._promise._boundTo; + this._promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + this._promise._popContext(); + if (ret === errorObj) return this._reject(ret.e); + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + if (limit >= 1) this._inFlight++; + values[index] = PENDING; + return maybePromise._proxyPromiseArray(this, index); + } else if (maybePromise._isFulfilled()) { + ret = maybePromise._value(); + } else { + return this._reject(maybePromise._reason()); + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + + } +}; + +MappingPromiseArray.prototype._drainQueue = function () { + var queue = this._queue; + var limit = this._limit; + var values = this._values; + while (queue.length > 0 && this._inFlight < limit) { + if (this._isResolved()) return; + var index = queue.pop(); + this._promiseFulfilled(values[index], index); + } +}; + +MappingPromiseArray.prototype._filter = function (booleans, values) { + var len = values.length; + var ret = new Array(len); + var j = 0; + for (var i = 0; i < len; ++i) { + if (booleans[i]) ret[j++] = values[i]; + } + ret.length = j; + this._resolve(ret); +}; + +MappingPromiseArray.prototype.preservedValues = function () { + return this._preservedValues; +}; + +function map(promises, fn, options, _filter) { + var limit = typeof options === "object" && options !== null + ? options.concurrency + : 0; + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter); +} + +Promise.prototype.map = function (fn, options) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + + return map(this, fn, options, null).promise(); +}; + +Promise.map = function (promises, fn, options, _filter) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + return map(promises, fn, options, _filter).promise(); +}; + + +}; + +},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn, args, ctx) { + if (typeof fn !== "function") { + return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = util.isArray(args) + ? tryCatch(fn).apply(ctx, args) + : tryCatch(fn).call(ctx, args); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false, true); + } else { + this._resolveCallback(value, true); + } +}; +}; + +},{"./util.js":38}],21:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundTo; + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var target = promise._target(); + var newReason = target._getCarriedStackTrace(); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundTo, reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = +Promise.prototype.nodeify = function (nodeback, options) { + if (typeof nodeback == "function") { + var adapter = successAdapter; + if (options !== undefined && Object(options).spread) { + adapter = spreadAdapter; + } + this._then( + adapter, + errorAdapter, + undefined, + this, + nodeback + ); + } + return this; +}; +}; + +},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +Promise.prototype.progressed = function (handler) { + return this._then(undefined, undefined, handler, undefined, undefined); +}; + +Promise.prototype._progress = function (progressValue) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._target()._progressUnchecked(progressValue); + +}; + +Promise.prototype._progressHandlerAt = function (index) { + return index === 0 + ? this._progressHandler0 + : this[(index << 2) + index - 5 + 2]; +}; + +Promise.prototype._doProgressWith = function (progression) { + var progressValue = progression.value; + var handler = progression.handler; + var promise = progression.promise; + var receiver = progression.receiver; + + var ret = tryCatch(handler).call(receiver, progressValue); + if (ret === errorObj) { + if (ret.e != null && + ret.e.name !== "StopProgressPropagation") { + var trace = util.canAttachTrace(ret.e) + ? ret.e : new Error(util.toString(ret.e)); + promise._attachExtraTrace(trace); + promise._progress(ret.e); + } + } else if (ret instanceof Promise) { + ret._then(promise._progress, null, null, promise, undefined); + } else { + promise._progress(ret); + } +}; + + +Promise.prototype._progressUnchecked = function (progressValue) { + var len = this._length(); + var progress = this._progress; + for (var i = 0; i < len; i++) { + var handler = this._progressHandlerAt(i); + var promise = this._promiseAt(i); + if (!(promise instanceof Promise)) { + var receiver = this._receiverAt(i); + if (typeof handler === "function") { + handler.call(receiver, progressValue, promise); + } else if (receiver instanceof PromiseArray && + !receiver._isResolved()) { + receiver._promiseProgressed(progressValue, promise); + } + continue; + } + + if (typeof handler === "function") { + async.invoke(this._doProgressWith, this, { + handler: handler, + promise: promise, + receiver: this._receiverAt(i), + value: progressValue + }); + } else { + async.invoke(progress, promise, progressValue); + } + } +}; +}; + +},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); +}; +var reflect = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var errors = _dereq_("./errors.js"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {e: null}; +var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = _dereq_("./captured_trace.js")(); +var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + _dereq_("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = _dereq_("./promise_resolver.js"); +var nodebackForPromise = PromiseResolver._nodebackForPromise; +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function Promise(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); + } + if (this.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._progressHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._settledValue = undefined; + if (resolver !== INTERNAL) this._resolveFromResolver(resolver); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (typeof item === "function") { + catchInstances[j++] = item; + } else { + return Promise.reject( + new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); + } + } + catchInstances.length = j; + fn = arguments[i]; + var catchFilter = new CatchFilter(catchInstances, fn, this); + return this._then(undefined, catchFilter.doFilter, undefined, + catchFilter, undefined); + } + return this._then(undefined, fn, undefined, undefined, undefined); +}; + +Promise.prototype.reflect = function () { + return this._then(reflect, reflect, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject, didProgress) { + if (isDebugging() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, didProgress, + undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject, didProgress) { + var promise = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (didFulfill, didReject) { + return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); +}; + +Promise.prototype.isCancellable = function () { + return !this.isResolved() && + this._cancellable(); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = function(fn) { + var ret = new Promise(INTERNAL); + var result = tryCatch(fn)(nodebackForPromise(ret)); + if (result === errorObj) { + ret._rejectCallback(result.e, true, true); + } + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.defer = Promise.pending = function () { + var promise = new Promise(INTERNAL); + return new PromiseResolver(promise); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + var val = ret; + ret = new Promise(INTERNAL); + ret._fulfillUnchecked(val); + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + didProgress, + receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var ret = haveInternalData ? internalData : new Promise(INTERNAL); + + if (!haveInternalData) { + ret._propagateFrom(this, 4 | 1); + ret._captureStackTrace(); + } + + var target = this._target(); + if (target !== this) { + if (receiver === undefined) receiver = this._boundTo; + if (!haveInternalData) ret._setIsMigrated(); + } + + var callbackIndex = + target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); + + if (target._isResolved() && !target._isSettlePromisesQueued()) { + async.invoke( + target._settlePromiseAtPostResolution, target, callbackIndex); + } + + return ret; +}; + +Promise.prototype._settlePromiseAtPostResolution = function (index) { + if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); + this._settlePromiseAt(index); +}; + +Promise.prototype._length = function () { + return this._bitField & 131071; +}; + +Promise.prototype._isFollowingOrFulfilledOrRejected = function () { + return (this._bitField & 939524096) > 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 536870912) === 536870912; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -131072) | + (len & 131071); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 536870912; +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 33554432; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 33554432) > 0; +}; + +Promise.prototype._cancellable = function () { + return (this._bitField & 67108864) > 0; +}; + +Promise.prototype._setCancellable = function () { + this._bitField = this._bitField | 67108864; +}; + +Promise.prototype._unsetCancellable = function () { + this._bitField = this._bitField & (~67108864); +}; + +Promise.prototype._setIsMigrated = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._unsetIsMigrated = function () { + this._bitField = this._bitField & (~4194304); +}; + +Promise.prototype._isMigrated = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 + ? this._receiver0 + : this[ + index * 5 - 5 + 4]; + if (ret === undefined && this._isBound()) { + return this._boundTo; + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return index === 0 + ? this._promise0 + : this[index * 5 - 5 + 3]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return index === 0 + ? this._fulfillmentHandler0 + : this[index * 5 - 5 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return index === 0 + ? this._rejectionHandler0 + : this[index * 5 - 5 + 1]; +}; + +Promise.prototype._migrateCallbacks = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var progress = follower._progressHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (promise instanceof Promise) promise._setIsMigrated(); + this._addCallbacks(fulfill, reject, progress, promise, receiver); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + progress, + promise, + receiver +) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + if (receiver !== undefined) this._receiver0 = receiver; + if (typeof fulfill === "function" && !this._isCarryingStackTrace()) + this._fulfillmentHandler0 = fulfill; + if (typeof reject === "function") this._rejectionHandler0 = reject; + if (typeof progress === "function") this._progressHandler0 = progress; + } else { + var base = index * 5 - 5; + this[base + 3] = promise; + this[base + 4] = receiver; + if (typeof fulfill === "function") + this[base + 0] = fulfill; + if (typeof reject === "function") + this[base + 1] = reject; + if (typeof progress === "function") + this[base + 2] = progress; + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + if (index === 0) { + this._promise0 = promiseSlotValue; + this._receiver0 = receiver; + } else { + var base = index * 5 - 5; + this[base + 3] = promiseSlotValue; + this[base + 4] = receiver; + } + this._setLength(index + 1); +}; + +Promise.prototype._proxyPromiseArray = function (promiseArray, index) { + this._setProxyHandlers(promiseArray, index); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (this._isFollowingOrFulfilledOrRejected()) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false, true); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + var propagationFlags = 1 | (shouldBind ? 4 : 0); + this._propagateFrom(maybePromise, propagationFlags); + var promise = maybePromise._target(); + if (promise._isPending()) { + var len = this._length(); + for (var i = 0; i < len; ++i) { + promise._migrateCallbacks(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (promise._isFulfilled()) { + this._fulfillUnchecked(promise._value()); + } else { + this._rejectUnchecked(promise._reason(), + promise._getCarriedStackTrace()); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { + if (!shouldNotMarkOriginatingFromRejection) { + util.markAsOriginatingFromRejection(reason); + } + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, hasStack ? undefined : trace); +}; + +Promise.prototype._resolveFromResolver = function (resolver) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = tryCatch(resolver)(function(value) { + if (promise === null) return; + promise._resolveCallback(value); + promise = null; + }, function (reason) { + if (promise === null) return; + promise._rejectCallback(reason, synchronous); + promise = null; + }); + synchronous = false; + this._popContext(); + + if (r !== undefined && r === errorObj && promise !== null) { + promise._rejectCallback(r.e, true, true); + promise = null; + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + if (promise._isRejected()) return; + promise._pushContext(); + var x; + if (receiver === APPLY && !this._isRejected()) { + x = tryCatch(handler).apply(this._boundTo, value); + } else { + x = tryCatch(handler).call(receiver, value); + } + promise._popContext(); + + if (x === errorObj || x === promise || x === NEXT_FILTER) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false, true); + } else { + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._cleanValues = function () { + if (this._cancellable()) { + this._cancellationParent = undefined; + } +}; + +Promise.prototype._propagateFrom = function (parent, flags) { + if ((flags & 1) > 0 && parent._cancellable()) { + this._setCancellable(); + this._cancellationParent = parent; + } + if ((flags & 4) > 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +}; + +Promise.prototype._fulfill = function (value) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._fulfillUnchecked(value); +}; + +Promise.prototype._reject = function (reason, carriedStackTrace) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._rejectUnchecked(reason, carriedStackTrace); +}; + +Promise.prototype._settlePromiseAt = function (index) { + var promise = this._promiseAt(index); + var isPromise = promise instanceof Promise; + + if (isPromise && promise._isMigrated()) { + promise._unsetIsMigrated(); + return async.invoke(this._settlePromiseAt, this, index); + } + var handler = this._isFulfilled() + ? this._fulfillmentHandlerAt(index) + : this._rejectionHandlerAt(index); + + var carriedStackTrace = + this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; + var value = this._settledValue; + var receiver = this._receiverAt(index); + + + this._clearCallbackDataAtIndex(index); + + if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof PromiseArray) { + if (!receiver._isResolved()) { + if (this._isFulfilled()) { + receiver._promiseFulfilled(value, promise); + } + else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (this._isFulfilled()) { + promise._fulfill(value); + } else { + promise._reject(value, carriedStackTrace); + } + } + + if (index >= 4 && (index & 31) === 4) + async.invokeLater(this._setLength, this, 0); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + if (index === 0) { + if (!this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = undefined; + } + this._rejectionHandler0 = + this._progressHandler0 = + this._receiver0 = + this._promise0 = undefined; + } else { + var base = index * 5 - 5; + this[base + 3] = + this[base + 4] = + this[base + 0] = + this[base + 1] = + this[base + 2] = undefined; + } +}; + +Promise.prototype._isSettlePromisesQueued = function () { + return (this._bitField & + -1073741824) === -1073741824; +}; + +Promise.prototype._setSettlePromisesQueued = function () { + this._bitField = this._bitField | -1073741824; +}; + +Promise.prototype._unsetSettlePromisesQueued = function () { + this._bitField = this._bitField & (~-1073741824); +}; + +Promise.prototype._queueSettlePromises = function() { + async.settlePromises(this); + this._setSettlePromisesQueued(); +}; + +Promise.prototype._fulfillUnchecked = function (value) { + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err, undefined); + } + this._setFulfilled(); + this._settledValue = value; + this._cleanValues(); + + if (this._length() > 0) { + this._queueSettlePromises(); + } +}; + +Promise.prototype._rejectUncheckedCheckError = function (reason) { + var trace = util.ensureErrorObject(reason); + this._rejectUnchecked(reason, trace === reason ? undefined : trace); +}; + +Promise.prototype._rejectUnchecked = function (reason, trace) { + if (reason === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err); + } + this._setRejected(); + this._settledValue = reason; + this._cleanValues(); + + if (this._isFinal()) { + async.throwLater(function(e) { + if ("stack" in e) { + async.invokeFirst( + CapturedTrace.unhandledRejection, undefined, e); + } + throw e; + }, trace === undefined ? reason : trace); + return; + } + + if (trace !== undefined && trace !== reason) { + this._setCarriedStackTrace(trace); + } + + if (this._length() > 0) { + this._queueSettlePromises(); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._settlePromises = function () { + this._unsetSettlePromisesQueued(); + var len = this._length(); + for (var i = 0; i < len; i++) { + this._settlePromiseAt(i); + } +}; + +Promise._makeSelfResolutionError = makeSelfResolutionError; +_dereq_("./progress.js")(Promise, PromiseArray); +_dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +_dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +_dereq_("./direct_resolve.js")(Promise); +_dereq_("./synchronous_inspection.js")(Promise); +_dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./cancel.js')(Promise); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +_dereq_('./nodeify.js')(Promise); +_dereq_('./call_get.js')(Promise); +_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./settle.js')(Promise, PromiseArray); +_dereq_('./some.js')(Promise, PromiseArray, apiRejection); +_dereq_('./promisify.js')(Promise, INTERNAL); +_dereq_('./any.js')(Promise); +_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./timers.js')(Promise, INTERNAL); +_dereq_('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._progressHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + p._settledValue = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + CapturedTrace.setBounds(async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = _dereq_("./util.js"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + var parent; + if (values instanceof Promise) { + parent = values; + promise._propagateFrom(parent, 1 | 4); + } + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + this._values = values; + if (values._isFulfilled()) { + values = values._value(); + if (!isArray(values)) { + var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + this.__hardReject__(err); + return; + } + } else if (values._isPending()) { + values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + return; + } else { + this._reject(values._reason()); + return; + } + } else if (!isArray(values)) { + this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var promise = this._promise; + for (var i = 0; i < len; ++i) { + var isResolved = this._isResolved(); + var maybePromise = tryConvertToPromise(values[i], promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (isResolved) { + maybePromise._unsetRejectionIsUnhandled(); + } else if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, i); + } else if (maybePromise._isFulfilled()) { + this._promiseFulfilled(maybePromise._value(), i); + } else { + this._promiseRejected(maybePromise._reason(), i); + } + } else if (!isResolved) { + this._promiseFulfilled(maybePromise, i); + } + } +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype.__hardReject__ = +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false, true); +}; + +PromiseArray.prototype._promiseProgressed = function (progressValue, index) { + this._promise._progress({ + index: index, + value: progressValue + }); +}; + + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +PromiseArray.prototype._promiseRejected = function (reason, index) { + this._totalResolved++; + this._reject(reason); +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util.js":38}],25:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = _dereq_("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = _dereq_("./es5.js"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise) { + return function(err, value) { + if (promise === null) return; + + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (arguments.length > 2) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + promise._fulfill(args); + } else { + promise._fulfill(value); + } + + promise = null; + }; +} + + +var PromiseResolver; +if (!haveGetters) { + PromiseResolver = function (promise) { + this.promise = promise; + this.asCallback = nodebackForPromise(promise); + this.callback = this.asCallback; + }; +} +else { + PromiseResolver = function (promise) { + this.promise = promise; + }; +} +if (haveGetters) { + var prop = { + get: function() { + return nodebackForPromise(this.promise); + } + }; + es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); + es5.defineProperty(PromiseResolver.prototype, "callback", prop); +} + +PromiseResolver._nodebackForPromise = nodebackForPromise; + +PromiseResolver.prototype.toString = function () { + return "[object PromiseResolver]"; +}; + +PromiseResolver.prototype.resolve = +PromiseResolver.prototype.fulfill = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._resolveCallback(value); +}; + +PromiseResolver.prototype.reject = function (reason) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._rejectCallback(reason); +}; + +PromiseResolver.prototype.progress = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._progress(value); +}; + +PromiseResolver.prototype.cancel = function (err) { + this.promise.cancel(err); +}; + +PromiseResolver.prototype.timeout = function () { + this.reject(new TimeoutError("timeout")); +}; + +PromiseResolver.prototype.isResolved = function () { + return this.promise.isResolved(); +}; + +PromiseResolver.prototype.toJSON = function () { + return this.promise.toJSON(); +}; + +module.exports = PromiseResolver; + +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = _dereq_("./util.js"); +var nodebackForPromise = _dereq_("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = _dereq_("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyPropsPattern = + /^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/; +var defaultFilter = function(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} + +function isPromisified(fn) { + try { + return fn.__isPromisified__ === true; + } + catch (e) { + return false; + } +} + +function hasPromisified(obj, key, suffix) { + var val = util.getDataPropertyOrDefault(obj, key + suffix, + defaultPromisified); + return val ? isPromisified(val) : false; +} +function checkValid(ret, suffix, suffixRegexp) { + for (var i = 0; i < ret.length; i += 2) { + var key = ret[i]; + if (suffixRegexp.test(key)) { + var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); + for (var j = 0; j < ret.length; j += 2) { + if (ret[j] === keyWithoutAsyncSuffix) { + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a" + .replace("%s", suffix)); + } + } + } + } +} + +function promisifiableMethods(obj, suffix, suffixRegexp, filter) { + var keys = util.inheritedDataKeys(obj); + var ret = []; + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var value = obj[key]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} + +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!true) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { + var ret = [likelyArgumentCount]; + var min = Math.max(0, likelyArgumentCount - 1 - 3); + for(var i = likelyArgumentCount - 1; i >= min; --i) { + ret.push(i); + } + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { + ret.push(i); + } + return ret; +}; + +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; + +var parameterCount = function(fn) { + if (typeof fn.length === "number") { + return Math.max(Math.min(fn.length, 1023 + 1), 0); + } + return 0; +}; + +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn) { + var newParameterCount = Math.max(0, parameterCount(fn) - 1); + var argumentOrder = switchCaseArgumentOrder(newParameterCount); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; + + function generateCallForArgumentCount(count) { + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; + } + return ret.replace("{{args}}", args).replace(", ", comma); + } + + function generateArgumentSwitchCase() { + var ret = ""; + for (var i = 0; i < argumentOrder.length; ++i) { + ret += "case " + argumentOrder[i] +":" + + generateCallForArgumentCount(argumentOrder[i]); + } + + ret += " \n\ + default: \n\ + var args = new Array(len + 1); \n\ + var i = 0; \n\ + for (var i = 0; i < len; ++i) { \n\ + args[i] = arguments[i]; \n\ + } \n\ + args[i] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); + return ret; + } + + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "INTERNAL","'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + return promise; \n\ + }; \n\ + ret.__isPromisified__ = true; \n\ + return ret; \n\ + " + .replace("Parameters", parameterDeclaration(newParameterCount)) + .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode))( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + INTERNAL + ); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } + function promisified() { + var _receiver = receiver; + if (receiver === THIS) _receiver = this; + var promise = new Promise(INTERNAL); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; + var fn = nodebackForPromise(promise); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + return promise; + } + promisified.__isPromisified__ = true; + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier) { + var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); + var methods = + promisifiableMethods(obj, suffix, suffixRegexp, filter); + + for (var i = 0, len = methods.length; i < len; i+= 2) { + var key = methods[i]; + var fn = methods[i+1]; + var promisifiedKey = key + suffix; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver) { + return makeNodePromisified(callback, receiver, undefined, callback); +} + +Promise.promisify = function (fn, receiver) { + if (typeof fn !== "function") { + throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + if (isPromisified(fn)) { + return fn; + } + var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + util.copyDescriptors(fn, ret, propsFilter); + return ret; +}; + +Promise.promisifyAll = function (target, options) { + if (typeof target !== "function" && typeof target !== "object") { + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a"); + } + options = Object(options); + var suffix = options.suffix; + if (typeof suffix !== "string") suffix = defaultSuffix; + var filter = options.filter; + if (typeof filter !== "function") filter = defaultFilter; + var promisifier = options.promisifier; + if (typeof promisifier !== "function") promisifier = makeNodePromisified; + + if (!util.isIdentifier(suffix)) { + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); + } + + var keys = util.inheritedDataKeys(target); + for (var i = 0; i < keys.length; ++i) { + var value = target[keys[i]]; + if (keys[i] !== "constructor" && + util.isClass(value)) { + promisifyAll(value.prototype, suffix, filter, promisifier); + promisifyAll(value, suffix, filter, promisifier); + } + } + + return promisifyAll(target, suffix, filter, promisifier); +}; +}; + + +},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var isObject = util.isObject; +var es5 = _dereq_("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; +}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val = {}; + var keyOffset = this.length(); + for (var i = 0, len = this.length(); i < len; ++i) { + val[this._values[i + keyOffset]] = this._values[i]; + } + this._resolve(val); + } +}; + +PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { + this._promise._progress({ + key: this._values[index + this.length()], + value: value + }); +}; + +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; + +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); + + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } + + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 4); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; + +},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; + +},{}],29:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = _dereq_("./util.js").isArray; + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else if (!isArray(promises)) { + return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 4 | 1); + } + var fulfill = ret._fulfill; + var reject = ret._reject; + for (var i = 0, len = promises.length; i < len; ++i) { + var val = promises[i]; + + if (val === undefined && !(i in promises)) { + continue; + } + + Promise.cast(val)._then(fulfill, reject, undefined, ret, null); + } + return ret; +} + +Promise.race = function (promises) { + return race(promises, undefined); +}; + +Promise.prototype.race = function () { + return race(this, undefined); +}; + +}; + +},{"./util.js":38}],30:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +function ReductionPromiseArray(promises, fn, accum, _each) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._preservedValues = _each === INTERNAL ? [] : null; + this._zerothIsAccum = (accum === undefined); + this._gotAccum = false; + this._reducingIndex = (this._zerothIsAccum ? 1 : 0); + this._valuesPhase = undefined; + var maybePromise = tryConvertToPromise(accum, this._promise); + var rejected = false; + var isPromise = maybePromise instanceof Promise; + if (isPromise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, -1); + } else if (maybePromise._isFulfilled()) { + accum = maybePromise._value(); + this._gotAccum = true; + } else { + this._reject(maybePromise._reason()); + rejected = true; + } + } + if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; + this._callback = fn; + this._accum = accum; + if (!rejected) async.invoke(init, this, undefined); +} +function init() { + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._init = function () {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); + } +}; + +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + values[index] = value; + var length = this.length(); + var preservedValues = this._preservedValues; + var isEach = preservedValues !== null; + var gotAccum = this._gotAccum; + var valuesPhase = this._valuesPhase; + var valuesPhaseIndex; + if (!valuesPhase) { + valuesPhase = this._valuesPhase = new Array(length); + for (valuesPhaseIndex=0; valuesPhaseIndex 10) || (version[0] > 0) + ? function(fn) { global.setImmediate(fn); } : process.nextTick; + + if (!schedule) { + if (typeof setImmediate !== "undefined") { + schedule = setImmediate; + } else if (typeof setTimeout !== "undefined") { + schedule = setTimeout; + } else { + schedule = noAsyncScheduler; + } + } +} else if (typeof MutationObserver !== "undefined") { + schedule = function(fn) { + var div = document.createElement("div"); + var observer = new MutationObserver(fn); + observer.observe(div, {attributes: true}); + return function() { div.classList.toggle("foo"); }; + }; + schedule.isStatic = true; +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; + +},{"./util.js":38}],32:[function(_dereq_,module,exports){ +"use strict"; +module.exports = + function(Promise, PromiseArray) { +var PromiseInspection = Promise.PromiseInspection; +var util = _dereq_("./util.js"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 268435456; + ret._settledValue = value; + this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 134217728; + ret._settledValue = reason; + this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return new SettledPromiseArray(this).promise(); +}; +}; + +},{"./util.js":38}],33:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = _dereq_("./util.js"); +var RangeError = _dereq_("./errors.js").RangeError; +var AggregateError = _dereq_("./errors.js").AggregateError; +var isArray = util.isArray; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + this._addFulfilled(value); + if (this._fulfilled() === this.howMany()) { + this._values.length = this.howMany(); + if (this.howMany() === 1 && this._unwrap) { + this._resolve(this._values[0]); + } else { + this._resolve(this._values); + } + } + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + e.push(this._values[i]); + } + this._reject(e); + } +}; + +SomePromiseArray.prototype._fulfilled = function () { + return this._totalResolved; +}; + +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); +}; + +SomePromiseArray.prototype._addRejected = function (reason) { + this._values.push(reason); +}; + +SomePromiseArray.prototype._addFulfilled = function (value) { + this._values[this._totalResolved++] = value; +}; + +SomePromiseArray.prototype._canPossiblyFulfill = function () { + return this.length() - this._rejected(); +}; + +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); +}; + +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; + +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} + +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; + +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; + +Promise._SomePromiseArray = SomePromiseArray; +}; + +},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValue = promise._settledValue; + } + else { + this._bitField = 0; + this._settledValue = undefined; + } +} + +PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.isFulfilled = +Promise.prototype._isFulfilled = function () { + return (this._bitField & 268435456) > 0; +}; + +PromiseInspection.prototype.isRejected = +Promise.prototype._isRejected = function () { + return (this._bitField & 134217728) > 0; +}; + +PromiseInspection.prototype.isPending = +Promise.prototype._isPending = function () { + return (this._bitField & 402653184) === 0; +}; + +PromiseInspection.prototype.isResolved = +Promise.prototype._isResolved = function () { + return (this._bitField & 402653184) > 0; +}; + +Promise.prototype.isPending = function() { + return this._target()._isPending(); +}; + +Promise.prototype.isRejected = function() { + return this._target()._isRejected(); +}; + +Promise.prototype.isFulfilled = function() { + return this._target()._isFulfilled(); +}; + +Promise.prototype.isResolved = function() { + return this._target()._isResolved(); +}; + +Promise.prototype._value = function() { + return this._settledValue; +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue; +}; + +Promise.prototype.value = function() { + var target = this._target(); + if (!target.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return target._settledValue; +}; + +Promise.prototype.reason = function() { + var target = this._target(); + if (!target.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + target._unsetRejectionIsUnhandled(); + return target._settledValue; +}; + + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],35:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) { + return obj; + } + else if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfillUnchecked, + ret._rejectUncheckedCheckError, + ret._progressUnchecked, + ret, + null + ); + return ret; + } + var then = util.tryCatch(getThen)(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + return doThenable(obj, then, context); + } + } + return obj; +} + +function getThen(obj) { + return obj.then; +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, + resolveFromThenable, + rejectFromThenable, + progressFromThenable); + synchronous = false; + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolveFromThenable(value) { + if (!promise) return; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + promise._resolveCallback(value); + } + promise = null; + } + + function rejectFromThenable(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + + function progressFromThenable(value) { + if (!promise) return; + if (typeof promise._progress === "function") { + promise._progress(value); + } + } + return ret; +} + +return tryConvertToPromise; +}; + +},{"./util.js":38}],36:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + if (typeof message !== "string") { + message = "operation timed out"; + } + var err = new TimeoutError(message); + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._cancel(err); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (value, ms) { + if (ms === undefined) { + ms = value; + value = undefined; + var ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, ms); + return ret; + } + ms = +ms; + return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); +}; + +Promise.prototype.delay = function (ms) { + return delay(this, ms); +}; + +function successClear(value) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + return value; +} + +function failureClear(reason) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret = this.then().cancellable(); + ret._cancellationParent = this; + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; + +},{"./util.js":38}],37:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = _dereq_("./errors.js").TypeError; + var inherits = _dereq_("./util.js").inherits; + var PromiseInspection = Promise.PromiseInspection; + + function inspectionMapper(inspections) { + var len = inspections.length; + for (var i = 0; i < len; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + return Promise.reject(inspection.error()); + } + inspections[i] = inspection._settledValue; + } + return inspections; + } + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + if (maybePromise !== thenable && + typeof thenable._isDisposable === "function" && + typeof thenable._getDisposer === "function" && + thenable._isDisposable()) { + maybePromise._setDisposable(thenable._getDisposer()); + } + return maybePromise; + } + function dispose(resources, inspection) { + var i = 0; + var len = resources.length; + var ret = Promise.defer(); + function iterator() { + if (i >= len) return ret.resolve(); + var maybePromise = castPreservingDisposable(resources[i++]); + if (maybePromise instanceof Promise && + maybePromise._isDisposable()) { + try { + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); + } catch (e) { + return thrower(e); + } + if (maybePromise instanceof Promise) { + return maybePromise._then(iterator, thrower, + null, null, null); + } + } + iterator(); + } + iterator(); + return ret.promise; + } + + function disposerSuccess(value) { + var inspection = new PromiseInspection(); + inspection._settledValue = value; + inspection._bitField = 268435456; + return dispose(this, inspection).thenReturn(value); + } + + function disposerFail(reason) { + var inspection = new PromiseInspection(); + inspection._settledValue = reason; + inspection._bitField = 134217728; + return dispose(this, inspection).thenThrow(reason); + } + + function Disposer(data, promise, context) { + this._data = data; + this._promise = promise; + this._context = context; + } + + Disposer.prototype.data = function () { + return this._data; + }; + + Disposer.prototype.promise = function () { + return this._promise; + }; + + Disposer.prototype.resource = function () { + if (this.promise().isFulfilled()) { + return this.promise().value(); + } + return null; + }; + + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== null + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; + + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); + }; + + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); + + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); + }; + + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); + } + return value; + } + + Promise.using = function () { + var len = arguments.length; + if (len < 2) return apiRejection( + "you must pass at least 2 arguments to Promise.using"); + var fn = arguments[len - 1]; + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } + } + resources[i] = resource; + } + + var promise = Promise.settle(resources) + .then(inspectionMapper) + .then(function(vals) { + promise._pushContext(); + var ret; + try { + ret = fn.apply(undefined, vals); + } finally { + promise._popContext(); + } + return ret; + }) + ._then( + disposerSuccess, disposerFail, undefined, resources, undefined); + resources.promise = promise; + return promise; + }; + + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 262144; + this._disposer = disposer; + }; + + Promise.prototype._isDisposable = function () { + return (this._bitField & 262144) > 0; + }; + + Promise.prototype._getDisposer = function () { + return this._disposer; + }; + + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~262144); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); + }; + +}; + +},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var canEvaluate = typeof navigator == "undefined"; +var haveGetters = (function(){ + try { + var o = {}; + es5.defineProperty(o, "f", { + get: function () { + return 3; + } + }); + return o.f === 3; + } + catch (e) { + return false; + } + +})(); + +var errorObj = {e: {}}; +var tryCatchTarget; +function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } + } + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return !isPrimitive(value); +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); +} + +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; +} + +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} + +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; +} + + +var wrapsPrimitiveReceiver = (function() { + return this !== "string"; +}).call("string"); + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + if (es5.isES5) { + var oProto = Object.prototype; + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && obj !== oProto) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function f() {} + f.prototype = obj; + var l = 8; + while (l--) new f(); + return obj; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + haveGetters: haveGetters, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" +}; +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5.js":14}],39:[function(_dereq_,module,exports){ +// 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. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } + throw TypeError('Uncaught, unspecified "error" event.'); + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + handler.apply(this, args); + } + } else if (isObject(handler)) { + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + var m; + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + var ret; + if (!emitter._events || !emitter._events[type]) + ret = 0; + else if (isFunction(emitter._events[type])) + ret = 1; + else + ret = emitter._events[type].length; + return ret; +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}]},{},[4])(4) +}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js new file mode 100644 index 0000000..679f778 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2014 Petka Antonov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions:

+ * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +/** + * bluebird build version 2.9.26 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers +*/ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,r;return function n(t,e,r){function i(s,a){if(!e[s]){if(!t[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=e[s]={exports:{}};t[s][0].call(l.exports,function(e){var r=t[s][1][e];return i(r?r:e)},l,l.exports,n,t,e,r)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0},r.prototype.throwLater=function(t,e){1===arguments.length&&(e=t,t=function(){throw e});var r=this._getDomain();if(void 0!==r&&(t=r.bind(t)),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(n){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")}},r.prototype._getDomain=function(){};l.hasDevTools?(r.prototype.invokeLater=function(t,e,r){this._trampolineEnabled?n.call(this,t,e,r):setTimeout(function(){t.call(e,r)},100)},r.prototype.invoke=function(t,e,r){this._trampolineEnabled?i.call(this,t,e,r):setTimeout(function(){t.call(e,r)},0)},r.prototype.settlePromises=function(t){this._trampolineEnabled?o.call(this,t):setTimeout(function(){t._settlePromises()},0)}):(r.prototype.invokeLater=n,r.prototype.invoke=i,r.prototype.settlePromises=o),r.prototype.invokeFirst=function(t,e,r){var n=this._getDomain();void 0!==n&&(t=n.bind(t)),this._normalQueue.unshift(t,e,r),this._queueTick()},r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var r=t.shift(),n=t.shift();e.call(r,n)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=new r,e.exports.firstLineError=s},{"./queue.js":28,"./schedule.js":31,"./util.js":38,events:39}],3:[function(t,e){"use strict";e.exports=function(t,e,r){var n=function(t,e){this._reject(e)},i=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(n,n,null,this,t)},o=function(t,e){this._setBoundTo(t),this._isPending()&&this._resolveCallback(e.target)},s=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(n){var a=r(n),u=new t(e);u._propagateFrom(this,1);var c=this._target();if(a instanceof t){var l={promiseRejectionQueued:!1,promise:u,target:c,bindingPromise:a};c._then(e,i,u._progress,u,l),a._then(o,s,u._progress,u,l)}else u._setBoundTo(n),u._resolveCallback(c);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=131072|this._bitField,this._boundTo=t):this._bitField=-131073&this._bitField},t.prototype._isBound=function(){return 131072===(131072&this._bitField)},t.bind=function(n,i){var o=r(n),s=new t(e);return o instanceof t?o._then(function(t){s._setBoundTo(t),s._resolveCallback(i)},s._reject,s._progress,s,null):(s._setBoundTo(n),s._resolveCallback(i)),s}}},{}],4:[function(t,e){"use strict";function r(){try{Promise===i&&(Promise=n)}catch(t){}return i}var n;"undefined"!=typeof Promise&&(n=Promise);var i=t("./promise.js")();i.noConflict=r,e.exports=i},{"./promise.js":23}],5:[function(t,e){"use strict";var r=Object.create;if(r){var n=r(null),i=r(null);n[" size"]=i[" size"]=0}e.exports=function(e){function r(t,r){var n;if(null!=t&&(n=t[r]),"function"!=typeof n){var i="Object "+a.classString(t)+" has no method '"+a.toString(r)+"'";throw new e.TypeError(i)}return n}function n(t){var e=this.pop(),n=r(t,e);return n.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}{var s,a=t("./util.js"),u=a.canEvaluate;a.isIdentifier}e.prototype.call=function(t){for(var e=arguments.length,r=new Array(e-1),i=1;e>i;++i)r[i-1]=arguments[i];return r.push(t),this._then(n,void 0,void 0,r,void 0)},e.prototype.get=function(t){var e,r="number"==typeof t;if(r)e=o;else if(u){var n=s(t);e=null!==n?n:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util.js":38}],6:[function(t,e){"use strict";e.exports=function(e){var r=t("./errors.js"),n=t("./async.js"),i=r.CancellationError;e.prototype._cancel=function(t){if(!this.isCancellable())return this;for(var e,r=this;void 0!==(e=r._cancellationParent)&&e.isCancellable();)r=e;this._unsetCancellable(),r._target()._rejectCallback(t,!1,!0)},e.prototype.cancel=function(t){return this.isCancellable()?(void 0===t&&(t=new i),n.invokeLater(this._cancel,this,t),this):this},e.prototype.cancellable=function(){return this._cancellable()?this:(n.enableTrampoline(),this._setCancellable(),this._cancellationParent=void 0,this)},e.prototype.uncancellable=function(){var t=this.then();return t._unsetCancellable(),t},e.prototype.fork=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);return n._setCancellable(),n._cancellationParent=void 0,n}}},{"./async.js":2,"./errors.js":13}],7:[function(t,e){"use strict";e.exports=function(){function e(t){this._parent=t;var r=this._length=1+(void 0===t?0:t._length);j(this,e),r>32&&this.uncycle()}function r(t,e){for(var r=0;r=0;--a)if(n[a]===o){s=a;break}for(var a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}function o(t){for(var e=[],r=0;r0&&(e=e.slice(r)),e}function a(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t.toString();var r=/\[object [a-zA-Z0-9$_]+\]/;if(r.test(e))try{var n=JSON.stringify(t);e=n}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+u(e)+">, no stack trace)"}function u(t){var e=41;return t.lengtht)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;t=this._length=n;for(var n=t-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(var n=0;t>n;++n){var s=e[n].stack,a=r[s];if(void 0!==a&&a!==n){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var u=n>0?e[n-1]:this;t-1>a?(u._parent=e[a+1],u._parent.uncycle(),u._length=u._parent._length+1):(u._parent=void 0,u._length=1);for(var c=u._length+1,l=n-2;l>=0;--l)e[l]._length=c,c++;return}}}},e.prototype.parent=function(){return this._parent},e.prototype.hasParent=function(){return void 0!==this._parent},e.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var s=e.parseStackAndMessage(t),a=s.message,u=[s.stack],c=this;void 0!==c;)u.push(o(c.stack.split("\n"))),c=c._parent;i(u),n(u),p.notEnumerableProp(t,"stack",r(a,u)),p.notEnumerableProp(t,"__stackCleaned__",!0)}},e.parseStackAndMessage=function(t){var e=t.stack,r=t.toString();return e="string"==typeof e&&e.length>0?s(t):[" (No stack trace)"],{message:r,stack:o(e)}},e.formatAndLogError=function(t,e){if("undefined"!=typeof console){var r;if("object"==typeof t||"function"==typeof t){var n=t.stack;r=e+d(n,t)}else r=e+String(t);"function"==typeof l?l(r):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}},e.unhandledRejection=function(t){e.formatAndLogError(t,"^--- With additional stack trace: ")},e.isSupported=function(){return"function"==typeof j},e.fireRejectionEvent=function(t,r,n,i){var o=!1;try{"function"==typeof r&&(o=!0,"rejectionHandled"===t?r(i):r(n,i))}catch(s){h.throwLater(s)}var a=!1;try{a=b(t,n,i)}catch(s){a=!0,h.throwLater(s)}var u=!1;if(m)try{u=m(t.toLowerCase(),{reason:n,promise:i})}catch(s){u=!0,h.throwLater(s)}a||o||u||"unhandledRejection"!==t||e.formatAndLogError(n,"Unhandled rejection ")};var y=function(){return!1},g=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;e.setBounds=function(t,r){if(e.isSupported()){for(var n,i,o=t.stack.split("\n"),s=r.stack.split("\n"),a=-1,u=-1,l=0;la||0>u||!n||!i||n!==i||a>=u||(y=function(t){if(f.test(t))return!0;var e=c(t);return e&&e.fileName===n&&a<=e.line&&e.line<=u?!0:!1})}};var m,j=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():a(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit=Error.stackTraceLimit+6,_=t,d=e;var r=Error.captureStackTrace;return y=function(t){return f.test(t)},function(t,e){Error.stackTraceLimit=Error.stackTraceLimit+6,r(t,e),Error.stackTraceLimit=Error.stackTraceLimit-6}}var n=new Error;if("string"==typeof n.stack&&n.stack.split("\n")[0].indexOf("stackDetection@")>=0)return _=/@/,d=e,v=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in n||!i?(d=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?a(e):e.toString()},null):(_=t,d=e,function(t){Error.stackTraceLimit=Error.stackTraceLimit+6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit=Error.stackTraceLimit-6})}([]),b=function(){if(p.isNode)return function(t,e,r){return"rejectionHandled"===t?process.emit(t,r):process.emit(t,e,r)};var t=!1,e=!0;try{var r=new self.CustomEvent("test");t=r instanceof CustomEvent}catch(n){}if(!t)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(n){e=!1}e&&(m=function(e,r){var n;return t?n=new self.CustomEvent(e,{detail:r,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(n=document.createEvent("CustomEvent"),n.initCustomEvent(e,!1,!0,r)),n?!self.dispatchEvent(n):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,r){var n=o[t],i=self[n];return i?("rejectionHandled"===t?i.call(self,r):i.call(self,e,r),!0):!1}}();return"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(l=function(t){console.warn(t)},p.isNode&&process.stderr.isTTY?l=function(t){process.stderr.write(""+t+"\n")}:p.isNode||"string"!=typeof(new Error).stack||(l=function(t){console.warn("%c"+t,"color: red")})),e}},{"./async.js":2,"./util.js":38}],8:[function(t,e){"use strict";e.exports=function(e){function r(t,e,r){this._instances=t,this._callback=e,this._promise=r}function n(t,e){var r={},n=s(t).call(r,e);if(n===a)return n;var i=u(r);return i.length?(a.e=new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"),a):n}var i=t("./util.js"),o=t("./errors.js"),s=i.tryCatch,a=i.errorObj,u=t("./es5.js").keys,c=o.TypeError;return r.prototype.doFilter=function(t){for(var r=this._callback,i=this._promise,o=i._boundTo,u=0,c=this._instances.length;c>u;++u){var l=this._instances[u],h=l===Error||null!=l&&l.prototype instanceof Error;if(h&&t instanceof l){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}if("function"==typeof l&&!h){var f=n(l,t);if(f===a){t=a.e;break}if(f){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}}}return e.e=t,e},r}},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(t,e){"use strict";e.exports=function(t,e,r){function n(){this._trace=new e(o())}function i(){return r()?new n:void 0}function o(){var t=s.length-1;return t>=0?s[t]:void 0}var s=[];return n.prototype._pushContext=function(){r()&&void 0!==this._trace&&s.push(this._trace)},n.prototype._popContext=function(){r()&&void 0!==this._trace&&s.pop()},t.prototype._peekContext=o,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,i}},{}],10:[function(t,e){"use strict";e.exports=function(e,r){var n,i,o=t("./async.js"),s=t("./errors.js").Warning,a=t("./util.js"),u=a.canAttachTrace,c=!1||a.isNode&&(!!process.env.BLUEBIRD_DEBUG||"development"===process.env.NODE_ENV);return c&&o.disableTrampolineIfNecessary(),e.prototype._ensurePossibleRejectionHandled=function(){this._setRejectionIsUnhandled(),o.invokeLater(this._notifyUnhandledRejection,this,void 0)},e.prototype._notifyUnhandledRejectionIsHandled=function(){r.fireRejectionEvent("rejectionHandled",n,void 0,this)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._getCarriedStackTrace()||this._settledValue;this._setUnhandledRejectionIsNotified(),r.fireRejectionEvent("unhandledRejection",i,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=524288|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-524289&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(524288&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=2097152|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-2097153&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(2097152&this._bitField)>0},e.prototype._setCarriedStackTrace=function(t){this._bitField=1048576|this._bitField,this._fulfillmentHandler0=t},e.prototype._isCarryingStackTrace=function(){return(1048576&this._bitField)>0},e.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0},e.prototype._captureStackTrace=function(){return c&&(this._trace=new r(this._peekContext())),this},e.prototype._attachExtraTrace=function(t,e){if(c&&u(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var i=r.parseStackAndMessage(t);a.notEnumerableProp(t,"stack",i.message+"\n"+i.stack.join("\n")),a.notEnumerableProp(t,"__stackCleaned__",!0)}}},e.prototype._warn=function(t){var e=new s(t),n=this._peekContext();if(n)n.attachExtraTrace(e);else{var i=r.parseStackAndMessage(e);e.stack=i.message+"\n"+i.stack.join("\n")}r.formatAndLogError(e,"")},e.onPossiblyUnhandledRejection=function(t){i="function"==typeof t?t:void 0},e.onUnhandledRejectionHandled=function(t){n="function"==typeof t?t:void 0},e.longStackTraces=function(){if(o.haveItemsQueued()&&c===!1)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/DT1qyG\n");c=r.isSupported(),c&&o.disableTrampolineIfNecessary()},e.hasLongStackTraces=function(){return c&&r.isSupported()},r.isSupported()||(e.longStackTraces=function(){},c=!1),function(){return c}}},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(t,e){"use strict";var r=t("./util.js"),n=r.isPrimitive,i=r.wrapsPrimitiveReceiver;e.exports=function(t){var e=function(){return this},r=function(){throw this},o=function(){},s=function(){throw void 0},a=function(t,e){return 1===e?function(){throw t}:2===e?function(){return t}:void 0};t.prototype["return"]=t.prototype.thenReturn=function(t){return void 0===t?this.then(o):i&&n(t)?this._then(a(t,2),void 0,void 0,void 0,void 0):this._then(e,void 0,void 0,t,void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return void 0===t?this.then(s):i&&n(t)?this._then(a(t,1),void 0,void 0,void 0,void 0):this._then(r,void 0,void 0,t,void 0)}}},{"./util.js":38}],12:[function(t,e){"use strict";e.exports=function(t,e){var r=t.reduce;t.prototype.each=function(t){return r(this,t,null,e)},t.each=function(t,n){return r(t,n,null,e)}}},{}],13:[function(t,e){"use strict";function r(t,e){function r(n){return this instanceof r?(l(this,"message","string"==typeof n?n:e),l(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new r(n)}return c(r,Error),r}function n(t){return this instanceof n?(l(this,"name","OperationalError"),l(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(l(this,"message",t.message),l(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new n(t)}var i,o,s=t("./es5.js"),a=s.freeze,u=t("./util.js"),c=u.inherits,l=u.notEnumerableProp,h=r("Warning","warning"),p=r("CancellationError","cancellation error"),f=r("TimeoutError","timeout error"),_=r("AggregateError","aggregate error");try{i=TypeError,o=RangeError}catch(d){i=r("TypeError","type error"),o=r("RangeError","range error")}for(var v="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y0&&"function"==typeof arguments[e]){t=arguments[e];var n}for(var i=arguments.length,o=new Array(i),s=0;i>s;++s)o[s]=arguments[s];t&&o.pop();var n=new r(o).promise();return void 0!==t?n.spread(t):n}}},{"./util.js":38}],19:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,e,r,n){this.constructor$(t),this._promise._captureStackTrace(),this._callback=e,this._preservedValues=n===o?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=r>=1?[]:_,c.invoke(a,this,void 0)}function a(){this._init$(void 0,-2)}function u(t,e,r,n){var i="object"==typeof r&&null!==r?r.concurrency:0;return i="number"==typeof i&&isFinite(i)&&i>=1?i:0,new s(t,e,i,n)}var c=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj,f={},_=[];l.inherits(s,r),s.prototype._init=function(){},s.prototype._promiseFulfilled=function(t,r){var n=this._values,o=this.length(),s=this._preservedValues,a=this._limit;if(n[r]===f){if(n[r]=t,a>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return}else{if(a>=1&&this._inFlight>=a)return n[r]=t,void this._queue.push(r);null!==s&&(s[r]=t);var u=this._callback,c=this._promise._boundTo;this._promise._pushContext();var l=h(u).call(c,t,r,o);if(this._promise._popContext(),l===p)return this._reject(l.e);var _=i(l,this._promise);if(_ instanceof e){if(_=_._target(),_._isPending())return a>=1&&this._inFlight++,n[r]=f,_._proxyPromiseArray(this,r);if(!_._isFulfilled())return this._reject(_._reason());l=_._value()}n[r]=l}var d=++this._totalResolved;d>=o&&(null!==s?this._filter(n,s):this._resolve(n))},s.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(n[i++]=e[o]);n.length=i,this._resolve(n)},s.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return"function"!=typeof t?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(this,t,e,null).promise()},e.map=function(t,e,r,i){return"function"!=typeof e?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(t,e,r,i).promise()}}},{"./async.js":2,"./util.js":38}],20:[function(t,e){"use strict";e.exports=function(e,r,n,i){var o=t("./util.js"),s=o.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");return function(){var n=new e(r);n._captureStackTrace(),n._pushContext();var i=s(t).apply(this,arguments);return n._popContext(),n._resolveFromSyncValue(i),n}},e.attempt=e["try"]=function(t,n,a){if("function"!=typeof t)return i("fn must be a function\n\n See http://goo.gl/916lJJ\n");var u=new e(r);u._captureStackTrace(),u._pushContext();var c=o.isArray(n)?s(t).apply(a,n):s(t).call(a,n);return u._popContext(),u._resolveFromSyncValue(c),u},e.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1,!0):this._resolveCallback(t,!0)}}},{"./util.js":38}],21:[function(t,e){"use strict";e.exports=function(e){function r(t,e){var r=this;if(!o.isArray(t))return n.call(r,t,e);var i=a(e).apply(r._boundTo,[null].concat(t));i===u&&s.throwLater(i.e)}function n(t,e){var r=this,n=r._boundTo,i=void 0===t?a(e).call(n,null):a(e).call(n,null,t);i===u&&s.throwLater(i.e)}function i(t,e){var r=this;if(!t){var n=r._target(),i=n._getCarriedStackTrace();i.cause=t,t=i}var o=a(e).call(r._boundTo,t);o===u&&s.throwLater(o.e)}var o=t("./util.js"),s=t("./async.js"),a=o.tryCatch,u=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=n;void 0!==e&&Object(e).spread&&(o=r),this._then(o,i,void 0,this,t)}return this}}},{"./async.js":2,"./util.js":38}],22:[function(t,e){"use strict";e.exports=function(e,r){var n=t("./util.js"),i=t("./async.js"),o=n.tryCatch,s=n.errorObj;e.prototype.progressed=function(t){return this._then(void 0,void 0,t,void 0,void 0)},e.prototype._progress=function(t){this._isFollowingOrFulfilledOrRejected()||this._target()._progressUnchecked(t)},e.prototype._progressHandlerAt=function(t){return 0===t?this._progressHandler0:this[(t<<2)+t-5+2]},e.prototype._doProgressWith=function(t){var r=t.value,i=t.handler,a=t.promise,u=t.receiver,c=o(i).call(u,r);if(c===s){if(null!=c.e&&"StopProgressPropagation"!==c.e.name){var l=n.canAttachTrace(c.e)?c.e:new Error(n.toString(c.e));a._attachExtraTrace(l),a._progress(c.e)}}else c instanceof e?c._then(a._progress,null,null,a,void 0):a._progress(c)},e.prototype._progressUnchecked=function(t){for(var n=this._length(),o=this._progress,s=0;n>s;s++){var a=this._progressHandlerAt(s),u=this._promiseAt(s);if(u instanceof e)"function"==typeof a?i.invoke(this._doProgressWith,this,{handler:a,promise:u,receiver:this._receiverAt(s),value:t}):i.invoke(o,u,t);else{var c=this._receiverAt(s);"function"==typeof a?a.call(c,t,u):c instanceof r&&!c._isResolved()&&c._promiseProgressed(t,u)}}}}},{"./async.js":2,"./util.js":38}],23:[function(t,e){"use strict";e.exports=function(){function e(t){if("function"!=typeof t)throw new c("the promise constructor requires a resolver function\n\n See http://goo.gl/EC22Yn\n");if(this.constructor!==e)throw new c("the promise constructor cannot be invoked directly\n\n See http://goo.gl/KsIlge\n");this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._progressHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._settledValue=void 0,t!==l&&this._resolveFromResolver(t)}function r(t){var r=new e(l);r._fulfillmentHandler0=t,r._rejectionHandler0=t,r._progressHandler0=t,r._promise0=t,r._receiver0=t,r._settledValue=t}var n=function(){return new c("circular promise resolution chain\n\n See http://goo.gl/LhFpo0\n")},i=function(){return new e.PromiseInspection(this._target())},o=function(t){return e.reject(new c(t))},s=t("./util.js"),a=t("./async.js"),u=t("./errors.js"),c=e.TypeError=u.TypeError;e.RangeError=u.RangeError,e.CancellationError=u.CancellationError,e.TimeoutError=u.TimeoutError,e.OperationalError=u.OperationalError,e.RejectionError=u.OperationalError,e.AggregateError=u.AggregateError;var l=function(){},h={},p={e:null},f=t("./thenables.js")(e,l),_=t("./promise_array.js")(e,l,f,o),d=t("./captured_trace.js")(),v=t("./debuggability.js")(e,d),y=t("./context.js")(e,d,v),g=t("./catch_filter.js")(p),m=t("./promise_resolver.js"),j=m._nodebackForPromise,b=s.errorObj,w=s.tryCatch;return e.prototype.toString=function(){return"[object Promise]"},e.prototype.caught=e.prototype["catch"]=function(t){var r=arguments.length;if(r>1){var n,i=new Array(r-1),o=0;for(n=0;r-1>n;++n){var s=arguments[n];if("function"!=typeof s)return e.reject(new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"));i[o++]=s}i.length=o,t=arguments[n];var a=new g(i,t,this);return this._then(void 0,a.doFilter,void 0,a,void 0)}return this._then(void 0,t,void 0,void 0,void 0)},e.prototype.reflect=function(){return this._then(i,i,void 0,this,void 0)},e.prototype.then=function(t,e,r){if(v()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+s.classString(t);arguments.length>1&&(n+=", "+s.classString(e)),this._warn(n)}return this._then(t,e,r,void 0,void 0)},e.prototype.done=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);n._setIsFinal()},e.prototype.spread=function(t,e){return this.all()._then(t,e,void 0,h,void 0)},e.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable() +},e.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},e.prototype.all=function(){return new _(this).promise()},e.prototype.error=function(t){return this.caught(s.originatesFromRejection,t)},e.is=function(t){return t instanceof e},e.fromNode=function(t){var r=new e(l),n=w(t)(j(r));return n===b&&r._rejectCallback(n.e,!0,!0),r},e.all=function(t){return new _(t).promise()},e.defer=e.pending=function(){var t=new e(l);return new m(t)},e.cast=function(t){var r=f(t);if(!(r instanceof e)){var n=r;r=new e(l),r._fulfillUnchecked(n)}return r},e.resolve=e.fulfilled=e.cast,e.reject=e.rejected=function(t){var r=new e(l);return r._captureStackTrace(),r._rejectCallback(t,!0),r},e.setScheduler=function(t){if("function"!=typeof t)throw new c("fn must be a function\n\n See http://goo.gl/916lJJ\n");var e=a._schedule;return a._schedule=t,e},e.prototype._then=function(t,r,n,i,o){var s=void 0!==o,u=s?o:new e(l);s||(u._propagateFrom(this,5),u._captureStackTrace());var c=this._target();c!==this&&(void 0===i&&(i=this._boundTo),s||u._setIsMigrated());var h=c._addCallbacks(t,r,n,u,i);return c._isResolved()&&!c._isSettlePromisesQueued()&&a.invoke(c._settlePromiseAtPostResolution,c,h),u},e.prototype._settlePromiseAtPostResolution=function(t){this._isRejectionUnhandled()&&this._unsetRejectionIsUnhandled(),this._settlePromiseAt(t)},e.prototype._length=function(){return 131071&this._bitField},e.prototype._isFollowingOrFulfilledOrRejected=function(){return(939524096&this._bitField)>0},e.prototype._isFollowing=function(){return 536870912===(536870912&this._bitField)},e.prototype._setLength=function(t){this._bitField=-131072&this._bitField|131071&t},e.prototype._setFulfilled=function(){this._bitField=268435456|this._bitField},e.prototype._setRejected=function(){this._bitField=134217728|this._bitField},e.prototype._setFollowing=function(){this._bitField=536870912|this._bitField},e.prototype._setIsFinal=function(){this._bitField=33554432|this._bitField},e.prototype._isFinal=function(){return(33554432&this._bitField)>0},e.prototype._cancellable=function(){return(67108864&this._bitField)>0},e.prototype._setCancellable=function(){this._bitField=67108864|this._bitField},e.prototype._unsetCancellable=function(){this._bitField=-67108865&this._bitField},e.prototype._setIsMigrated=function(){this._bitField=4194304|this._bitField},e.prototype._unsetIsMigrated=function(){this._bitField=-4194305&this._bitField},e.prototype._isMigrated=function(){return(4194304&this._bitField)>0},e.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[5*t-5+4];return void 0===e&&this._isBound()?this._boundTo:e},e.prototype._promiseAt=function(t){return 0===t?this._promise0:this[5*t-5+3]},e.prototype._fulfillmentHandlerAt=function(t){return 0===t?this._fulfillmentHandler0:this[5*t-5+0]},e.prototype._rejectionHandlerAt=function(t){return 0===t?this._rejectionHandler0:this[5*t-5+1]},e.prototype._migrateCallbacks=function(t,r){var n=t._fulfillmentHandlerAt(r),i=t._rejectionHandlerAt(r),o=t._progressHandlerAt(r),s=t._promiseAt(r),a=t._receiverAt(r);s instanceof e&&s._setIsMigrated(),this._addCallbacks(n,i,o,s,a)},e.prototype._addCallbacks=function(t,e,r,n,i){var o=this._length();if(o>=131066&&(o=0,this._setLength(0)),0===o)this._promise0=n,void 0!==i&&(this._receiver0=i),"function"!=typeof t||this._isCarryingStackTrace()||(this._fulfillmentHandler0=t),"function"==typeof e&&(this._rejectionHandler0=e),"function"==typeof r&&(this._progressHandler0=r);else{var s=5*o-5;this[s+3]=n,this[s+4]=i,"function"==typeof t&&(this[s+0]=t),"function"==typeof e&&(this[s+1]=e),"function"==typeof r&&(this[s+2]=r)}return this._setLength(o+1),o},e.prototype._setProxyHandlers=function(t,e){var r=this._length();if(r>=131066&&(r=0,this._setLength(0)),0===r)this._promise0=e,this._receiver0=t;else{var n=5*r-5;this[n+3]=e,this[n+4]=t}this._setLength(r+1)},e.prototype._proxyPromiseArray=function(t,e){this._setProxyHandlers(t,e)},e.prototype._resolveCallback=function(t,r){if(!this._isFollowingOrFulfilledOrRejected()){if(t===this)return this._rejectCallback(n(),!1,!0);var i=f(t,this);if(!(i instanceof e))return this._fulfill(t);var o=1|(r?4:0);this._propagateFrom(i,o);var s=i._target();if(s._isPending()){for(var a=this._length(),u=0;a>u;++u)s._migrateCallbacks(this,u);this._setFollowing(),this._setLength(0),this._setFollowee(s)}else s._isFulfilled()?this._fulfillUnchecked(s._value()):this._rejectUnchecked(s._reason(),s._getCarriedStackTrace())}},e.prototype._rejectCallback=function(t,e,r){r||s.markAsOriginatingFromRejection(t);var n=s.ensureErrorObject(t),i=n===t;this._attachExtraTrace(n,e?i:!1),this._reject(t,i?void 0:n)},e.prototype._resolveFromResolver=function(t){var e=this;this._captureStackTrace(),this._pushContext();var r=!0,n=w(t)(function(t){null!==e&&(e._resolveCallback(t),e=null)},function(t){null!==e&&(e._rejectCallback(t,r),e=null)});r=!1,this._popContext(),void 0!==n&&n===b&&null!==e&&(e._rejectCallback(n.e,!0,!0),e=null)},e.prototype._settlePromiseFromHandler=function(t,e,r,i){if(!i._isRejected()){i._pushContext();var o;if(o=e!==h||this._isRejected()?w(t).call(e,r):w(t).apply(this._boundTo,r),i._popContext(),o===b||o===i||o===p){var s=o===i?n():o.e;i._rejectCallback(s,!1,!0)}else i._resolveCallback(o)}},e.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},e.prototype._followee=function(){return this._rejectionHandler0},e.prototype._setFollowee=function(t){this._rejectionHandler0=t},e.prototype._cleanValues=function(){this._cancellable()&&(this._cancellationParent=void 0)},e.prototype._propagateFrom=function(t,e){(1&e)>0&&t._cancellable()&&(this._setCancellable(),this._cancellationParent=t),(4&e)>0&&t._isBound()&&this._setBoundTo(t._boundTo)},e.prototype._fulfill=function(t){this._isFollowingOrFulfilledOrRejected()||this._fulfillUnchecked(t)},e.prototype._reject=function(t,e){this._isFollowingOrFulfilledOrRejected()||this._rejectUnchecked(t,e)},e.prototype._settlePromiseAt=function(t){var r=this._promiseAt(t),n=r instanceof e;if(n&&r._isMigrated())return r._unsetIsMigrated(),a.invoke(this._settlePromiseAt,this,t);var i=this._isFulfilled()?this._fulfillmentHandlerAt(t):this._rejectionHandlerAt(t),o=this._isCarryingStackTrace()?this._getCarriedStackTrace():void 0,s=this._settledValue,u=this._receiverAt(t);this._clearCallbackDataAtIndex(t),"function"==typeof i?n?this._settlePromiseFromHandler(i,u,s,r):i.call(u,s,r):u instanceof _?u._isResolved()||(this._isFulfilled()?u._promiseFulfilled(s,r):u._promiseRejected(s,r)):n&&(this._isFulfilled()?r._fulfill(s):r._reject(s,o)),t>=4&&4===(31&t)&&a.invokeLater(this._setLength,this,0)},e.prototype._clearCallbackDataAtIndex=function(t){if(0===t)this._isCarryingStackTrace()||(this._fulfillmentHandler0=void 0),this._rejectionHandler0=this._progressHandler0=this._receiver0=this._promise0=void 0;else{var e=5*t-5;this[e+3]=this[e+4]=this[e+0]=this[e+1]=this[e+2]=void 0}},e.prototype._isSettlePromisesQueued=function(){return-1073741824===(-1073741824&this._bitField)},e.prototype._setSettlePromisesQueued=function(){this._bitField=-1073741824|this._bitField},e.prototype._unsetSettlePromisesQueued=function(){this._bitField=1073741823&this._bitField},e.prototype._queueSettlePromises=function(){a.settlePromises(this),this._setSettlePromisesQueued()},e.prototype._fulfillUnchecked=function(t){if(t===this){var e=n();return this._attachExtraTrace(e),this._rejectUnchecked(e,void 0)}this._setFulfilled(),this._settledValue=t,this._cleanValues(),this._length()>0&&this._queueSettlePromises()},e.prototype._rejectUncheckedCheckError=function(t){var e=s.ensureErrorObject(t);this._rejectUnchecked(t,e===t?void 0:e)},e.prototype._rejectUnchecked=function(t,e){if(t===this){var r=n();return this._attachExtraTrace(r),this._rejectUnchecked(r)}return this._setRejected(),this._settledValue=t,this._cleanValues(),this._isFinal()?void a.throwLater(function(t){throw"stack"in t&&a.invokeFirst(d.unhandledRejection,void 0,t),t},void 0===e?t:e):(void 0!==e&&e!==t&&this._setCarriedStackTrace(e),void(this._length()>0?this._queueSettlePromises():this._ensurePossibleRejectionHandled()))},e.prototype._settlePromises=function(){this._unsetSettlePromisesQueued();for(var t=this._length(),e=0;t>e;e++)this._settlePromiseAt(e)},e._makeSelfResolutionError=n,t("./progress.js")(e,_),t("./method.js")(e,l,f,o),t("./bind.js")(e,l,f),t("./finally.js")(e,p,f),t("./direct_resolve.js")(e),t("./synchronous_inspection.js")(e),t("./join.js")(e,_,f,l),e.Promise=e,t("./map.js")(e,_,o,f,l),t("./cancel.js")(e),t("./using.js")(e,o,f,y),t("./generators.js")(e,o,l,f),t("./nodeify.js")(e),t("./call_get.js")(e),t("./props.js")(e,_,f,o),t("./race.js")(e,l,f,o),t("./reduce.js")(e,_,o,f,l),t("./settle.js")(e,_),t("./some.js")(e,_,o),t("./promisify.js")(e,l),t("./any.js")(e),t("./each.js")(e,l),t("./timers.js")(e,l),t("./filter.js")(e,l),s.toFastProperties(e),s.toFastProperties(e.prototype),r({a:1}),r({b:2}),r({c:3}),r(1),r(function(){}),r(void 0),r(!1),r(new e(l)),d.setBounds(a.firstLineError,s.lastLineError),e}},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){switch(t){case-2:return[];case-3:return{}}}function s(t){var n,i=this._promise=new e(r);t instanceof e&&(n=t,i._propagateFrom(n,5)),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var a=t("./util.js"),u=a.isArray;return s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function c(t,r){var s=n(this._values,this._promise);if(s instanceof e){if(s=s._target(),this._values=s,!s._isFulfilled())return s._isPending()?void s._then(c,this._reject,void 0,this,r):void this._reject(s._reason());if(s=s._value(),!u(s)){var a=new e.TypeError("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");return void this.__hardReject__(a)}}else if(!u(s))return void this._promise._reject(i("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")._reason());if(0===s.length)return void(-5===r?this._resolveEmptyArray():this._resolve(o(r)));var l=this.getActualLength(s.length);this._length=l,this._values=this.shouldCopyValues()?new Array(l):this._values;for(var h=this._promise,p=0;l>p;++p){var f=this._isResolved(),_=n(s[p],h);_ instanceof e?(_=_._target(),f?_._unsetRejectionIsUnhandled():_._isPending()?_._proxyPromiseArray(this,p):_._isFulfilled()?this._promiseFulfilled(_._value(),p):this._promiseRejected(_._reason(),p)):f||this._promiseFulfilled(_,p)}},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype.__hardReject__=s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1,!0)},s.prototype._promiseProgressed=function(t,e){this._promise._progress({index:e,value:t})},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},s.prototype._promiseRejected=function(t){this._totalResolved++,this._reject(t)},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}},{"./util.js":38}],25:[function(t,e){"use strict";function r(t){return t instanceof Error&&p.getPrototypeOf(t)===Error.prototype}function n(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=p.keys(t),i=0;i2){for(var o=arguments.length,s=new Array(o-1),u=1;o>u;++u)s[u-1]=arguments[u];t._fulfill(s)}else t._fulfill(r);t=null}}}var o,s=t("./util.js"),a=s.maybeWrapAsError,u=t("./errors.js"),c=u.TimeoutError,l=u.OperationalError,h=s.haveGetters,p=t("./es5.js"),f=/^(?:name|message|stack|cause)$/;if(o=h?function(t){this.promise=t}:function(t){this.promise=t,this.asCallback=i(t),this.callback=this.asCallback},h){var _={get:function(){return i(this.promise)}};p.defineProperty(o.prototype,"asCallback",_),p.defineProperty(o.prototype,"callback",_)}o._nodebackForPromise=i,o.prototype.toString=function(){return"[object PromiseResolver]"},o.prototype.resolve=o.prototype.fulfill=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._resolveCallback(t)},o.prototype.reject=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._rejectCallback(t)},o.prototype.progress=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._progress(t)},o.prototype.cancel=function(t){this.promise.cancel(t)},o.prototype.timeout=function(){this.reject(new c("timeout"))},o.prototype.isResolved=function(){return this.promise.isResolved()},o.prototype.toJSON=function(){return this.promise.toJSON()},e.exports=o},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(t,e){"use strict";e.exports=function(e,r){function n(t){return!b.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(e){return!1}}function o(t,e,r){var n=f.getDataPropertyOrDefault(t,e+r,j);return n?i(n):!1}function s(t,e,r){for(var n=0;ns;s+=2){var c=o[s],l=o[s+1],h=c+e;t[h]=n===E?E(c,p,c,l,e):n(l,function(){return E(c,p,c,l,e)})}return f.toFastProperties(t),t}function l(t,e){return E(t,e,void 0,t)}var h,p={},f=t("./util.js"),_=t("./promise_resolver.js")._nodebackForPromise,d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,g=t("./errors").TypeError,m="Async",j={__isPromisified__:!0},b=/^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/,w=function(t,e){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&!f.isClass(e)},k=function(t){return t.replace(/([$])/,"\\$")},E=y?h:u;e.promisify=function(t,e){if("function"!=typeof t)throw new g("fn must be a function\n\n See http://goo.gl/916lJJ\n");if(i(t))return t;var r=l(t,arguments.length<2?p:e);return f.copyDescriptors(t,r,n),r},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new g("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/9ITlV0\n");e=Object(e);var r=e.suffix;"string"!=typeof r&&(r=m);var n=e.filter;"function"!=typeof n&&(n=w);var i=e.promisifier;if("function"!=typeof i&&(i=E),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/8FZo5V\n");for(var o=f.inheritedDataKeys(t),s=0;si;++i){var o=e[i];n[i]=t[o],n[i+r]=o}this.constructor$(n)}function s(t){var r,s=n(t);return u(s)?(r=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&r._propagateFrom(s,4),r):i("cannot await properties of a non-object\n\n See http://goo.gl/OsFKC8\n")}var a=t("./util.js"),u=a.isObject,c=t("./es5.js");a.inherits(o,r),o.prototype._init=function(){this._init$(void 0,-3)},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;if(r>=this._length){for(var n={},i=this.length(),o=0,s=this.length();s>o;++o)n[this._values[o+i]]=this._values[o];this._resolve(n)}},o.prototype._promiseProgressed=function(t,e){this._promise._progress({key:this._values[e+this.length()],value:t})},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5.js":14,"./util.js":38}],28:[function(t,e){"use strict";function r(t,e,r,n,i){for(var o=0;i>o;++o)r[o+n]=t[o+e],t[o+e]=void 0}function n(t){this._capacity=t,this._length=0,this._front=0}n.prototype._willBeOverCapacity=function(t){return this._capacityp;++p){var _=t[p];(void 0!==_||p in t)&&e.cast(_)._then(l,h,void 0,c,null)}return c}var s=t("./util.js").isArray,a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util.js":38}],30:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,r,n,s){this.constructor$(t),this._promise._captureStackTrace(),this._preservedValues=s===o?[]:null,this._zerothIsAccum=void 0===n,this._gotAccum=!1,this._reducingIndex=this._zerothIsAccum?1:0,this._valuesPhase=void 0;var u=i(n,this._promise),l=!1,h=u instanceof e;h&&(u=u._target(),u._isPending()?u._proxyPromiseArray(this,-1):u._isFulfilled()?(n=u._value(),this._gotAccum=!0):(this._reject(u._reason()),l=!0)),h||this._zerothIsAccum||(this._gotAccum=!0),this._callback=r,this._accum=n,l||c.invoke(a,this,void 0)}function a(){this._init$(void 0,-5)}function u(t,e,r,i){if("function"!=typeof e)return n("fn must be a function\n\n See http://goo.gl/916lJJ\n");var o=new s(t,e,r,i);return o.promise()}var c=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj;l.inherits(s,r),s.prototype._init=function(){},s.prototype._resolveEmptyArray=function(){(this._gotAccum||this._zerothIsAccum)&&this._resolve(null!==this._preservedValues?[]:this._accum)},s.prototype._promiseFulfilled=function(t,r){var n=this._values;n[r]=t;var o,s=this.length(),a=this._preservedValues,u=null!==a,c=this._gotAccum,l=this._valuesPhase;if(!l)for(l=this._valuesPhase=new Array(s),o=0;s>o;++o)l[o]=0;if(o=l[r],0===r&&this._zerothIsAccum?(this._accum=t,this._gotAccum=c=!0,l[r]=0===o?1:2):-1===r?(this._accum=t,this._gotAccum=c=!0):0===o?l[r]=1:(l[r]=2,this._accum=t),c){for(var f,_=this._callback,d=this._promise._boundTo,v=this._reducingIndex;s>v;++v)if(o=l[v],2!==o){if(1!==o)return;if(t=n[v],this._promise._pushContext(),u?(a.push(t),f=h(_).call(d,t,v,s)):f=h(_).call(d,this._accum,t,v,s),this._promise._popContext(),f===p)return this._reject(f.e);var y=i(f,this._promise);if(y instanceof e){if(y=y._target(),y._isPending())return l[v]=4,y._proxyPromiseArray(this,v);if(!y._isFulfilled())return this._reject(y._reason());f=y._value()}this._reducingIndex=v+1,this._accum=f}else this._reducingIndex=v+1;this._resolve(u?a:this._accum)}},e.prototype.reduce=function(t,e){return u(this,t,e,null)},e.reduce=function(t,e,r,n){return u(t,e,r,n)}}},{"./async.js":2,"./util.js":38}],31:[function(t,e){"use strict";var r,n=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")};if(t("./util.js").isNode){var i=process.versions.node.split(".").map(Number);r=0===i[0]&&i[1]>10||i[0]>0?function(t){global.setImmediate(t)}:process.nextTick,r||(r="undefined"!=typeof setImmediate?setImmediate:"undefined"!=typeof setTimeout?setTimeout:n)}else"undefined"!=typeof MutationObserver?(r=function(t){var e=document.createElement("div"),r=new MutationObserver(t);return r.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},r.isStatic=!0):r="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:n;e.exports=r},{"./util.js":38}],32:[function(t,e){"use strict";e.exports=function(e,r){function n(t){this.constructor$(t)}var i=e.PromiseInspection,o=t("./util.js");o.inherits(n,r),n.prototype._promiseResolved=function(t,e){this._values[t]=e;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},n.prototype._promiseFulfilled=function(t,e){var r=new i;r._bitField=268435456,r._settledValue=t,this._promiseResolved(e,r)},n.prototype._promiseRejected=function(t,e){var r=new i;r._bitField=134217728,r._settledValue=t,this._promiseResolved(e,r)},e.settle=function(t){return new n(t).promise()},e.prototype.settle=function(){return new n(this).promise()}}},{"./util.js":38}],33:[function(t,e){"use strict";e.exports=function(e,r,n){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return n("expecting a positive integer\n\n See http://goo.gl/1wAmHx\n");var r=new i(t),o=r.promise();return r.setHowMany(e),r.init(),o}var s=t("./util.js"),a=t("./errors.js").RangeError,u=t("./errors.js").AggregateError,c=s.isArray;s.inherits(i,r),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=c(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),this._resolve(1===this.howMany()&&this._unwrap?this._values[0]:this._values))},i.prototype._promiseRejected=function(t){if(this._addRejected(t),this.howMany()>this._canPossiblyFulfill()){for(var e=new u,r=this.length();r0},e.prototype.isRejected=t.prototype._isRejected=function(){return(134217728&this._bitField)>0},e.prototype.isPending=t.prototype._isPending=function(){return 0===(402653184&this._bitField)},e.prototype.isResolved=t.prototype._isResolved=function(){return(402653184&this._bitField)>0},t.prototype.isPending=function(){return this._target()._isPending()},t.prototype.isRejected=function(){return this._target()._isRejected()},t.prototype.isFulfilled=function(){return this._target()._isFulfilled()},t.prototype.isResolved=function(){return this._target()._isResolved()},t.prototype._value=function(){return this._settledValue},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue},t.prototype.value=function(){var t=this._target();if(!t.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n");return t._settledValue},t.prototype.reason=function(){var t=this._target();if(!t.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n");return t._unsetRejectionIsUnhandled(),t._settledValue},t.PromiseInspection=e}},{}],35:[function(t,e){"use strict";e.exports=function(e,r){function n(t,n){if(c(t)){if(t instanceof e)return t;if(o(t)){var l=new e(r);return t._then(l._fulfillUnchecked,l._rejectUncheckedCheckError,l._progressUnchecked,l,null),l}var h=a.tryCatch(i)(t);if(h===u){n&&n._pushContext();var l=e.reject(h.e);return n&&n._popContext(),l}if("function"==typeof h)return s(t,h,n)}return t}function i(t){return t.then}function o(t){return l.call(t,"_promise0")}function s(t,n,i){function o(r){l&&(t===r?l._rejectCallback(e._makeSelfResolutionError(),!1,!0):l._resolveCallback(r),l=null)}function s(t){l&&(l._rejectCallback(t,p,!0),l=null)}function c(t){l&&"function"==typeof l._progress&&l._progress(t)}var l=new e(r),h=l;i&&i._pushContext(),l._captureStackTrace(),i&&i._popContext();var p=!0,f=a.tryCatch(n).call(t,o,s,c);return p=!1,l&&f===u&&(l._rejectCallback(f.e,!0,!0),l=null),h}var a=t("./util.js"),u=a.errorObj,c=a.isObject,l={}.hasOwnProperty;return n}},{"./util.js":38}],36:[function(t,e){"use strict";e.exports=function(e,r){function n(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util.js"),s=e.TimeoutError,a=function(t,e){if(t.isPending()){"string"!=typeof e&&(e="operation timed out");var r=new s(e);o.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._cancel(r)}},u=function(t){return c(+this).thenReturn(t)},c=e.delay=function(t,n){if(void 0===n){n=t,t=void 0;var i=new e(r);return setTimeout(function(){i._fulfill()},n),i}return n=+n,e.resolve(t)._then(u,null,null,n,void 0)};e.prototype.delay=function(t){return c(this,t)},e.prototype.timeout=function(t,e){t=+t;var r=this.then().cancellable();r._cancellationParent=this;var o=setTimeout(function(){a(r,e)},t);return r._then(n,i,void 0,o,void 0)}}},{"./util.js":38}],37:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){for(var r=t.length,n=0;r>n;++n){var i=t[n];if(i.isRejected())return e.reject(i.error());t[n]=i._settledValue}return t}function s(t){setTimeout(function(){throw t},0)}function a(t){var e=n(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function u(t,r){function i(){if(o>=u)return c.resolve();var l=a(t[o++]);if(l instanceof e&&l._isDisposable()){try{l=n(l._getDisposer().tryDispose(r),t.promise)}catch(h){return s(h)}if(l instanceof e)return l._then(i,s,null,null,null)}i()}var o=0,u=t.length,c=e.defer();return i(),c.promise}function c(t){var e=new v;return e._settledValue=t,e._bitField=268435456,u(this,e).thenReturn(t)}function l(t){var e=new v;return e._settledValue=t,e._bitField=134217728,u(this,e).thenThrow(t)}function h(t,e,r){this._data=t,this._promise=e,this._context=r}function p(t,e,r){this.constructor$(t,e,r)}function f(t){return h.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}var _=t("./errors.js").TypeError,d=t("./util.js").inherits,v=e.PromiseInspection;h.prototype.data=function(){return this._data},h.prototype.promise=function(){return this._promise},h.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},h.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=null!==e?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},h.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},d(p,h),p.prototype.doDispose=function(t,e){var r=this.data();return r.call(t,t,e)},e.using=function(){var t=arguments.length;if(2>t)return r("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return r("fn must be a function\n\n See http://goo.gl/916lJJ\n");t--;for(var s=new Array(t),a=0;t>a;++a){var u=arguments[a];if(h.isDisposer(u)){var p=u;u=u.promise(),u._setDisposable(p)}else{var _=n(u);_ instanceof e&&(u=_._then(f,null,null,{resources:s,index:a},void 0))}s[a]=u}var d=e.settle(s).then(o).then(function(t){d._pushContext();var e;try{e=i.apply(void 0,t)}finally{d._popContext()}return e})._then(c,l,void 0,s,void 0);return s.promise=d,d},e.prototype._setDisposable=function(t){this._bitField=262144|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(262144&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-262145&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new _}}},{"./errors.js":13,"./util.js":38}],38:[function(t,e,r){"use strict"; +function n(){try{return T.apply(this,arguments)}catch(t){return F.e=t,F}}function i(t){return T=t,n}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return!o(t)}function a(t){return o(t)?new Error(v(t)):t}function u(t,e){var r,n=t.length,i=new Array(n+1);for(r=0;n>r;++r)i[r]=t[r];return i[r]=e,i}function c(t,e,r){if(!w.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var n=Object.getOwnPropertyDescriptor(t,e);return null!=n?null==n.get&&null==n.set?n.value:r:void 0}function l(t,e,r){if(o(t))return t;var n={value:r,configurable:!0,enumerable:!1,writable:!0};return w.defineProperty(t,e,n),t}function h(t){throw t}function p(t){try{if("function"==typeof t){var e=w.names(t.prototype);return w.isES5?e.length>1:e.length>0&&!(1===e.length&&"constructor"===e[0])}return!1}catch(r){return!1}}function f(t){function e(){}e.prototype=t;for(var r=8;r--;)new e;return t}function _(t){return R.test(t)}function d(t,e,r){for(var n=new Array(t),i=0;t>i;++i)n[i]=e+i+r;return n}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){try{l(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function m(t){return t instanceof Error&&w.propertyIsWritable(t,"stack")}function j(t){return{}.toString.call(t)}function b(t,e,r){for(var n=w.names(t),i=0;it||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,r,i,a,u,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],s(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];r.apply(this,a)}else if(o(r)){for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];for(c=r.slice(),i=c.length,u=0;i>u;u++)c[u].apply(this,a)}return!0},r.prototype.addListener=function(t,e){var i;if(!n(e))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,n(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned){var i;i=s(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,i&&i>0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())}return this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),i||(i=!0,e.apply(this,arguments))}if(!n(e))throw TypeError("listener must be a function");var i=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,i,s,a;if(!n(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],s=r.length,i=-1,r===e||n(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(a=s;a-->0;)if(r[a]===e||r[a].listener&&r[a].listener===e){i=a;break}if(0>i)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],n(r))this.removeListener(t,r);else for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?n(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.listenerCount=function(t,e){var r;return r=t._events&&t._events[e]?n(t._events[e])?1:t._events[e].length:0}},{}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js new file mode 100644 index 0000000..05a6228 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js @@ -0,0 +1,21 @@ +"use strict"; +module.exports = function(Promise) { +var SomePromiseArray = Promise._SomePromiseArray; +function any(promises) { + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(1); + ret.setUnwrap(); + ret.init(); + return promise; +} + +Promise.any = function (promises) { + return any(promises); +}; + +Promise.prototype.any = function () { + return any(this); +}; + +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js new file mode 100644 index 0000000..a98955c --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js @@ -0,0 +1,55 @@ +"use strict"; +module.exports = (function(){ +var AssertionError = (function() { + function AssertionError(a) { + this.constructor$(a); + this.message = a; + this.name = "AssertionError"; + } + AssertionError.prototype = new Error(); + AssertionError.prototype.constructor = AssertionError; + AssertionError.prototype.constructor$ = Error; + return AssertionError; +})(); + +function getParams(args) { + var params = []; + for (var i = 0; i < args.length; ++i) params.push("arg" + i); + return params; +} + +function nativeAssert(callName, args, expect) { + try { + var params = getParams(args); + var constructorArgs = params; + constructorArgs.push("return " + + callName + "("+ params.join(",") + ");"); + var fn = Function.apply(null, constructorArgs); + return fn.apply(null, args); + } catch (e) { + if (!(e instanceof SyntaxError)) { + throw e; + } else { + return expect; + } + } +} + +return function assert(boolExpr, message) { + if (boolExpr === true) return; + + if (typeof boolExpr === "string" && + boolExpr.charAt(0) === "%") { + var nativeCallName = boolExpr; + var $_len = arguments.length;var args = new Array($_len - 2); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];} + if (nativeAssert(nativeCallName, args, message) === message) return; + message = (nativeCallName + " !== " + message); + } + + var ret = new AssertionError(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(ret, assert); + } + throw ret; +}; +})(); diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js new file mode 100644 index 0000000..3b5f828 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js @@ -0,0 +1,204 @@ +"use strict"; +var firstLineError; +try {throw new Error(); } catch (e) {firstLineError = e;} +var schedule = require("./schedule.js"); +var Queue = require("./queue.js"); +var util = require("./util.js"); + +function Async() { + this._isTickUsed = false; + this._lateQueue = new Queue(16); + this._normalQueue = new Queue(16); + this._trampolineEnabled = true; + var self = this; + this.drainQueues = function () { + self._drainQueues(); + }; + this._schedule = + schedule.isStatic ? schedule(this.drainQueues) : schedule; +} + +Async.prototype.disableTrampolineIfNecessary = function() { + if (util.hasDevTools) { + this._trampolineEnabled = false; + } +}; + +Async.prototype.enableTrampoline = function() { + if (!this._trampolineEnabled) { + this._trampolineEnabled = true; + this._schedule = function(fn) { + setTimeout(fn, 0); + }; + } +}; + +Async.prototype.haveItemsQueued = function () { + return this._normalQueue.length() > 0; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + } +}; + +Async.prototype._getDomain = function() {}; + +if (!false) { +if (util.isNode) { + var EventsModule = require("events"); + + var domainGetter = function() { + var domain = process.domain; + if (domain === null) return undefined; + return domain; + }; + + if (EventsModule.usingDomains) { + Async.prototype._getDomain = domainGetter; + } else { + var descriptor = + Object.getOwnPropertyDescriptor(EventsModule, "usingDomains"); + + if (descriptor) { + if (!descriptor.configurable) { + process.on("domainsActivated", function() { + Async.prototype._getDomain = domainGetter; + }); + } else { + var usingDomains = false; + Object.defineProperty(EventsModule, "usingDomains", { + configurable: false, + enumerable: true, + get: function() { + return usingDomains; + }, + set: function(value) { + if (usingDomains || !value) return; + usingDomains = true; + Async.prototype._getDomain = domainGetter; + util.toFastProperties(process); + process.emit("domainsActivated"); + } + }); + } + } + } +} +} + +function AsyncInvokeLater(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + var domain = this._getDomain(); + if (domain !== undefined) { + var fn = domain.bind(promise._settlePromises); + this._normalQueue.push(fn, promise, undefined); + } else { + this._normalQueue._pushOne(promise); + } + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 0); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + setTimeout(function() { + promise._settlePromises(); + }, 0); + } + }; +} + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = new Async(); +module.exports.firstLineError = firstLineError; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js new file mode 100644 index 0000000..d6f6da2 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js @@ -0,0 +1,73 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + this._setBoundTo(thisArg); + if (this._isPending()) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, ret._progress, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, ret._progress, ret, context); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 131072; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~131072); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.bind = function (thisArg, value) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + + if (maybePromise instanceof Promise) { + maybePromise._then(function(thisArg) { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + }, ret._reject, ret._progress, ret, null); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + } + return ret; +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js new file mode 100644 index 0000000..ed6226e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js @@ -0,0 +1,11 @@ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = require("./promise.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js new file mode 100644 index 0000000..62c166d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js @@ -0,0 +1,123 @@ +"use strict"; +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} + +module.exports = function(Promise) { +var util = require("./util.js"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!false) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; + } + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; + } + } + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + if (!false) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } + } + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; + +function namedGetter(obj) { + return obj[this]; +} +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js new file mode 100644 index 0000000..9eb40b6 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js @@ -0,0 +1,48 @@ +"use strict"; +module.exports = function(Promise) { +var errors = require("./errors.js"); +var async = require("./async.js"); +var CancellationError = errors.CancellationError; + +Promise.prototype._cancel = function (reason) { + if (!this.isCancellable()) return this; + var parent; + var promiseToReject = this; + while ((parent = promiseToReject._cancellationParent) !== undefined && + parent.isCancellable()) { + promiseToReject = parent; + } + this._unsetCancellable(); + promiseToReject._target()._rejectCallback(reason, false, true); +}; + +Promise.prototype.cancel = function (reason) { + if (!this.isCancellable()) return this; + if (reason === undefined) reason = new CancellationError(); + async.invokeLater(this._cancel, this, reason); + return this; +}; + +Promise.prototype.cancellable = function () { + if (this._cancellable()) return this; + async.enableTrampoline(); + this._setCancellable(); + this._cancellationParent = undefined; + return this; +}; + +Promise.prototype.uncancellable = function () { + var ret = this.then(); + ret._unsetCancellable(); + return ret; +}; + +Promise.prototype.fork = function (didFulfill, didReject, didProgress) { + var ret = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + + ret._setCancellable(); + ret._cancellationParent = undefined; + return ret; +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js new file mode 100644 index 0000000..6fda9e8 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js @@ -0,0 +1,492 @@ +"use strict"; +module.exports = function() { +var async = require("./async.js"); +var util = require("./util.js"); +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var warn; + +function CapturedTrace(parent) { + this._parent = parent; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.parent = function() { + return this._parent; +}; + +CapturedTrace.prototype.hasParent = function() { + return this._parent !== undefined; +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = CapturedTrace.parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = stackFramePattern.test(line) || + " (No stack trace)" === line; + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +CapturedTrace.parseStackAndMessage = function(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +}; + +CapturedTrace.formatAndLogError = function(error, title) { + if (typeof console !== "undefined") { + var message; + if (typeof error === "object" || typeof error === "function") { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof warn === "function") { + warn(message); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +}; + +CapturedTrace.unhandledRejection = function (reason) { + CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: "); +}; + +CapturedTrace.isSupported = function () { + return typeof captureStackTrace === "function"; +}; + +CapturedTrace.fireRejectionEvent = +function(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); + } + } + + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + } +}; + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj.toString(); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} +CapturedTrace.setBounds = function(firstLineError, lastLineError) { + if (!CapturedTrace.isSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow) { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); + } + }; + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; + } + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); + } + return true; + }; + } +})(); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + warn = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + warn = function(message) { + process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + warn = function(message) { + console.warn("%c" + message, "color: red"); + }; + } +} + +return CapturedTrace; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js new file mode 100644 index 0000000..040f057 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js @@ -0,0 +1,66 @@ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = require("./util.js"); +var errors = require("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = require("./es5.js").keys; +var TypeError = errors.TypeError; + +function CatchFilter(instances, callback, promise) { + this._instances = instances; + this._callback = callback; + this._promise = promise; +} + +function safePredicate(predicate, e) { + var safeObject = {}; + var retfilter = tryCatch(predicate).call(safeObject, e); + + if (retfilter === errorObj) return retfilter; + + var safeKeys = keys(safeObject); + if (safeKeys.length) { + errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); + return errorObj; + } + return retfilter; +} + +CatchFilter.prototype.doFilter = function (e) { + var cb = this._callback; + var promise = this._promise; + var boundTo = promise._boundTo; + for (var i = 0, len = this._instances.length; i < len; ++i) { + var item = this._instances[i]; + var itemIsErrorType = item === Error || + (item != null && item.prototype instanceof Error); + + if (itemIsErrorType && e instanceof item) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } else if (typeof item === "function" && !itemIsErrorType) { + var shouldHandle = safePredicate(item, e); + if (shouldHandle === errorObj) { + e = errorObj.e; + break; + } else if (shouldHandle) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } + } + } + NEXT_FILTER.e = e; + return NEXT_FILTER; +}; + +return CatchFilter; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js new file mode 100644 index 0000000..ccd7702 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js @@ -0,0 +1,38 @@ +"use strict"; +module.exports = function(Promise, CapturedTrace, isDebugging) { +var contextStack = []; +function Context() { + this._trace = new CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.pop(); + } +}; + +function createContext() { + if (isDebugging()) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} + +Promise.prototype._peekContext = peekContext; +Promise.prototype._pushContext = Context.prototype._pushContext; +Promise.prototype._popContext = Context.prototype._popContext; + +return createContext; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js new file mode 100644 index 0000000..5ac1767 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js @@ -0,0 +1,147 @@ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var async = require("./async.js"); +var Warning = require("./errors.js").Warning; +var util = require("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +if (debugging) { + async.disableTrampolineIfNecessary(); +} + +Promise.prototype._ensurePossibleRejectionHandled = function () { + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + CapturedTrace.fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._getCarriedStackTrace() || this._settledValue; + this._setUnhandledRejectionIsNotified(); + CapturedTrace.fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 524288; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~524288); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 524288) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 2097152; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~2097152); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 2097152) > 0; +}; + +Promise.prototype._setCarriedStackTrace = function (capturedTrace) { + this._bitField = this._bitField | 1048576; + this._fulfillmentHandler0 = capturedTrace; +}; + +Promise.prototype._isCarryingStackTrace = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._getCarriedStackTrace = function () { + return this._isCarryingStackTrace() + ? this._fulfillmentHandler0 + : undefined; +}; + +Promise.prototype._captureStackTrace = function () { + if (debugging) { + this._trace = new CapturedTrace(this._peekContext()); + } + return this; +}; + +Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { + if (debugging && canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = CapturedTrace.parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +}; + +Promise.prototype._warn = function(message) { + var warning = new Warning(message); + var ctx = this._peekContext(); + if (ctx) { + ctx.attachExtraTrace(warning); + } else { + var parsed = CapturedTrace.parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + CapturedTrace.formatAndLogError(warning, ""); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + unhandledRejectionHandled = typeof fn === "function" ? fn : undefined; +}; + +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && + debugging === false + ) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); + } + debugging = CapturedTrace.isSupported(); + if (debugging) { + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js new file mode 100644 index 0000000..47a9ce9 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js @@ -0,0 +1,62 @@ +"use strict"; +var util = require("./util.js"); +var isPrimitive = util.isPrimitive; +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; + +module.exports = function(Promise) { +var returner = function () { + return this; +}; +var thrower = function () { + throw this; +}; +var returnUndefined = function() {}; +var throwUndefined = function() { + throw undefined; +}; + +var wrapper = function (value, action) { + if (action === 1) { + return function () { + throw value; + }; + } else if (action === 2) { + return function () { + return value; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value === undefined) return this.then(returnUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js new file mode 100644 index 0000000..a37e22c --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js @@ -0,0 +1,12 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, null, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, null, INTERNAL); +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js new file mode 100644 index 0000000..c334bb1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js @@ -0,0 +1,111 @@ +"use strict"; +var es5 = require("./es5.js"); +var Objectfreeze = es5.freeze; +var util = require("./util.js"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} + +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; + + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + +} +inherits(OperationalError, Error); + +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js new file mode 100644 index 0000000..ea41d5a --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js @@ -0,0 +1,80 @@ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js new file mode 100644 index 0000000..ed57bf0 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js @@ -0,0 +1,12 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseMap = Promise.map; + +Promise.prototype.filter = function (fn, options) { + return PromiseMap(this, fn, options, INTERNAL); +}; + +Promise.filter = function (promises, fn, options) { + return PromiseMap(promises, fn, options, INTERNAL); +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js new file mode 100644 index 0000000..ed84a2a --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js @@ -0,0 +1,99 @@ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = require("./util.js"); +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, reasonOrValue, + promise.isFulfilled()); + } + } + + if (promise.isRejected()) { + NEXT_FILTER.e = reasonOrValue; + return NEXT_FILTER; + } else { + return reasonOrValue; + } +} + +function tapHandler(value) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo, value) + : handler(value); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, value, true); + } + } + return value; +} + +Promise.prototype._passThroughHandler = function (handler, isFinally) { + if (typeof handler !== "function") return this.then(); + + var promiseAndHandler = { + promise: this, + handler: handler + }; + + return this._then( + isFinally ? finallyHandler : tapHandler, + isFinally ? finallyHandler : undefined, undefined, + promiseAndHandler, undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThroughHandler(handler, true); +}; + +Promise.prototype.tap = function (handler) { + return this._passThroughHandler(handler, false); +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js new file mode 100644 index 0000000..4c0568d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js @@ -0,0 +1,136 @@ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = require("./errors.js"); +var TypeError = errors.TypeError; +var util = require("./util.js"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; +} + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._next(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + if (result === errorObj) { + return this._promise._rejectCallback(result.e, false, true); + } + + var value = result.value; + if (result.done === true) { + this._promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._throw( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise._then( + this._next, + this._throw, + undefined, + this, + null + ); + } +}; + +PromiseSpawn.prototype._throw = function (reason) { + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._next = function (value) { + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + spawn._generator = generator; + spawn._next(undefined); + return spawn.promise(); + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js new file mode 100644 index 0000000..cf33eb1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js @@ -0,0 +1,107 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = require("./util.js"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!false) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var caller = function(count) { + var values = []; + for (var i = 1; i <= count; ++i) values.push("holder.p" + i); + return new Function("holder", " \n\ + 'use strict'; \n\ + var callback = holder.fn; \n\ + return callback(values); \n\ + ".replace(/values/g, values.join(", "))); + }; + var thenCallbacks = []; + var callers = [undefined]; + for (var i = 1; i <= 5; ++i) { + thenCallbacks.push(thenCallback(i)); + callers.push(caller(i)); + } + + var Holder = function(total, fn) { + this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; + this.fn = fn; + this.total = total; + this.now = 0; + }; + + Holder.prototype.callers = callers; + Holder.prototype.checkFulfillment = function(promise) { + var now = this.now; + now++; + var total = this.total; + if (now >= total) { + var handler = this.callers[total]; + promise._pushContext(); + var ret = tryCatch(handler)(this); + promise._popContext(); + if (ret === errorObj) { + promise._rejectCallback(ret.e, false, true); + } else { + promise._resolveCallback(ret); + } + } else { + this.now = now; + } + }; + + var reject = function (reason) { + this._reject(reason); + }; +} +} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!false) { + if (last < 6 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var holder = new Holder(last, fn); + var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + } else if (maybePromise._isFulfilled()) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else { + ret._reject(maybePromise._reason()); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + return ret; + } + } + } + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js new file mode 100644 index 0000000..66a5b17 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js @@ -0,0 +1,131 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = require("./async.js"); +var util = require("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var PENDING = {}; +var EMPTY_ARRAY = []; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._callback = fn; + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + async.invoke(init, this, undefined); +} +util.inherits(MappingPromiseArray, PromiseArray); +function init() {this._init$(undefined, -2);} + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + if (values[index] === PENDING) { + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return; + } + if (preservedValues !== null) preservedValues[index] = value; + + var callback = this._callback; + var receiver = this._promise._boundTo; + this._promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + this._promise._popContext(); + if (ret === errorObj) return this._reject(ret.e); + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + if (limit >= 1) this._inFlight++; + values[index] = PENDING; + return maybePromise._proxyPromiseArray(this, index); + } else if (maybePromise._isFulfilled()) { + ret = maybePromise._value(); + } else { + return this._reject(maybePromise._reason()); + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + + } +}; + +MappingPromiseArray.prototype._drainQueue = function () { + var queue = this._queue; + var limit = this._limit; + var values = this._values; + while (queue.length > 0 && this._inFlight < limit) { + if (this._isResolved()) return; + var index = queue.pop(); + this._promiseFulfilled(values[index], index); + } +}; + +MappingPromiseArray.prototype._filter = function (booleans, values) { + var len = values.length; + var ret = new Array(len); + var j = 0; + for (var i = 0; i < len; ++i) { + if (booleans[i]) ret[j++] = values[i]; + } + ret.length = j; + this._resolve(ret); +}; + +MappingPromiseArray.prototype.preservedValues = function () { + return this._preservedValues; +}; + +function map(promises, fn, options, _filter) { + var limit = typeof options === "object" && options !== null + ? options.concurrency + : 0; + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter); +} + +Promise.prototype.map = function (fn, options) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + + return map(this, fn, options, null).promise(); +}; + +Promise.map = function (promises, fn, options, _filter) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + return map(promises, fn, options, _filter).promise(); +}; + + +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js new file mode 100644 index 0000000..3d3eeb1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js @@ -0,0 +1,44 @@ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = require("./util.js"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn, args, ctx) { + if (typeof fn !== "function") { + return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = util.isArray(args) + ? tryCatch(fn).apply(ctx, args) + : tryCatch(fn).call(ctx, args); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false, true); + } else { + this._resolveCallback(value, true); + } +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js new file mode 100644 index 0000000..f305b93 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise) { +var util = require("./util.js"); +var async = require("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundTo; + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var target = promise._target(); + var newReason = target._getCarriedStackTrace(); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundTo, reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = +Promise.prototype.nodeify = function (nodeback, options) { + if (typeof nodeback == "function") { + var adapter = successAdapter; + if (options !== undefined && Object(options).spread) { + adapter = spreadAdapter; + } + this._then( + adapter, + errorAdapter, + undefined, + this, + nodeback + ); + } + return this; +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js new file mode 100644 index 0000000..2e3e95e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js @@ -0,0 +1,76 @@ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = require("./util.js"); +var async = require("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +Promise.prototype.progressed = function (handler) { + return this._then(undefined, undefined, handler, undefined, undefined); +}; + +Promise.prototype._progress = function (progressValue) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._target()._progressUnchecked(progressValue); + +}; + +Promise.prototype._progressHandlerAt = function (index) { + return index === 0 + ? this._progressHandler0 + : this[(index << 2) + index - 5 + 2]; +}; + +Promise.prototype._doProgressWith = function (progression) { + var progressValue = progression.value; + var handler = progression.handler; + var promise = progression.promise; + var receiver = progression.receiver; + + var ret = tryCatch(handler).call(receiver, progressValue); + if (ret === errorObj) { + if (ret.e != null && + ret.e.name !== "StopProgressPropagation") { + var trace = util.canAttachTrace(ret.e) + ? ret.e : new Error(util.toString(ret.e)); + promise._attachExtraTrace(trace); + promise._progress(ret.e); + } + } else if (ret instanceof Promise) { + ret._then(promise._progress, null, null, promise, undefined); + } else { + promise._progress(ret); + } +}; + + +Promise.prototype._progressUnchecked = function (progressValue) { + var len = this._length(); + var progress = this._progress; + for (var i = 0; i < len; i++) { + var handler = this._progressHandlerAt(i); + var promise = this._promiseAt(i); + if (!(promise instanceof Promise)) { + var receiver = this._receiverAt(i); + if (typeof handler === "function") { + handler.call(receiver, progressValue, promise); + } else if (receiver instanceof PromiseArray && + !receiver._isResolved()) { + receiver._promiseProgressed(progressValue, promise); + } + continue; + } + + if (typeof handler === "function") { + async.invoke(this._doProgressWith, this, { + handler: handler, + promise: promise, + receiver: this._receiverAt(i), + value: progressValue + }); + } else { + async.invoke(progress, promise, progressValue); + } + } +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js new file mode 100644 index 0000000..f80d247 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js @@ -0,0 +1,700 @@ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); +}; +var reflect = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +var util = require("./util.js"); +var async = require("./async.js"); +var errors = require("./errors.js"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {e: null}; +var tryConvertToPromise = require("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + require("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = require("./captured_trace.js")(); +var isDebugging = require("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + require("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = require("./promise_resolver.js"); +var nodebackForPromise = PromiseResolver._nodebackForPromise; +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function Promise(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); + } + if (this.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._progressHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._settledValue = undefined; + if (resolver !== INTERNAL) this._resolveFromResolver(resolver); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (typeof item === "function") { + catchInstances[j++] = item; + } else { + return Promise.reject( + new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); + } + } + catchInstances.length = j; + fn = arguments[i]; + var catchFilter = new CatchFilter(catchInstances, fn, this); + return this._then(undefined, catchFilter.doFilter, undefined, + catchFilter, undefined); + } + return this._then(undefined, fn, undefined, undefined, undefined); +}; + +Promise.prototype.reflect = function () { + return this._then(reflect, reflect, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject, didProgress) { + if (isDebugging() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, didProgress, + undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject, didProgress) { + var promise = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (didFulfill, didReject) { + return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); +}; + +Promise.prototype.isCancellable = function () { + return !this.isResolved() && + this._cancellable(); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = function(fn) { + var ret = new Promise(INTERNAL); + var result = tryCatch(fn)(nodebackForPromise(ret)); + if (result === errorObj) { + ret._rejectCallback(result.e, true, true); + } + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.defer = Promise.pending = function () { + var promise = new Promise(INTERNAL); + return new PromiseResolver(promise); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + var val = ret; + ret = new Promise(INTERNAL); + ret._fulfillUnchecked(val); + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + didProgress, + receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var ret = haveInternalData ? internalData : new Promise(INTERNAL); + + if (!haveInternalData) { + ret._propagateFrom(this, 4 | 1); + ret._captureStackTrace(); + } + + var target = this._target(); + if (target !== this) { + if (receiver === undefined) receiver = this._boundTo; + if (!haveInternalData) ret._setIsMigrated(); + } + + var callbackIndex = + target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); + + if (target._isResolved() && !target._isSettlePromisesQueued()) { + async.invoke( + target._settlePromiseAtPostResolution, target, callbackIndex); + } + + return ret; +}; + +Promise.prototype._settlePromiseAtPostResolution = function (index) { + if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); + this._settlePromiseAt(index); +}; + +Promise.prototype._length = function () { + return this._bitField & 131071; +}; + +Promise.prototype._isFollowingOrFulfilledOrRejected = function () { + return (this._bitField & 939524096) > 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 536870912) === 536870912; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -131072) | + (len & 131071); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 536870912; +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 33554432; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 33554432) > 0; +}; + +Promise.prototype._cancellable = function () { + return (this._bitField & 67108864) > 0; +}; + +Promise.prototype._setCancellable = function () { + this._bitField = this._bitField | 67108864; +}; + +Promise.prototype._unsetCancellable = function () { + this._bitField = this._bitField & (~67108864); +}; + +Promise.prototype._setIsMigrated = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._unsetIsMigrated = function () { + this._bitField = this._bitField & (~4194304); +}; + +Promise.prototype._isMigrated = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 + ? this._receiver0 + : this[ + index * 5 - 5 + 4]; + if (ret === undefined && this._isBound()) { + return this._boundTo; + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return index === 0 + ? this._promise0 + : this[index * 5 - 5 + 3]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return index === 0 + ? this._fulfillmentHandler0 + : this[index * 5 - 5 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return index === 0 + ? this._rejectionHandler0 + : this[index * 5 - 5 + 1]; +}; + +Promise.prototype._migrateCallbacks = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var progress = follower._progressHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (promise instanceof Promise) promise._setIsMigrated(); + this._addCallbacks(fulfill, reject, progress, promise, receiver); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + progress, + promise, + receiver +) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + if (receiver !== undefined) this._receiver0 = receiver; + if (typeof fulfill === "function" && !this._isCarryingStackTrace()) + this._fulfillmentHandler0 = fulfill; + if (typeof reject === "function") this._rejectionHandler0 = reject; + if (typeof progress === "function") this._progressHandler0 = progress; + } else { + var base = index * 5 - 5; + this[base + 3] = promise; + this[base + 4] = receiver; + if (typeof fulfill === "function") + this[base + 0] = fulfill; + if (typeof reject === "function") + this[base + 1] = reject; + if (typeof progress === "function") + this[base + 2] = progress; + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + if (index === 0) { + this._promise0 = promiseSlotValue; + this._receiver0 = receiver; + } else { + var base = index * 5 - 5; + this[base + 3] = promiseSlotValue; + this[base + 4] = receiver; + } + this._setLength(index + 1); +}; + +Promise.prototype._proxyPromiseArray = function (promiseArray, index) { + this._setProxyHandlers(promiseArray, index); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (this._isFollowingOrFulfilledOrRejected()) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false, true); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + var propagationFlags = 1 | (shouldBind ? 4 : 0); + this._propagateFrom(maybePromise, propagationFlags); + var promise = maybePromise._target(); + if (promise._isPending()) { + var len = this._length(); + for (var i = 0; i < len; ++i) { + promise._migrateCallbacks(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (promise._isFulfilled()) { + this._fulfillUnchecked(promise._value()); + } else { + this._rejectUnchecked(promise._reason(), + promise._getCarriedStackTrace()); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { + if (!shouldNotMarkOriginatingFromRejection) { + util.markAsOriginatingFromRejection(reason); + } + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, hasStack ? undefined : trace); +}; + +Promise.prototype._resolveFromResolver = function (resolver) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = tryCatch(resolver)(function(value) { + if (promise === null) return; + promise._resolveCallback(value); + promise = null; + }, function (reason) { + if (promise === null) return; + promise._rejectCallback(reason, synchronous); + promise = null; + }); + synchronous = false; + this._popContext(); + + if (r !== undefined && r === errorObj && promise !== null) { + promise._rejectCallback(r.e, true, true); + promise = null; + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + if (promise._isRejected()) return; + promise._pushContext(); + var x; + if (receiver === APPLY && !this._isRejected()) { + x = tryCatch(handler).apply(this._boundTo, value); + } else { + x = tryCatch(handler).call(receiver, value); + } + promise._popContext(); + + if (x === errorObj || x === promise || x === NEXT_FILTER) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false, true); + } else { + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._cleanValues = function () { + if (this._cancellable()) { + this._cancellationParent = undefined; + } +}; + +Promise.prototype._propagateFrom = function (parent, flags) { + if ((flags & 1) > 0 && parent._cancellable()) { + this._setCancellable(); + this._cancellationParent = parent; + } + if ((flags & 4) > 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +}; + +Promise.prototype._fulfill = function (value) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._fulfillUnchecked(value); +}; + +Promise.prototype._reject = function (reason, carriedStackTrace) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._rejectUnchecked(reason, carriedStackTrace); +}; + +Promise.prototype._settlePromiseAt = function (index) { + var promise = this._promiseAt(index); + var isPromise = promise instanceof Promise; + + if (isPromise && promise._isMigrated()) { + promise._unsetIsMigrated(); + return async.invoke(this._settlePromiseAt, this, index); + } + var handler = this._isFulfilled() + ? this._fulfillmentHandlerAt(index) + : this._rejectionHandlerAt(index); + + var carriedStackTrace = + this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; + var value = this._settledValue; + var receiver = this._receiverAt(index); + + + this._clearCallbackDataAtIndex(index); + + if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof PromiseArray) { + if (!receiver._isResolved()) { + if (this._isFulfilled()) { + receiver._promiseFulfilled(value, promise); + } + else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (this._isFulfilled()) { + promise._fulfill(value); + } else { + promise._reject(value, carriedStackTrace); + } + } + + if (index >= 4 && (index & 31) === 4) + async.invokeLater(this._setLength, this, 0); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + if (index === 0) { + if (!this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = undefined; + } + this._rejectionHandler0 = + this._progressHandler0 = + this._receiver0 = + this._promise0 = undefined; + } else { + var base = index * 5 - 5; + this[base + 3] = + this[base + 4] = + this[base + 0] = + this[base + 1] = + this[base + 2] = undefined; + } +}; + +Promise.prototype._isSettlePromisesQueued = function () { + return (this._bitField & + -1073741824) === -1073741824; +}; + +Promise.prototype._setSettlePromisesQueued = function () { + this._bitField = this._bitField | -1073741824; +}; + +Promise.prototype._unsetSettlePromisesQueued = function () { + this._bitField = this._bitField & (~-1073741824); +}; + +Promise.prototype._queueSettlePromises = function() { + async.settlePromises(this); + this._setSettlePromisesQueued(); +}; + +Promise.prototype._fulfillUnchecked = function (value) { + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err, undefined); + } + this._setFulfilled(); + this._settledValue = value; + this._cleanValues(); + + if (this._length() > 0) { + this._queueSettlePromises(); + } +}; + +Promise.prototype._rejectUncheckedCheckError = function (reason) { + var trace = util.ensureErrorObject(reason); + this._rejectUnchecked(reason, trace === reason ? undefined : trace); +}; + +Promise.prototype._rejectUnchecked = function (reason, trace) { + if (reason === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err); + } + this._setRejected(); + this._settledValue = reason; + this._cleanValues(); + + if (this._isFinal()) { + async.throwLater(function(e) { + if ("stack" in e) { + async.invokeFirst( + CapturedTrace.unhandledRejection, undefined, e); + } + throw e; + }, trace === undefined ? reason : trace); + return; + } + + if (trace !== undefined && trace !== reason) { + this._setCarriedStackTrace(trace); + } + + if (this._length() > 0) { + this._queueSettlePromises(); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._settlePromises = function () { + this._unsetSettlePromisesQueued(); + var len = this._length(); + for (var i = 0; i < len; i++) { + this._settlePromiseAt(i); + } +}; + +Promise._makeSelfResolutionError = makeSelfResolutionError; +require("./progress.js")(Promise, PromiseArray); +require("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +require("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +require("./direct_resolve.js")(Promise); +require("./synchronous_inspection.js")(Promise); +require("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./cancel.js')(Promise); +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +require('./nodeify.js')(Promise); +require('./call_get.js')(Promise); +require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./settle.js')(Promise, PromiseArray); +require('./some.js')(Promise, PromiseArray, apiRejection); +require('./promisify.js')(Promise, INTERNAL); +require('./any.js')(Promise); +require('./each.js')(Promise, INTERNAL); +require('./timers.js')(Promise, INTERNAL); +require('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._progressHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + p._settledValue = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + CapturedTrace.setBounds(async.firstLineError, util.lastLineError); + return Promise; + +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js new file mode 100644 index 0000000..6dac866 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js @@ -0,0 +1,142 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = require("./util.js"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + var parent; + if (values instanceof Promise) { + parent = values; + promise._propagateFrom(parent, 1 | 4); + } + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + this._values = values; + if (values._isFulfilled()) { + values = values._value(); + if (!isArray(values)) { + var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + this.__hardReject__(err); + return; + } + } else if (values._isPending()) { + values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + return; + } else { + this._reject(values._reason()); + return; + } + } else if (!isArray(values)) { + this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var promise = this._promise; + for (var i = 0; i < len; ++i) { + var isResolved = this._isResolved(); + var maybePromise = tryConvertToPromise(values[i], promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (isResolved) { + maybePromise._unsetRejectionIsUnhandled(); + } else if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, i); + } else if (maybePromise._isFulfilled()) { + this._promiseFulfilled(maybePromise._value(), i); + } else { + this._promiseRejected(maybePromise._reason(), i); + } + } else if (!isResolved) { + this._promiseFulfilled(maybePromise, i); + } + } +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype.__hardReject__ = +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false, true); +}; + +PromiseArray.prototype._promiseProgressed = function (progressValue, index) { + this._promise._progress({ + index: index, + value: progressValue + }); +}; + + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +PromiseArray.prototype._promiseRejected = function (reason, index) { + this._totalResolved++; + this._reject(reason); +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js new file mode 100644 index 0000000..b180a32 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js @@ -0,0 +1,123 @@ +"use strict"; +var util = require("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = require("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = require("./es5.js"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise) { + return function(err, value) { + if (promise === null) return; + + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (arguments.length > 2) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + promise._fulfill(args); + } else { + promise._fulfill(value); + } + + promise = null; + }; +} + + +var PromiseResolver; +if (!haveGetters) { + PromiseResolver = function (promise) { + this.promise = promise; + this.asCallback = nodebackForPromise(promise); + this.callback = this.asCallback; + }; +} +else { + PromiseResolver = function (promise) { + this.promise = promise; + }; +} +if (haveGetters) { + var prop = { + get: function() { + return nodebackForPromise(this.promise); + } + }; + es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); + es5.defineProperty(PromiseResolver.prototype, "callback", prop); +} + +PromiseResolver._nodebackForPromise = nodebackForPromise; + +PromiseResolver.prototype.toString = function () { + return "[object PromiseResolver]"; +}; + +PromiseResolver.prototype.resolve = +PromiseResolver.prototype.fulfill = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._resolveCallback(value); +}; + +PromiseResolver.prototype.reject = function (reason) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._rejectCallback(reason); +}; + +PromiseResolver.prototype.progress = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._progress(value); +}; + +PromiseResolver.prototype.cancel = function (err) { + this.promise.cancel(err); +}; + +PromiseResolver.prototype.timeout = function () { + this.reject(new TimeoutError("timeout")); +}; + +PromiseResolver.prototype.isResolved = function () { + return this.promise.isResolved(); +}; + +PromiseResolver.prototype.toJSON = function () { + return this.promise.toJSON(); +}; + +module.exports = PromiseResolver; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js new file mode 100644 index 0000000..0355344 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js @@ -0,0 +1,291 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = require("./util.js"); +var nodebackForPromise = require("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = require("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyPropsPattern = + /^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/; +var defaultFilter = function(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} + +function isPromisified(fn) { + try { + return fn.__isPromisified__ === true; + } + catch (e) { + return false; + } +} + +function hasPromisified(obj, key, suffix) { + var val = util.getDataPropertyOrDefault(obj, key + suffix, + defaultPromisified); + return val ? isPromisified(val) : false; +} +function checkValid(ret, suffix, suffixRegexp) { + for (var i = 0; i < ret.length; i += 2) { + var key = ret[i]; + if (suffixRegexp.test(key)) { + var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); + for (var j = 0; j < ret.length; j += 2) { + if (ret[j] === keyWithoutAsyncSuffix) { + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a" + .replace("%s", suffix)); + } + } + } + } +} + +function promisifiableMethods(obj, suffix, suffixRegexp, filter) { + var keys = util.inheritedDataKeys(obj); + var ret = []; + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var value = obj[key]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} + +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!false) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { + var ret = [likelyArgumentCount]; + var min = Math.max(0, likelyArgumentCount - 1 - 3); + for(var i = likelyArgumentCount - 1; i >= min; --i) { + ret.push(i); + } + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { + ret.push(i); + } + return ret; +}; + +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; + +var parameterCount = function(fn) { + if (typeof fn.length === "number") { + return Math.max(Math.min(fn.length, 1023 + 1), 0); + } + return 0; +}; + +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn) { + var newParameterCount = Math.max(0, parameterCount(fn) - 1); + var argumentOrder = switchCaseArgumentOrder(newParameterCount); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; + + function generateCallForArgumentCount(count) { + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; + } + return ret.replace("{{args}}", args).replace(", ", comma); + } + + function generateArgumentSwitchCase() { + var ret = ""; + for (var i = 0; i < argumentOrder.length; ++i) { + ret += "case " + argumentOrder[i] +":" + + generateCallForArgumentCount(argumentOrder[i]); + } + + ret += " \n\ + default: \n\ + var args = new Array(len + 1); \n\ + var i = 0; \n\ + for (var i = 0; i < len; ++i) { \n\ + args[i] = arguments[i]; \n\ + } \n\ + args[i] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); + return ret; + } + + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "INTERNAL","'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + return promise; \n\ + }; \n\ + ret.__isPromisified__ = true; \n\ + return ret; \n\ + " + .replace("Parameters", parameterDeclaration(newParameterCount)) + .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode))( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + INTERNAL + ); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } + function promisified() { + var _receiver = receiver; + if (receiver === THIS) _receiver = this; + var promise = new Promise(INTERNAL); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; + var fn = nodebackForPromise(promise); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + return promise; + } + promisified.__isPromisified__ = true; + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier) { + var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); + var methods = + promisifiableMethods(obj, suffix, suffixRegexp, filter); + + for (var i = 0, len = methods.length; i < len; i+= 2) { + var key = methods[i]; + var fn = methods[i+1]; + var promisifiedKey = key + suffix; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver) { + return makeNodePromisified(callback, receiver, undefined, callback); +} + +Promise.promisify = function (fn, receiver) { + if (typeof fn !== "function") { + throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + if (isPromisified(fn)) { + return fn; + } + var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + util.copyDescriptors(fn, ret, propsFilter); + return ret; +}; + +Promise.promisifyAll = function (target, options) { + if (typeof target !== "function" && typeof target !== "object") { + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a"); + } + options = Object(options); + var suffix = options.suffix; + if (typeof suffix !== "string") suffix = defaultSuffix; + var filter = options.filter; + if (typeof filter !== "function") filter = defaultFilter; + var promisifier = options.promisifier; + if (typeof promisifier !== "function") promisifier = makeNodePromisified; + + if (!util.isIdentifier(suffix)) { + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); + } + + var keys = util.inheritedDataKeys(target); + for (var i = 0; i < keys.length; ++i) { + var value = target[keys[i]]; + if (keys[i] !== "constructor" && + util.isClass(value)) { + promisifyAll(value.prototype, suffix, filter, promisifier); + promisifyAll(value, suffix, filter, promisifier); + } + } + + return promisifyAll(target, suffix, filter, promisifier); +}; +}; + diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js new file mode 100644 index 0000000..d6f9e64 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js @@ -0,0 +1,79 @@ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = require("./util.js"); +var isObject = util.isObject; +var es5 = require("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; +}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val = {}; + var keyOffset = this.length(); + for (var i = 0, len = this.length(); i < len; ++i) { + val[this._values[i + keyOffset]] = this._values[i]; + } + this._resolve(val); + } +}; + +PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { + this._promise._progress({ + key: this._values[index + this.length()], + value: value + }); +}; + +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; + +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); + + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } + + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 4); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js new file mode 100644 index 0000000..84d57d5 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js @@ -0,0 +1,90 @@ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js new file mode 100644 index 0000000..30e7bb0 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js @@ -0,0 +1,47 @@ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = require("./util.js").isArray; + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else if (!isArray(promises)) { + return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 4 | 1); + } + var fulfill = ret._fulfill; + var reject = ret._reject; + for (var i = 0, len = promises.length; i < len; ++i) { + var val = promises[i]; + + if (val === undefined && !(i in promises)) { + continue; + } + + Promise.cast(val)._then(fulfill, reject, undefined, ret, null); + } + return ret; +} + +Promise.race = function (promises) { + return race(promises, undefined); +}; + +Promise.prototype.race = function () { + return race(this, undefined); +}; + +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js new file mode 100644 index 0000000..3192220 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js @@ -0,0 +1,146 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = require("./async.js"); +var util = require("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +function ReductionPromiseArray(promises, fn, accum, _each) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._preservedValues = _each === INTERNAL ? [] : null; + this._zerothIsAccum = (accum === undefined); + this._gotAccum = false; + this._reducingIndex = (this._zerothIsAccum ? 1 : 0); + this._valuesPhase = undefined; + var maybePromise = tryConvertToPromise(accum, this._promise); + var rejected = false; + var isPromise = maybePromise instanceof Promise; + if (isPromise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, -1); + } else if (maybePromise._isFulfilled()) { + accum = maybePromise._value(); + this._gotAccum = true; + } else { + this._reject(maybePromise._reason()); + rejected = true; + } + } + if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; + this._callback = fn; + this._accum = accum; + if (!rejected) async.invoke(init, this, undefined); +} +function init() { + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._init = function () {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); + } +}; + +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + values[index] = value; + var length = this.length(); + var preservedValues = this._preservedValues; + var isEach = preservedValues !== null; + var gotAccum = this._gotAccum; + var valuesPhase = this._valuesPhase; + var valuesPhaseIndex; + if (!valuesPhase) { + valuesPhase = this._valuesPhase = new Array(length); + for (valuesPhaseIndex=0; valuesPhaseIndex 10) || (version[0] > 0) + ? function(fn) { global.setImmediate(fn); } : process.nextTick; + + if (!schedule) { + if (typeof setImmediate !== "undefined") { + schedule = setImmediate; + } else if (typeof setTimeout !== "undefined") { + schedule = setTimeout; + } else { + schedule = noAsyncScheduler; + } + } +} else if (typeof MutationObserver !== "undefined") { + schedule = function(fn) { + var div = document.createElement("div"); + var observer = new MutationObserver(fn); + observer.observe(div, {attributes: true}); + return function() { div.classList.toggle("foo"); }; + }; + schedule.isStatic = true; +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js new file mode 100644 index 0000000..f9299c2 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js @@ -0,0 +1,40 @@ +"use strict"; +module.exports = + function(Promise, PromiseArray) { +var PromiseInspection = Promise.PromiseInspection; +var util = require("./util.js"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 268435456; + ret._settledValue = value; + this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 134217728; + ret._settledValue = reason; + this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return new SettledPromiseArray(this).promise(); +}; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js new file mode 100644 index 0000000..f3968cf --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js @@ -0,0 +1,125 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = require("./util.js"); +var RangeError = require("./errors.js").RangeError; +var AggregateError = require("./errors.js").AggregateError; +var isArray = util.isArray; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + this._addFulfilled(value); + if (this._fulfilled() === this.howMany()) { + this._values.length = this.howMany(); + if (this.howMany() === 1 && this._unwrap) { + this._resolve(this._values[0]); + } else { + this._resolve(this._values); + } + } + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + e.push(this._values[i]); + } + this._reject(e); + } +}; + +SomePromiseArray.prototype._fulfilled = function () { + return this._totalResolved; +}; + +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); +}; + +SomePromiseArray.prototype._addRejected = function (reason) { + this._values.push(reason); +}; + +SomePromiseArray.prototype._addFulfilled = function (value) { + this._values[this._totalResolved++] = value; +}; + +SomePromiseArray.prototype._canPossiblyFulfill = function () { + return this.length() - this._rejected(); +}; + +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); +}; + +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; + +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} + +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; + +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; + +Promise._SomePromiseArray = SomePromiseArray; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js new file mode 100644 index 0000000..7aac149 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js @@ -0,0 +1,94 @@ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValue = promise._settledValue; + } + else { + this._bitField = 0; + this._settledValue = undefined; + } +} + +PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.isFulfilled = +Promise.prototype._isFulfilled = function () { + return (this._bitField & 268435456) > 0; +}; + +PromiseInspection.prototype.isRejected = +Promise.prototype._isRejected = function () { + return (this._bitField & 134217728) > 0; +}; + +PromiseInspection.prototype.isPending = +Promise.prototype._isPending = function () { + return (this._bitField & 402653184) === 0; +}; + +PromiseInspection.prototype.isResolved = +Promise.prototype._isResolved = function () { + return (this._bitField & 402653184) > 0; +}; + +Promise.prototype.isPending = function() { + return this._target()._isPending(); +}; + +Promise.prototype.isRejected = function() { + return this._target()._isRejected(); +}; + +Promise.prototype.isFulfilled = function() { + return this._target()._isFulfilled(); +}; + +Promise.prototype.isResolved = function() { + return this._target()._isResolved(); +}; + +Promise.prototype._value = function() { + return this._settledValue; +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue; +}; + +Promise.prototype.value = function() { + var target = this._target(); + if (!target.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return target._settledValue; +}; + +Promise.prototype.reason = function() { + var target = this._target(); + if (!target.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + target._unsetRejectionIsUnhandled(); + return target._settledValue; +}; + + +Promise.PromiseInspection = PromiseInspection; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js new file mode 100644 index 0000000..c858f86 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js @@ -0,0 +1,89 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util.js"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) { + return obj; + } + else if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfillUnchecked, + ret._rejectUncheckedCheckError, + ret._progressUnchecked, + ret, + null + ); + return ret; + } + var then = util.tryCatch(getThen)(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + return doThenable(obj, then, context); + } + } + return obj; +} + +function getThen(obj) { + return obj.then; +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, + resolveFromThenable, + rejectFromThenable, + progressFromThenable); + synchronous = false; + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolveFromThenable(value) { + if (!promise) return; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + promise._resolveCallback(value); + } + promise = null; + } + + function rejectFromThenable(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + + function progressFromThenable(value) { + if (!promise) return; + if (typeof promise._progress === "function") { + promise._progress(value); + } + } + return ret; +} + +return tryConvertToPromise; +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js new file mode 100644 index 0000000..ecf1b57 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + if (typeof message !== "string") { + message = "operation timed out"; + } + var err = new TimeoutError(message); + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._cancel(err); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (value, ms) { + if (ms === undefined) { + ms = value; + value = undefined; + var ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, ms); + return ret; + } + ms = +ms; + return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); +}; + +Promise.prototype.delay = function (ms) { + return delay(this, ms); +}; + +function successClear(value) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + return value; +} + +function failureClear(reason) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret = this.then().cancellable(); + ret._cancellationParent = this; + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js new file mode 100644 index 0000000..4038711 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js @@ -0,0 +1,202 @@ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = require("./errors.js").TypeError; + var inherits = require("./util.js").inherits; + var PromiseInspection = Promise.PromiseInspection; + + function inspectionMapper(inspections) { + var len = inspections.length; + for (var i = 0; i < len; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + return Promise.reject(inspection.error()); + } + inspections[i] = inspection._settledValue; + } + return inspections; + } + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + if (maybePromise !== thenable && + typeof thenable._isDisposable === "function" && + typeof thenable._getDisposer === "function" && + thenable._isDisposable()) { + maybePromise._setDisposable(thenable._getDisposer()); + } + return maybePromise; + } + function dispose(resources, inspection) { + var i = 0; + var len = resources.length; + var ret = Promise.defer(); + function iterator() { + if (i >= len) return ret.resolve(); + var maybePromise = castPreservingDisposable(resources[i++]); + if (maybePromise instanceof Promise && + maybePromise._isDisposable()) { + try { + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); + } catch (e) { + return thrower(e); + } + if (maybePromise instanceof Promise) { + return maybePromise._then(iterator, thrower, + null, null, null); + } + } + iterator(); + } + iterator(); + return ret.promise; + } + + function disposerSuccess(value) { + var inspection = new PromiseInspection(); + inspection._settledValue = value; + inspection._bitField = 268435456; + return dispose(this, inspection).thenReturn(value); + } + + function disposerFail(reason) { + var inspection = new PromiseInspection(); + inspection._settledValue = reason; + inspection._bitField = 134217728; + return dispose(this, inspection).thenThrow(reason); + } + + function Disposer(data, promise, context) { + this._data = data; + this._promise = promise; + this._context = context; + } + + Disposer.prototype.data = function () { + return this._data; + }; + + Disposer.prototype.promise = function () { + return this._promise; + }; + + Disposer.prototype.resource = function () { + if (this.promise().isFulfilled()) { + return this.promise().value(); + } + return null; + }; + + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== null + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; + + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); + }; + + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); + + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); + }; + + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); + } + return value; + } + + Promise.using = function () { + var len = arguments.length; + if (len < 2) return apiRejection( + "you must pass at least 2 arguments to Promise.using"); + var fn = arguments[len - 1]; + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } + } + resources[i] = resource; + } + + var promise = Promise.settle(resources) + .then(inspectionMapper) + .then(function(vals) { + promise._pushContext(); + var ret; + try { + ret = fn.apply(undefined, vals); + } finally { + promise._popContext(); + } + return ret; + }) + ._then( + disposerSuccess, disposerFail, undefined, resources, undefined); + resources.promise = promise; + return promise; + }; + + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 262144; + this._disposer = disposer; + }; + + Promise.prototype._isDisposable = function () { + return (this._bitField & 262144) > 0; + }; + + Promise.prototype._getDisposer = function () { + return this._disposer; + }; + + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~262144); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); + }; + +}; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js new file mode 100644 index 0000000..fbee5de --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js @@ -0,0 +1,280 @@ +"use strict"; +var es5 = require("./es5.js"); +var canEvaluate = typeof navigator == "undefined"; +var haveGetters = (function(){ + try { + var o = {}; + es5.defineProperty(o, "f", { + get: function () { + return 3; + } + }); + return o.f === 3; + } + catch (e) { + return false; + } + +})(); + +var errorObj = {e: {}}; +var tryCatchTarget; +function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } + } + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return !isPrimitive(value); +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); +} + +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; +} + +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} + +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; +} + + +var wrapsPrimitiveReceiver = (function() { + return this !== "string"; +}).call("string"); + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + if (es5.isES5) { + var oProto = Object.prototype; + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && obj !== oProto) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function f() {} + f.prototype = obj; + var l = 8; + while (l--) new f(); + return obj; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + haveGetters: haveGetters, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" +}; +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json new file mode 100644 index 0000000..4371fc3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json @@ -0,0 +1,97 @@ +{ + "name": "bluebird", + "description": "Full featured Promises/A+ implementation with exceptionally good performance", + "version": "2.9.26", + "keywords": [ + "promise", + "performance", + "promises", + "promises-a", + "promises-aplus", + "async", + "await", + "deferred", + "deferreds", + "future", + "flow control", + "dsl", + "fluent interface" + ], + "scripts": { + "lint": "node scripts/jshint.js", + "test": "node tools/test.js", + "istanbul": "istanbul", + "prepublish": "node tools/build.js --no-debug --main --zalgo --browser --minify" + }, + "homepage": "https://github.com/petkaantonov/bluebird", + "repository": { + "type": "git", + "url": "git://github.com/petkaantonov/bluebird.git" + }, + "bugs": { + "url": "http://github.com/petkaantonov/bluebird/issues" + }, + "license": "MIT", + "author": { + "name": "Petka Antonov", + "email": "petka_antonov@hotmail.com", + "url": "http://github.com/petkaantonov/" + }, + "devDependencies": { + "acorn": "~0.6.0", + "baconjs": "^0.7.43", + "bluebird": "^2.9.2", + "body-parser": "^1.10.2", + "browserify": "^8.1.1", + "cli-table": "~0.3.1", + "co": "^4.2.0", + "cross-spawn": "^0.2.3", + "glob": "^4.3.2", + "grunt-saucelabs": "~8.4.1", + "highland": "^2.3.0", + "istanbul": "^0.3.5", + "jshint": "^2.6.0", + "jshint-stylish": "~0.2.0", + "mkdirp": "~0.5.0", + "mocha": "~2.1", + "open": "~0.0.5", + "optimist": "~0.6.1", + "rimraf": "~2.2.6", + "rx": "^2.3.25", + "serve-static": "^1.7.1", + "sinon": "~1.7.3", + "uglify-js": "~2.4.16" + }, + "main": "./js/main/bluebird.js", + "browser": "./js/browser/bluebird.js", + "files": [ + "js/browser", + "js/main", + "js/zalgo", + "LICENSE", + "zalgo.js" + ], + "gitHead": "c6604d44f219af9da683f6e28d818008fa374af2", + "_id": "bluebird@2.9.26", + "_shasum": "362772ea4d09f556a4b9f3b64c2fd136e87e3a55", + "_from": "bluebird@2.9.26", + "_npmVersion": "2.7.1", + "_nodeVersion": "1.6.2", + "_npmUser": { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + }, + "maintainers": [ + { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + } + ], + "dist": { + "shasum": "362772ea4d09f556a4b9f3b64c2fd136e87e3a55", + "tarball": "http://registry.npmjs.org/bluebird/-/bluebird-2.9.26.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.9.26.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/.jshintrc b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md new file mode 100644 index 0000000..854c971 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md @@ -0,0 +1,195 @@ + +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 +================== + + * 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/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile new file mode 100644 index 0000000..5cf4a59 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile @@ -0,0 +1,36 @@ + +# 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 dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +distclean: clean + @rm -rf node_modules + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean distclean diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md new file mode 100644 index 0000000..b4f45e3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md @@ -0,0 +1,188 @@ +# 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'); +``` + +### 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 + - 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/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/bower.json b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/bower.json new file mode 100644 index 0000000..6af573f --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/bower.json @@ -0,0 +1,28 @@ +{ + "name": "visionmedia-debug", + "main": "dist/debug.js", + "version": "2.2.0", + "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/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/browser.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/browser.js new file mode 100644 index 0000000..7c76452 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/browser.js @@ -0,0 +1,168 @@ + +/** + * 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; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : 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) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.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/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/component.json b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/component.json new file mode 100644 index 0000000..ca10637 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.2.0", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js new file mode 100644 index 0000000..7571a86 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * 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/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/node.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/node.js new file mode 100644 index 0000000..1d392a8 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/node.js @@ -0,0 +1,209 @@ + +/** + * 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/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json new file mode 100644 index 0000000..6ecc8c9 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json @@ -0,0 +1,73 @@ +{ + "name": "debug", + "version": "2.2.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "license": "MIT", + "dependencies": { + "ms": "0.7.1" + }, + "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": "b38458422b5aa8aa6d286b10dfe427e8a67e2b35", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@2.2.0", + "scripts": {}, + "_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "_from": "debug@2.2.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "tarball": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.npmignore b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.travis.yml b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.travis.yml new file mode 100644 index 0000000..895dbd3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/History.md b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/History.md new file mode 100644 index 0000000..33abe6d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/History.md @@ -0,0 +1,30 @@ + +0.0.5 / 2013-02-05 +================== + + * optimization: remove use of arguments [jkroso](https://github.com/jkroso) + * add scripts to component.json [jkroso](https://github.com/jkroso) + * tests; remove time for travis + +0.0.4 / 2013-01-07 +================== + + * added component.json #1 [jkroso](https://github.com/jkroso) + * reversed array loop #1 [jkroso](https://github.com/jkroso) + * remove fn params + +0.0.3 / 2012-09-29 +================== + + * faster with negative start args + +0.0.2 / 2012-09-29 +================== + + * support full [].slice semantics + +0.0.1 / 2012-09-29 +=================== + + * initial release + diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/LICENSE b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/LICENSE @@ -0,0 +1,22 @@ +(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/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/Makefile b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/Makefile new file mode 100644 index 0000000..2ad4e47 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/Makefile @@ -0,0 +1,5 @@ + +test: + @./node_modules/.bin/mocha $(T) $(TESTS) + +.PHONY: test diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/README.md b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/README.md new file mode 100644 index 0000000..6605c39 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/README.md @@ -0,0 +1,62 @@ +#sliced +========== + +A faster alternative to `[].slice.call(arguments)`. + +[![Build Status](https://secure.travis-ci.org/aheckmann/sliced.png)](http://travis-ci.org/aheckmann/sliced) + +Example output from [benchmark.js](https://github.com/bestiejs/benchmark.js) + + Array.prototype.slice.call x 1,320,205 ops/sec ±2.35% (92 runs sampled) + [].slice.call x 1,314,605 ops/sec ±1.60% (95 runs sampled) + cached slice.call x 10,468,380 ops/sec ±1.45% (95 runs sampled) + sliced x 16,608,237 ops/sec ±1.40% (92 runs sampled) + fastest is sliced + + Array.prototype.slice.call(arguments, 1) x 1,383,584 ops/sec ±1.73% (97 runs sampled) + [].slice.call(arguments, 1) x 1,494,735 ops/sec ±1.33% (95 runs sampled) + cached slice.call(arguments, 1) x 10,085,270 ops/sec ±1.51% (97 runs sampled) + sliced(arguments, 1) x 16,620,480 ops/sec ±1.29% (95 runs sampled) + fastest is sliced(arguments, 1) + + Array.prototype.slice.call(arguments, -1) x 1,303,262 ops/sec ±1.62% (94 runs sampled) + [].slice.call(arguments, -1) x 1,325,615 ops/sec ±1.36% (97 runs sampled) + cached slice.call(arguments, -1) x 9,673,603 ops/sec ±1.70% (96 runs sampled) + sliced(arguments, -1) x 16,384,575 ops/sec ±1.06% (91 runs sampled) + fastest is sliced(arguments, -1) + + Array.prototype.slice.call(arguments, -2, -10) x 1,404,390 ops/sec ±1.61% (95 runs sampled) + [].slice.call(arguments, -2, -10) x 1,514,367 ops/sec ±1.21% (96 runs sampled) + cached slice.call(arguments, -2, -10) x 9,836,017 ops/sec ±1.21% (95 runs sampled) + sliced(arguments, -2, -10) x 18,544,882 ops/sec ±1.30% (91 runs sampled) + fastest is sliced(arguments, -2, -10) + + Array.prototype.slice.call(arguments, -2, -1) x 1,458,604 ops/sec ±1.41% (97 runs sampled) + [].slice.call(arguments, -2, -1) x 1,536,547 ops/sec ±1.63% (99 runs sampled) + cached slice.call(arguments, -2, -1) x 10,060,633 ops/sec ±1.37% (96 runs sampled) + sliced(arguments, -2, -1) x 18,608,712 ops/sec ±1.08% (93 runs sampled) + fastest is sliced(arguments, -2, -1) + +_Benchmark [source](https://github.com/aheckmann/sliced/blob/master/bench.js)._ + +##Usage + +`sliced` accepts the same arguments as `Array#slice` so you can easily swap it out. + +```js +function zing () { + var slow = [].slice.call(arguments, 1, 8); + var args = slice(arguments, 1, 8); + + var slow = Array.prototype.slice.call(arguments); + var args = slice(arguments); + // etc +} +``` + +## install + + npm install sliced + + +[LICENSE](https://github.com/aheckmann/sliced/blob/master/LICENSE) diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/bench.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/bench.js new file mode 100644 index 0000000..f201d16 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/bench.js @@ -0,0 +1,95 @@ + +var sliced = require('./') +var Bench = require('benchmark'); +var s = new Bench.Suite; +var slice = [].slice; + +s.add('Array.prototype.slice.call', function () { + Array.prototype.slice.call(arguments); +}).add('[].slice.call', function () { + [].slice.call(arguments); +}).add('cached slice.call', function () { + slice.call(arguments) +}).add('sliced', function () { + sliced(arguments) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, 1)', function () { + Array.prototype.slice.call(arguments, 1); +}).add('[].slice.call(arguments, 1)', function () { + [].slice.call(arguments, 1); +}).add('cached slice.call(arguments, 1)', function () { + slice.call(arguments, 1) +}).add('sliced(arguments, 1)', function () { + sliced(arguments, 1) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, -1)', function () { + Array.prototype.slice.call(arguments, -1); +}).add('[].slice.call(arguments, -1)', function () { + [].slice.call(arguments, -1); +}).add('cached slice.call(arguments, -1)', function () { + slice.call(arguments, -1) +}).add('sliced(arguments, -1)', function () { + sliced(arguments, -1) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, -2, -10)', function () { + Array.prototype.slice.call(arguments, -2, -10); +}).add('[].slice.call(arguments, -2, -10)', function () { + [].slice.call(arguments, -2, -10); +}).add('cached slice.call(arguments, -2, -10)', function () { + slice.call(arguments, -2, -10) +}).add('sliced(arguments, -2, -10)', function () { + sliced(arguments, -2, -10) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, -2, -1)', function () { + Array.prototype.slice.call(arguments, -2, -1); +}).add('[].slice.call(arguments, -2, -1)', function () { + [].slice.call(arguments, -2, -1); +}).add('cached slice.call(arguments, -2, -1)', function () { + slice.call(arguments, -2, -1) +}).add('sliced(arguments, -2, -1)', function () { + sliced(arguments, -2, -1) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +/** + * Output: + * + * Array.prototype.slice.call x 1,289,592 ops/sec ±2.88% (87 runs sampled) + * [].slice.call x 1,345,451 ops/sec ±1.68% (97 runs sampled) + * cached slice.call x 10,719,886 ops/sec ±1.04% (99 runs sampled) + * sliced x 15,809,545 ops/sec ±1.46% (93 runs sampled) + * fastest is sliced + * + */ diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/component.json b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/component.json new file mode 100644 index 0000000..57e9e0c --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/component.json @@ -0,0 +1,14 @@ +{ + "name": "sliced", + "version": "0.0.5", + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "repo" : "aheckmann/sliced", + "keywords": [ + "arguments", + "slice", + "array" + ], + "scripts": ["lib/sliced.js", "index.js"], + "author": "Aaron Heckmann ", + "license": "MIT" +} diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/index.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/index.js new file mode 100644 index 0000000..3b90ae7 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/index.js @@ -0,0 +1 @@ +module.exports = exports = require('./lib/sliced'); diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/lib/sliced.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/lib/sliced.js new file mode 100644 index 0000000..d88c85b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/lib/sliced.js @@ -0,0 +1,33 @@ + +/** + * An Array.prototype.slice.call(arguments) alternative + * + * @param {Object} args something with a length + * @param {Number} slice + * @param {Number} sliceEnd + * @api public + */ + +module.exports = function (args, slice, sliceEnd) { + var ret = []; + var len = args.length; + + if (0 === len) return ret; + + var start = slice < 0 + ? Math.max(0, slice + len) + : slice || 0; + + if (sliceEnd !== undefined) { + len = sliceEnd < 0 + ? sliceEnd + len + : sliceEnd + } + + while (len-- > start) { + ret[len - start] = args[len]; + } + + return ret; +} + diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/package.json b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/package.json new file mode 100644 index 0000000..4db2cd4 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/package.json @@ -0,0 +1,52 @@ +{ + "name": "sliced", + "version": "0.0.5", + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/sliced.git" + }, + "keywords": [ + "arguments", + "slice", + "array" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.5.0", + "benchmark": "~1.0.0" + }, + "_id": "sliced@0.0.5", + "dist": { + "shasum": "5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", + "tarball": "http://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz" + }, + "_npmVersion": "1.1.59", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "directories": {}, + "_shasum": "5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", + "_resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", + "_from": "sliced@0.0.5", + "bugs": { + "url": "https://github.com/aheckmann/sliced/issues" + }, + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/aheckmann/sliced#readme" +} diff --git a/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/test/index.js b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/test/index.js new file mode 100644 index 0000000..33d36a1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/node_modules/sliced/test/index.js @@ -0,0 +1,80 @@ + +var sliced = require('../') +var assert = require('assert') + +describe('sliced', function(){ + it('exports a function', function(){ + assert.equal('function', typeof sliced); + }) + describe('with 1 arg', function(){ + it('returns an array of the arg', function(){ + var o = [3, "4", {}]; + var r = sliced(o); + assert.equal(3, r.length); + assert.equal(o[0], r[0]); + assert.equal(o[1], r[1]); + assert.equal(o[1], r[1]); + }) + }) + describe('with 2 args', function(){ + it('returns an array of the arg starting at the 2nd arg', function(){ + var o = [3, "4", 5, null]; + var r = sliced(o, 2); + assert.equal(2, r.length); + assert.equal(o[2], r[0]); + assert.equal(o[3], r[1]); + }) + }) + describe('with 3 args', function(){ + it('returns an array of the arg from the 2nd to the 3rd arg', function(){ + var o = [3, "4", 5, null]; + var r = sliced(o, 1, 2); + assert.equal(1, r.length); + assert.equal(o[1], r[0]); + }) + }) + describe('with negative start and no end', function(){ + it('begins at an offset from the end and includes all following elements', function(){ + var o = [3, "4", 5, null]; + var r = sliced(o, -2); + assert.equal(2, r.length); + assert.equal(o[2], r[0]); + assert.equal(o[3], r[1]); + + var r = sliced(o, -12); + assert.equal(4, r.length); + assert.equal(o[0], r[0]); + assert.equal(o[1], r[1]); + }) + }) + describe('with negative start and positive end', function(){ + it('begins at an offset from the end and includes `end` elements', function(){ + var o = [3, "4", {x:1}, null]; + + var r = sliced(o, -2, 1); + assert.equal(0, r.length); + + var r = sliced(o, -2, 2); + assert.equal(0, r.length); + + var r = sliced(o, -2, 3); + assert.equal(1, r.length); + assert.equal(o[2], r[0]); + }) + }) + describe('with negative start and negative end', function(){ + it('begins at `start` offset from the end and includes all elements up to `end` offset from the end', function(){ + var o = [3, "4", {x:1}, null]; + var r = sliced(o, -3, -1); + assert.equal(2, r.length); + assert.equal(o[1], r[0]); + assert.equal(o[2], r[1]); + + var r = sliced(o, -3, -3); + assert.equal(0, r.length); + + var r = sliced(o, -3, -4); + assert.equal(0, r.length); + }) + }) +}) diff --git a/5-3/node_modules/mongoose/node_modules/mquery/package.json b/5-3/node_modules/mongoose/node_modules/mquery/package.json new file mode 100644 index 0000000..e1ce167 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/package.json @@ -0,0 +1,69 @@ +{ + "name": "mquery", + "version": "1.6.3", + "description": "Expressive query building for MongoDB", + "main": "lib/mquery.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mquery.git" + }, + "dependencies": { + "bluebird": "2.9.26", + "debug": "2.2.0", + "regexp-clone": "0.0.1", + "sliced": "0.0.5" + }, + "devDependencies": { + "mongodb": "1.4.38", + "mocha": "1.9.x", + "istanbul": "0.3.2" + }, + "bugs": { + "url": "https://github.com/aheckmann/mquery/issues/new" + }, + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "keywords": [ + "mongodb", + "query", + "builder" + ], + "homepage": "https://github.com/aheckmann/mquery/", + "gitHead": "cd0c3284df2089eed5f0a331802e15c6ff0e7fab", + "_id": "mquery@1.6.3", + "_shasum": "7c02bfb7e49c8012cece1556c5e65fef61f3c8e5", + "_from": "mquery@1.6.3", + "_npmVersion": "2.9.1", + "_nodeVersion": "0.12.3", + "_npmUser": { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + "dist": { + "shasum": "7c02bfb7e49c8012cece1556c5e65fef61f3c8e5", + "tarball": "http://registry.npmjs.org/mquery/-/mquery-1.6.3.tgz" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "ebensing", + "email": "ebensing38@gmail.com" + }, + { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/mquery/-/mquery-1.6.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/mquery/test/collection/browser.js b/5-3/node_modules/mongoose/node_modules/mquery/test/collection/browser.js new file mode 100644 index 0000000..e69de29 diff --git a/5-3/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js b/5-3/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js new file mode 100644 index 0000000..e69de29 diff --git a/5-3/node_modules/mongoose/node_modules/mquery/test/collection/node.js b/5-3/node_modules/mongoose/node_modules/mquery/test/collection/node.js new file mode 100644 index 0000000..43f446e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/test/collection/node.js @@ -0,0 +1,29 @@ + +var assert = require('assert') +var slice = require('sliced') +var mongo = require('mongodb') +var utils = require('../../').utils; + +var uri = process.env.MQUERY_URI || 'mongodb://localhost/mquery'; +var db; + +exports.getCollection = function (cb) { + mongo.Db.connect(uri, function (err, db_) { + assert.ifError(err); + db = db_; + + var collection = db.collection('stuff'); + collection.opts.safe = true; + + // clean test db before starting + db.dropDatabase(function () { + cb(null, collection); + }); + }) +} + +exports.dropCollection = function (cb) { + db.dropDatabase(function () { + db.close(cb); + }) +} diff --git a/5-3/node_modules/mongoose/node_modules/mquery/test/env.js b/5-3/node_modules/mongoose/node_modules/mquery/test/env.js new file mode 100644 index 0000000..9b9b80b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/test/env.js @@ -0,0 +1,20 @@ + +var assert = require('assert') +var env = require('../').env; + +console.log('environment: %s', env.type); + +var col; +switch (env.type) { + case 'node': + col = require('./collection/node'); + break; + case 'mongo': + col = require('./collection/mongo'); + case 'browser': + col = require('./collection/browser'); + default: + throw new Error('missing collection implementation for environment: ' + env.type); +} + +module.exports = exports = col; diff --git a/5-3/node_modules/mongoose/node_modules/mquery/test/index.js b/5-3/node_modules/mongoose/node_modules/mquery/test/index.js new file mode 100644 index 0000000..747c947 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/test/index.js @@ -0,0 +1,2875 @@ +var mquery = require('../'); +var assert = require('assert'); + +describe('mquery', function(){ + var col; + + before(function(done){ + // get the env specific collection interface + require('./env').getCollection(function (err, collection) { + assert.ifError(err); + col = collection; + done(); + }); + }) + + after(function(done){ + require('./env').dropCollection(done); + }) + + describe('mquery', function(){ + it('is a function', function(){ + assert.equal('function', typeof mquery); + }) + it('creates instances with the `new` keyword', function(){ + assert.ok(mquery() instanceof mquery); + }) + describe('defaults', function(){ + it('are set', function(){ + var m = mquery(); + assert.strictEqual(undefined, m.op); + assert.deepEqual({}, m.options); + }) + }) + describe('criteria', function(){ + it('if collection-like is used as collection', function(){ + var m = mquery(col); + assert.equal(col, m._collection.collection); + }) + it('non-collection-like is used as criteria', function(){ + var m = mquery({ works: true }); + assert.ok(!m._collection); + assert.deepEqual({ works: true }, m._conditions); + }) + }) + describe('options', function(){ + it('are merged when passed', function(){ + var m = mquery(col, { safe: true }); + assert.deepEqual({ safe: true }, m.options); + var m = mquery({ name: 'mquery' }, { safe: true }); + assert.deepEqual({ safe: true }, m.options); + }) + }) + }) + + describe('toConstructor', function(){ + it('creates subclasses of mquery', function(){ + var opts = { safe: { w: 'majority' }, readPreference: 'p' }; + var match = { name: 'test', count: { $gt: 101 }}; + var select = { name: 1, count: 0 } + var update = { $set: { x: true }}; + var path = 'street'; + + var q = mquery().setOptions(opts); + q.where(match); + q.select(select); + q.update(update); + q.where(path); + q.find(); + + var M = q.toConstructor(); + var m = M(); + + assert.ok(m instanceof mquery); + assert.deepEqual(opts, m.options); + assert.deepEqual(match, m._conditions); + assert.deepEqual(select, m._fields); + assert.deepEqual(update, m._update); + assert.equal(path, m._path); + assert.equal('find', m.op); + }) + }) + + describe('setOptions', function(){ + it('calls associated methods', function(){ + var m = mquery(); + assert.equal(m._collection, null); + m.setOptions({ collection: col }); + assert.equal(m._collection.collection, col); + }) + it('directly sets option when no method exists', function(){ + var m = mquery(); + assert.equal(m.options.woot, null); + m.setOptions({ woot: 'yay' }); + assert.equal(m.options.woot, 'yay'); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.setOptions(); + assert.equal(m, n); + var n = m.setOptions({ x: 1 }); + assert.equal(m, n); + }) + }) + + describe('collection', function(){ + it('sets the _collection', function(){ + var m = mquery(); + m.collection(col); + assert.equal(m._collection.collection, col); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.collection(col); + assert.equal(m, n); + }) + }) + + describe('$where', function(){ + it('sets the $where condition', function(){ + var m = mquery(); + function go () {} + m.$where(go); + assert.ok(go === m._conditions.$where); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.$where('x'); + assert.equal(m, n); + }) + }) + + describe('where', function(){ + it('without arguments', function(){ + var m = mquery(); + m.where(); + assert.deepEqual({}, m._conditions); + }) + it('with non-string/object argument', function(){ + var m = mquery(); + + assert.throws(function(){ + m.where([]); + }, /path must be a string or object/); + }) + describe('with one argument', function(){ + it('that is an object', function(){ + var m = mquery(); + m.where({ name: 'flawed' }); + assert.strictEqual(m._conditions.name, 'flawed'); + }) + it('that is a query', function(){ + var m = mquery({ name: 'first' }); + var n = mquery({ name: 'changed' }); + m.where(n); + assert.strictEqual(m._conditions.name, 'changed'); + }) + it('that is a string', function(){ + var m = mquery(); + m.where('name'); + assert.equal('name', m._path); + assert.strictEqual(m._conditions.name, undefined); + }) + }) + it('with two arguments', function(){ + var m = mquery(); + m.where('name', 'The Great Pumpkin'); + assert.equal('name', m._path); + assert.strictEqual(m._conditions.name, 'The Great Pumpkin'); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.where('x', 'y'); + assert.equal(m, n); + var n = m.where() + assert.equal(m, n); + }) + }) + + describe('equals', function(){ + it('must be called after where()', function(){ + var m = mquery(); + assert.throws(function () { + m.equals(); + }, /must be used after where/) + }) + it('sets value of path set with where()', function(){ + var m = mquery(); + m.where('age').equals(1000); + assert.deepEqual({ age: 1000 }, m._conditions); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.where('x').equals(3); + assert.equal(m, n); + }) + }) + + describe('or', function(){ + it('pushes onto the internal $or condition', function(){ + var m = mquery(); + m.or({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$or) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.or(arg); + assert.deepEqual(arg, m._conditions.$or) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.or(arg); + m.or({ y: 1 }) + m.or([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$or) + }) + it('is chainable', function(){ + var m = mquery(); + m.or({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $or: [{ o: 'k' }] }, m._conditions) + }) + }) + + describe('nor', function(){ + it('pushes onto the internal $nor condition', function(){ + var m = mquery(); + m.nor({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$nor) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.nor(arg); + assert.deepEqual(arg, m._conditions.$nor) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.nor(arg); + m.nor({ y: 1 }) + m.nor([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$nor) + }) + it('is chainable', function(){ + var m = mquery(); + m.nor({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $nor: [{ o: 'k' }] }, m._conditions) + }) + }) + + describe('and', function(){ + it('pushes onto the internal $and condition', function(){ + var m = mquery(); + m.and({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$and) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.and(arg); + assert.deepEqual(arg, m._conditions.$and) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.and(arg); + m.and({ y: 1 }) + m.and([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$and) + }) + it('is chainable', function(){ + var m = mquery(); + m.and({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $and: [{ o: 'k' }] }, m._conditions) + }) + }) + + function generalCondition (type) { + return function () { + it('accepts 2 args', function(){ + var m = mquery()[type]('count', 3); + var check = {}; + check['$' + type] = 3; + assert.deepEqual(m._conditions.count, check); + }) + it('uses previously set `where` path if 1 arg passed', function(){ + var m = mquery().where('count')[type](3); + var check = {}; + check['$' + type] = 3; + assert.deepEqual(m._conditions.count, check); + }) + it('throws if 1 arg was passed but no previous `where` was used', function(){ + assert.throws(function(){ + mquery()[type](3); + }, /must be used after where/); + }) + it('is chainable', function(){ + var m = mquery().where('count')[type](3).where('x', 8); + var check = {x: 8, count: {}}; + check.count['$' + type] = 3; + assert.deepEqual(m._conditions, check); + }) + it('overwrites previous value', function(){ + var m = mquery().where('count')[type](3)[type](8); + var check = {}; + check['$' + type] = 8; + assert.deepEqual(m._conditions.count, check); + }) + } + } + + 'gt gte lt lte ne in nin regex size maxDistance'.split(' ').forEach(function (type) { + describe(type, generalCondition(type)) + }) + + describe('mod', function () { + describe('with 1 argument', function(){ + it('requires a previous where()', function(){ + assert.throws(function () { + mquery().mod([30, 10]) + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('madmen').mod([10,20]); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + }) + + describe('with 2 arguments and second is non-Array', function(){ + it('requires a previous where()', function(){ + assert.throws(function () { + mquery().mod('x', 10) + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('madmen').mod(10, 20); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + }) + + it('with 2 arguments and second is an array', function(){ + var m = mquery().mod('madmen', [10,20]); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + + it('with 3 arguments', function(){ + var m = mquery().mod('madmen', 10, 20); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + + it('is chainable', function(){ + var m = mquery().mod('madmen', 10, 20).where('x', 8); + var check = { madmen: { $mod: [10,20] }, x: 8}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('exists', function(){ + it('with 0 args', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().exists() + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('name').exists(); + var check = { name: { $exists: true }}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('with 1 arg', function(){ + describe('that is boolean', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().exists() + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().exists('name', false); + var check = { name: { $exists: false }}; + assert.deepEqual(m._conditions, check); + }) + }) + describe('that is not boolean', function(){ + it('sets the value to `true`', function(){ + var m = mquery().where('name').exists('yummy'); + var check = { yummy: { $exists: true }}; + assert.deepEqual(m._conditions, check); + }) + }) + }) + + describe('with 2 args', function(){ + it('works', function(){ + var m = mquery().exists('yummy', false); + var check = { yummy: { $exists: false }}; + assert.deepEqual(m._conditions, check); + }) + }) + + it('is chainable', function(){ + var m = mquery().where('name').exists().find({ x: 1 }); + var check = { name: { $exists: true }, x: 1}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('elemMatch', function(){ + describe('with null/undefined first argument', function(){ + assert.throws(function () { + mquery().elemMatch(); + }, /Invalid argument/); + assert.throws(function () { + mquery().elemMatch(null); + }, /Invalid argument/); + assert.doesNotThrow(function () { + mquery().elemMatch('', {}); + }); + }) + + describe('with 1 argument', function(){ + it('throws if not a function or object', function(){ + assert.throws(function () { + mquery().elemMatch([]); + }, /Invalid argument/); + }) + + describe('that is an object', function(){ + it('throws if no previous `where` was used', function(){ + assert.throws(function () { + mquery().elemMatch({}); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('comment').elemMatch({ author: 'joe', votes: {$gte: 3 }}); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + describe('that is a function', function(){ + it('throws if no previous `where` was used', function(){ + assert.throws(function () { + mquery().elemMatch(function(){}); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('comment').elemMatch(function (query) { + query.where({ author: 'joe', votes: {$gte: 3 }}) + }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + }) + + describe('with 2 arguments', function(){ + describe('and the 2nd is an object', function(){ + it('works', function(){ + var m = mquery().elemMatch('comment', { author: 'joe', votes: {$gte: 3 }}); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + describe('and the 2nd is a function', function(){ + it('works', function(){ + var m = mquery().elemMatch('comment', function (query) { + query.where({ author: 'joe', votes: {$gte: 3 }}) + }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + it('and the 2nd is not a function or object', function(){ + assert.throws(function () { + mquery().elemMatch('comment', []); + }, /Invalid argument/); + }) + }) + }) + + describe('within', function(){ + it('is chainable', function(){ + var m = mquery(); + assert.equal(m.where('a').within(), m); + }) + describe('when called with arguments', function(){ + it('must follow where()', function(){ + assert.throws(function () { + mquery().within([]); + }, /must be used after where/); + }) + + describe('of length 1', function(){ + it('throws if not a recognized shape', function(){ + assert.throws(function () { + mquery().where('loc').within({}); + }, /Invalid argument/) + assert.throws(function () { + mquery().where('loc').within(null); + }, /Invalid argument/) + }) + it('delegates to circle when center exists', function(){ + var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); + assert.deepEqual({ $geoWithin: {$center:[[10,10], 3]}}, m._conditions.loc); + }) + it('delegates to box when exists', function(){ + var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); + assert.deepEqual({ $geoWithin: {$box:[[10,10], [11,14]]}}, m._conditions.loc); + }) + it('delegates to polygon when exists', function(){ + var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $geoWithin: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); + }) + it('delegates to geometry when exists', function(){ + var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $geoWithin: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); + }) + }) + + describe('of length 2', function(){ + it('delegates to box()', function(){ + var m = mquery().where('loc').within([1,2],[2,5]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[2,5]]}}); + }) + }) + + describe('of length > 2', function(){ + it('delegates to polygon()', function(){ + var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); + }) + }) + }) + }) + + describe('geoWithin', function(){ + before(function(){ + mquery.use$geoWithin = false; + }) + after(function(){ + mquery.use$geoWithin = true; + }) + describe('when called with arguments', function(){ + describe('of length 1', function(){ + it('delegates to circle when center exists', function(){ + var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); + assert.deepEqual({ $within: {$center:[[10,10], 3]}}, m._conditions.loc); + }) + it('delegates to box when exists', function(){ + var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); + assert.deepEqual({ $within: {$box:[[10,10], [11,14]]}}, m._conditions.loc); + }) + it('delegates to polygon when exists', function(){ + var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $within: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); + }) + it('delegates to geometry when exists', function(){ + var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $within: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); + }) + }) + + describe('of length 2', function(){ + it('delegates to box()', function(){ + var m = mquery().where('loc').within([1,2],[2,5]); + assert.deepEqual(m._conditions.loc, { $within: { $box: [[1,2],[2,5]]}}); + }) + }) + + describe('of length > 2', function(){ + it('delegates to polygon()', function(){ + var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); + assert.deepEqual(m._conditions.loc, { $within: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); + }) + }) + }) + }) + + describe('box', function(){ + describe('with 1 argument', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().box('sometihng'); + }, /Invalid argument/); + }) + }) + describe('with > 3 arguments', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().box(1,2,3,4); + }, /Invalid argument/); + }) + }) + + describe('with 2 arguments', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().box([],[]); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('loc').box([1,2],[3,4]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); + }) + }) + + describe('with 3 arguments', function(){ + it('works', function(){ + var m = mquery().box('loc', [1,2],[3,4]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); + }) + }) + }) + + describe('polygon', function(){ + describe('when first argument is not a string', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().polygon({}); + }, /must be used after where/); + + assert.doesNotThrow(function () { + mquery().where('loc').polygon([1,2], [2,3], [3,6]); + }); + }) + + it('assigns arguments to within polygon condition', function(){ + var m = mquery().where('loc').polygon([1,2], [2,3], [3,6]); + assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); + }) + }) + + describe('when first arg is a string', function(){ + it('assigns remaining arguments to within polygon condition', function(){ + var m = mquery().polygon('loc', [1,2], [2,3], [3,6]); + assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); + }) + }) + }) + + describe('circle', function(){ + describe('with one arg', function(){ + it('must follow where()', function(){ + assert.throws(function () { + mquery().circle('x'); + }, /must be used after where/); + assert.doesNotThrow(function () { + mquery().where('loc').circle({center:[0,0], radius: 3 }); + }); + }) + it('works', function(){ + var m = mquery().where('loc').circle({center:[0,0], radius: 3 }); + assert.deepEqual(m._conditions, { loc: { $geoWithin: {$center: [[0,0],3] }}}); + }) + }) + describe('with 3 args', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().where('loc').circle(1,2,3); + }, /Invalid argument/); + }) + }) + describe('requires radius and center', function(){ + assert.throws(function () { + mquery().circle('loc', { center: 1 }); + }, /center and radius are required/); + assert.throws(function () { + mquery().circle('loc', { radius: 1 }); + }, /center and radius are required/); + assert.doesNotThrow(function () { + mquery().circle('loc', { center: [1,2], radius: 1 }); + }); + }) + }) + + describe('geometry', function(){ + // within + intersects + var point = { type: 'Point', coordinates: [[0,0],[1,1]] }; + + it('must be called after within or intersects', function(done){ + assert.throws(function () { + mquery().where('a').geometry(point); + }, /must come after/); + + assert.doesNotThrow(function () { + mquery().where('a').within().geometry(point); + }); + + assert.doesNotThrow(function () { + mquery().where('a').intersects().geometry(point); + }); + + done(); + }) + + describe('when called with one argument', function(){ + describe('after within()', function(){ + it('and arg quacks like geoJSON', function(done){ + var m = mquery().where('a').within().geometry(point); + assert.deepEqual({ a: { $geoWithin: { $geometry: point }}}, m._conditions); + done(); + }) + }) + + describe('after intersects()', function(){ + it('and arg quacks like geoJSON', function(done){ + var m = mquery().where('a').intersects().geometry(point); + assert.deepEqual({ a: { $geoIntersects: { $geometry: point }}}, m._conditions); + done(); + }) + }) + + it('and arg does not quack like geoJSON', function(done){ + assert.throws(function () { + mquery().where('b').within().geometry({type:1, coordinates:2}); + }, /Invalid argument/); + done(); + }) + }) + + describe('when called with zero arguments', function(){ + it('throws', function(done){ + assert.throws(function () { + mquery().where('a').within().geometry(); + }, /Invalid argument/); + + done(); + }) + }) + + describe('when called with more than one arguments', function(){ + it('throws', function(done){ + assert.throws(function () { + mquery().where('a').within().geometry({type:'a',coordinates:[]}, 2); + }, /Invalid argument/); + done(); + }) + }) + }) + + describe('intersects', function(){ + it('must be used after where()', function(done){ + var m = mquery(); + assert.throws(function () { + m.intersects(); + }, /must be used after where/) + done(); + }) + + it('sets geo comparison to "$intersects"', function(done){ + var n = mquery().where('a').intersects(); + assert.equal('$geoIntersects', n._geoComparison); + done(); + }) + + it('is chainable', function(){ + var m = mquery(); + assert.equal(m.where('a').intersects(), m); + }) + + it('calls geometry if argument quacks like geojson', function(done){ + var m = mquery(); + var o = { type: 'LineString', coordinates: [[0,1],[3,40]] }; + var ran = false; + + m.geometry = function (arg) { + ran = true; + assert.deepEqual(o, arg); + } + + m.where('a').intersects(o); + assert.ok(ran); + + done(); + }) + + it('throws if argument is not geometry-like', function(done){ + var m = mquery().where('a'); + + assert.throws(function () { + m.intersects(null); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(undefined); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(false); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects({}); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects([]); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(function(){}); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(NaN); + }, /Invalid argument/); + + done(); + }) + }) + + describe('near', function(){ + // near nearSphere + describe('with 0 args', function(){ + it('is compatible with geometry()', function(done){ + var q = mquery().where('x').near().geometry({ type: 'Point', coordinates: [180, 11] }); + assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [180,11]}}}, q._conditions.x); + done(); + }) + }) + + describe('with 1 arg', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().near(1); + }, /must be used after where/) + }) + it('does not throw if used after where()', function(){ + assert.doesNotThrow(function () { + mquery().where('loc').near({center:[1,1]}); + }) + }) + }) + describe('with > 2 args', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().near(1,2,3); + }, /Invalid argument/) + }) + }) + + it('creates $geometry args for GeoJSON', function(){ + var m = mquery().where('loc').near({ center: { type: 'Point', coordinates: [10,10] }}); + assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [10,10]}}}, m._conditions.loc); + }) + + it('expects `center`', function(){ + assert.throws(function () { + mquery().near('loc', { maxDistance: 3 }); + }, /center is required/) + assert.doesNotThrow(function () { + mquery().near('loc', { center: [3,4] }); + }) + }) + + it('accepts spherical conditions', function(){ + var m = mquery().where('loc').near({ center: [1,2], spherical: true }); + assert.deepEqual(m._conditions, { loc: { $nearSphere: [1,2]}}); + }) + + it('is non-spherical by default', function(){ + var m = mquery().where('loc').near({ center: [1,2] }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2]}}); + }) + + it('supports maxDistance', function(){ + var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}}); + }) + + it('is chainable', function(){ + var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }).find({ x: 1 }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}, x: 1}); + }) + + describe('supports passing GeoJSON, gh-13', function(){ + it('with center', function(){ + var m = mquery().where('loc').near({ + center: { type: 'Point', coordinates: [1,1] } + , maxDistance: 2 + }); + + var expect = { + loc: { + $near: { + $geometry: { + type: 'Point' + , coordinates : [1,1] + } + , $maxDistance : 2 + } + } + } + + assert.deepEqual(m._conditions, expect); + }) + }) + }) + + // fields + + describe('select', function(){ + describe('with 0 args', function(){ + it('is chainable', function(){ + var m = mquery() + assert.equal(m, m.select()); + }) + }) + + it('accepts an object', function(){ + var o = { x: 1, y: 1 } + var m = mquery().select(o); + assert.deepEqual(m._fields, o); + }) + + it('accepts a string', function(){ + var o = 'x -y'; + var m = mquery().select(o); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + }) + + it('does not accept an array', function(done){ + assert.throws(function () { + var o = ['x', '-y']; + var m = mquery().select(o); + }, /Invalid select/); + done(); + }) + + it('merges previous arguments', function(){ + var o = { x: 1, y: 0, a: 1 } + var m = mquery().select(o); + m.select('z -u w').select({ x: 0 }) + assert.deepEqual(m._fields, { + x: 0 + , y: 0 + , z: 1 + , u: 0 + , w: 1 + , a: 1 + }); + }) + + it('rejects non-string, object, arrays', function(){ + assert.throws(function () { + mquery().select(function(){}); + }, /Invalid select\(\) argument/); + }) + + it('accepts aguments objects', function(){ + var m = mquery(); + function t () { + m.select(arguments); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + } + t('x', '-y'); + }) + + noDistinct('select'); + no('count', 'select'); + }) + + describe('selected', function() { + it('returns true when fields have been selected', function(done) { + var m = mquery().select({ name: 1 }); + assert.ok(m.selected()); + + var m = mquery().select('name'); + assert.ok(m.selected()); + + done(); + }); + + it('returns false when no fields have been selected', function(done) { + var m = mquery(); + assert.strictEqual(false, m.selected()); + done(); + }); + }); + + describe('selectedInclusively', function() { + describe('returns false', function(){ + it('when no fields have been selected', function(done) { + assert.strictEqual(false, mquery().selectedInclusively()); + assert.equal(false, mquery().select({}).selectedInclusively()); + done(); + }); + it('when any fields have been excluded', function(done) { + assert.strictEqual(false, mquery().select('-name').selectedInclusively()); + assert.strictEqual(false, mquery().select({ name: 0 }).selectedInclusively()); + assert.strictEqual(false, mquery().select('name bio -_id').selectedInclusively()); + assert.strictEqual(false, mquery().select({ name: 1, _id: 0 }).selectedInclusively()); + done(); + }); + it('when using $meta', function(done) { + assert.strictEqual(false, mquery().select({ name: { $meta: 'textScore' } }).selectedInclusively()); + done(); + }); + }); + + describe('returns true', function() { + it('when fields have been included', function(done) { + assert.equal(true, mquery().select('name').selectedInclusively()); + assert.equal(true, mquery().select({ name:1 }).selectedInclusively()); + done(); + }); + }); + }); + + describe('selectedExclusively', function() { + describe('returns false', function(){ + it('when no fields have been selected', function(done) { + assert.equal(false, mquery().selectedExclusively()); + assert.equal(false, mquery().select({}).selectedExclusively()); + done(); + }); + it('when fields have only been included', function(done) { + assert.equal(false, mquery().select('name').selectedExclusively()); + assert.equal(false, mquery().select({ name: 1 }).selectedExclusively()); + done(); + }); + }); + + describe('returns true', function() { + it('when any field has been excluded', function(done) { + assert.equal(true, mquery().select('-name').selectedExclusively()); + assert.equal(true, mquery().select({ name:0 }).selectedExclusively()); + assert.equal(true, mquery().select('-_id').selectedExclusively()); + assert.strictEqual(true, mquery().select('name bio -_id').selectedExclusively()); + assert.strictEqual(true, mquery().select({ name: 1, _id: 0 }).selectedExclusively()); + done(); + }); + }); + }); + + describe('slice', function(){ + describe('with 0 args', function(){ + it('is chainable', function(){ + var m = mquery() + assert.equal(m, m.slice()); + }) + it('is a noop', function(){ + var m = mquery().slice(); + assert.deepEqual(m._fields, undefined); + }) + }) + + describe('with 1 arg', function(){ + it('throws if not called after where()', function(){ + assert.throws(function () { + mquery().slice(1); + }, /must be used after where/); + assert.doesNotThrow(function () { + mquery().where('a').slice(1); + }); + }) + it('that is a number', function(){ + var query = mquery(); + query.where('collection').slice(5); + assert.deepEqual(query._fields, {collection: {$slice: 5}}); + }) + it('that is an array', function(){ + var query = mquery(); + query.where('collection').slice([5,10]); + assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); + }) + it('that is an object', function() { + var query = mquery(); + query.slice({ collection: [5, 10] }); + assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); + }) + }) + + describe('with 2 args', function(){ + describe('and first is a number', function(){ + it('throws if not called after where', function(){ + assert.throws(function () { + mquery().slice(2,3); + }, /must be used after where/); + }) + it('does not throw if used after where', function(){ + var query = mquery(); + query.where('collection').slice(2,3); + assert.deepEqual(query._fields, {collection: {$slice: [2,3]}}); + }) + }) + it('and first is not a number', function(){ + var query = mquery().slice('collection', [-5, 2]); + assert.deepEqual(query._fields, {collection: {$slice: [-5,2]}}); + }) + }) + + describe('with 3 args', function(){ + it('works', function(){ + var query = mquery(); + query.slice('collection', 14, 10); + assert.deepEqual(query._fields, {collection: {$slice: [14, 10]}}); + }) + }) + + noDistinct('slice'); + no('count', 'slice'); + }) + + // options + + describe('sort', function(){ + describe('with 0 args', function(){ + it('chains', function(){ + var m = mquery(); + assert.equal(m, m.sort()); + }) + it('has no affect', function(){ + var m = mquery(); + assert.equal(m.options.sort, undefined); + }) + }) + + it('works', function(){ + var query = mquery(); + query.sort('a -c b'); + assert.deepEqual(query.options.sort, { a : 1, b: 1, c : -1}); + + query = mquery(); + query.sort({'a': 1, 'c': -1, 'b': 'asc', e: 'descending', f: 'ascending'}); + assert.deepEqual(query.options.sort, {'a': 1, 'c': -1, 'b': 1, 'e': -1, 'f': 1}); + + query = mquery(); + var e= undefined; + try { + query.sort(['a', 1]); + } catch (err) { + e= err; + } + assert.ok(e, 'uh oh. no error was thrown'); + assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); + + e= undefined; + try { + query.sort('a', 1, 'c', -1, 'b', 1); + } catch (err) { + e= err; + } + assert.ok(e, 'uh oh. no error was thrown'); + assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); + }) + + it('handles $meta sort options', function(){ + var query = mquery(); + query.sort({ score: { $meta : "textScore" } }); + assert.deepEqual(query.options.sort, { score : { $meta : "textScore" } }); + }) + + no('count', 'sort'); + }) + + function simpleOption (type, options) { + describe(type, function(){ + it('sets the ' + type + ' option', function(){ + var m = mquery()[type](2); + var optionName = options.name || type; + assert.equal(2, m.options[optionName]); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m[type](3), m); + }) + + if (!options.distinct) noDistinct(type); + if (!options.count) no('count', type); + }) + } + + var negated = { + limit: {distinct: false, count: true} + , skip: {distinct: false, count: true} + , maxScan: {distinct: false, count: false} + , batchSize: {distinct: false, count: false} + , maxTime: {distinct: true, count: true, name: 'maxTimeMS' } + , comment: {distinct: false, count: false} + }; + Object.keys(negated).forEach(function (key) { + simpleOption(key, negated[key]); + }) + + describe('snapshot', function(){ + it('works', function(){ + var query = mquery(); + query.snapshot(); + assert.equal(true, query.options.snapshot); + + var query = mquery() + query.snapshot(true); + assert.equal(true, query.options.snapshot); + + var query = mquery() + query.snapshot(false); + assert.equal(false, query.options.snapshot); + }) + noDistinct('snapshot'); + no('count', 'snapshot'); + }) + + describe('hint', function(){ + it('accepts an object', function(){ + var query2 = mquery(); + query2.hint({'a': 1, 'b': -1}); + assert.deepEqual(query2.options.hint, {'a': 1, 'b': -1}); + }) + + it('rejects everything else', function(){ + assert.throws(function(){ + mquery().hint('c'); + }, /Invalid hint./); + assert.throws(function(){ + mquery().hint(['c']); + }, /Invalid hint./); + assert.throws(function(){ + mquery().hint(1); + }, /Invalid hint./); + }) + + describe('does not have side affects', function(){ + it('on invalid arg', function(){ + var m = mquery(); + try { + m.hint(1); + } catch (err) { + // ignore + } + assert.equal(undefined, m.options.hint); + }) + it('on missing arg', function(){ + var m = mquery().hint(); + assert.equal(undefined, m.options.hint); + }) + }) + + noDistinct('hint'); + }) + + describe('slaveOk', function(){ + it('works', function(){ + var query = mquery(); + query.slaveOk(); + assert.equal(true, query.options.slaveOk); + + var query = mquery() + query.slaveOk(true); + assert.equal(true, query.options.slaveOk); + + var query = mquery() + query.slaveOk(false); + assert.equal(false, query.options.slaveOk); + }) + }) + + describe('read', function(){ + it('sets associated readPreference option', function(){ + var m = mquery(); + m.read('p'); + assert.equal('primary', m.options.readPreference); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m, m.read('sp')); + }) + }) + + describe('tailable', function(){ + it('works', function(){ + var query = mquery(); + query.tailable(); + assert.equal(true, query.options.tailable); + + var query = mquery() + query.tailable(true); + assert.equal(true, query.options.tailable); + + var query = mquery() + query.tailable(false); + assert.equal(false, query.options.tailable); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m, m.tailable()); + }) + noDistinct('tailable'); + no('count', 'tailable'); + }) + + // query utilities + + describe('merge', function(){ + describe('with falsy arg', function(){ + it('returns itself', function(){ + var m = mquery(); + assert.equal(m, m.merge()); + assert.equal(m, m.merge(null)); + assert.equal(m, m.merge(0)); + }) + }) + describe('with an argument', function(){ + describe('that is not a query or plain object', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().merge([]); + }, /Invalid argument/); + assert.throws(function () { + mquery().merge('merge'); + }, /Invalid argument/); + assert.doesNotThrow(function () { + mquery().merge({}); + }, /Invalid argument/); + }) + }) + + describe('that is a query', function(){ + it('merges conditions, field selection, and options', function(){ + var m = mquery({ x: 'hi' }, { select: 'x y', another: true }) + var n = mquery().merge(m); + assert.deepEqual(n._conditions, m._conditions); + assert.deepEqual(n._fields, m._fields); + assert.deepEqual(n.options, m.options); + }) + it('clones update arguments', function(done){ + var original = { $set: { iTerm: true }} + var m = mquery().update(original); + var n = mquery().merge(m); + m.update({ $set: { x: 2 }}) + assert.notDeepEqual(m._update, n._update); + done(); + }) + it('is chainable', function(){ + var m = mquery({ x: 'hi' }); + var n = mquery(); + assert.equal(n, n.merge(m)); + }) + }) + + describe('that is an object', function(){ + it('merges', function(){ + var m = { x: 'hi' }; + var n = mquery().merge(m); + assert.deepEqual(n._conditions, { x: 'hi' }); + }) + it('clones update arguments', function(done){ + var original = { $set: { iTerm: true }} + var m = mquery().update(original); + var n = mquery().merge(original); + m.update({ $set: { x: 2 }}) + assert.notDeepEqual(m._update, n._update); + done(); + }) + it('is chainable', function(){ + var m = { x: 'hi' }; + var n = mquery(); + assert.equal(n, n.merge(m)); + }) + }) + }) + }) + + // queries + + describe('find', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.find() + }) + assert.doesNotThrow(function () { + m.find({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery().find({ x: 1 }).find().find({ y: 2 }); + assert.deepEqual(m._conditions, {x:1,y:2}); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.tailable(); + m.select('_id'); + var a = mquery().find(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).find({ name: 'mquery' }, function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery({ name: 'mquery' }); + mquery(col).find(m, function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery' }).collection(col).find(function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }); + }) + }) + }) + + describe('findOne', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.findOne() + }) + assert.doesNotThrow(function () { + m.findOne({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery(); + var n = m.findOne({ x: 1 }).findOne().findOne({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(m._conditions, {x:1,y:2}); + assert.equal('findOne', m.op); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.read('nearest'); + m.select('_id'); + var a = mquery().findOne(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery findone' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery findone' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).findOne({ name: 'mquery findone' }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery(col).where({ name: 'mquery findone' }); + mquery(col).findOne(m, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery findone' }).collection(col).findOne(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }); + }) + }) + }) + + describe('count', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.count() + }) + assert.doesNotThrow(function () { + m.count({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery(); + var n = m.count({ x: 1 }).count().count({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(m._conditions, {x:1,y:2}); + assert.equal('count', m.op); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.read('nearest'); + m.select('_id'); + var a = mquery().count(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery count' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery count' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).count({ name: 'mquery count' }, function (err, count) { + assert.ifError(err); + assert.ok(count); + assert.ok(1 === count); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery({ name: 'mquery count' }); + mquery(col).count(m, function (err, count) { + assert.ifError(err); + assert.ok(count); + assert.ok(1 === count); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery count' }).collection(col).count(function (err, count) { + assert.ifError(err); + assert.ok(1 === count); + done(); + }); + }) + }) + + describe('validates its option', function(){ + it('sort', function(done){ + assert.throws(function(){ + var m = mquery().sort('x').count(); + }, /sort cannot be used with count/); + done(); + }) + + it('select', function(done){ + assert.throws(function(){ + var m = mquery().select('x').count(); + }, /field selection and slice cannot be used with count/); + done(); + }) + + it('slice', function(done){ + assert.throws(function(){ + var m = mquery().where('x').slice(-3).count(); + }, /field selection and slice cannot be used with count/); + done(); + }) + + it('limit', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().limit(3).count(); + }) + done(); + }) + + it('skip', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().skip(3).count(); + }) + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 }).count(); + }, /batchSize cannot be used with count/); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery').count(); + }, /comment cannot be used with count/); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300).count(); + }, /maxScan cannot be used with count/); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot().count(); + }, /snapshot cannot be used with count/); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable().count(); + }, /tailable cannot be used with count/); + done(); + }) + }) + }) + + describe('distinct', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.distinct() + }) + assert.doesNotThrow(function () { + m.distinct('name') + }) + assert.doesNotThrow(function () { + m.distinct({ name: 'mquery distinct' }) + }) + assert.doesNotThrow(function () { + m.distinct({ name: 'mquery distinct' }, 'name') + }) + }) + }) + + it('is chainable', function(){ + var m = mquery({x:1}).distinct('name'); + var n = m.distinct({y:2}); + assert.equal(m, n); + assert.deepEqual(n._conditions, {x:1, y:2}); + assert.equal('name', n._distinct); + assert.equal('distinct', n.op); + }); + + it('overwrites field', function(){ + var m = mquery({ name: 'mquery' }).distinct('name'); + m.distinct('rename'); + assert.equal(m._distinct, 'rename'); + m.distinct({x:1}, 'renamed'); + assert.equal(m._distinct, 'renamed'); + }) + + it('merges other queries', function(){ + var m = mquery().distinct({ name: 'mquery' }, 'age') + m.read('nearest'); + var a = mquery().distinct(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + assert.deepEqual(a._distinct, m._distinct); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery distinct', age: 1 }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery distinct' }, done); + }) + + it('when distinct arg is passed with a callback', function(done){ + mquery(col).distinct('distinct', function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + describe('when criteria is passed with a callback', function(){ + it('if distinct arg was declared', function(done){ + mquery(col).distinct('age').distinct({ name: 'mquery distinct' }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + it('but not if distinct arg was not declared', function(){ + assert.throws(function(){ + mquery(col).distinct({ name: 'mquery distinct' }, function(){}) + }, /No value for `distinct`/) + }) + }) + describe('when Query is passed with a callback', function(){ + var m = mquery({ name: 'mquery distinct' }); + it('if distinct arg was declared', function(done){ + mquery(col).distinct('age').distinct(m, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + it('but not if distinct arg was not declared', function(){ + assert.throws(function(){ + mquery(col).distinct(m, function(){}) + }, /No value for `distinct`/) + }) + }) + describe('when just a callback is passed', function(done){ + it('if distinct arg was declared', function(done){ + var m = mquery({ name: 'mquery distinct' }); + m.collection(col); + m.distinct('age'); + m.distinct(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }); + }) + it('but not if no distinct arg was declared', function(){ + var m = mquery(); + m.collection(col); + assert.throws(function () { + m.distinct(function(){}); + }, /No value for `distinct`/); + }) + }) + }) + + describe('validates its option', function(){ + it('sort', function(done){ + assert.throws(function(){ + var m = mquery().sort('x').distinct(); + }, /sort cannot be used with distinct/); + done(); + }) + + it('select', function(done){ + assert.throws(function(){ + var m = mquery().select('x').distinct(); + }, /field selection and slice cannot be used with distinct/); + done(); + }) + + it('slice', function(done){ + assert.throws(function(){ + var m = mquery().where('x').slice(-3).distinct(); + }, /field selection and slice cannot be used with distinct/); + done(); + }) + + it('limit', function(done){ + assert.throws(function(){ + var m = mquery().limit(3).distinct(); + }, /limit cannot be used with distinct/); + done(); + }) + + it('skip', function(done){ + assert.throws(function(){ + var m = mquery().skip(3).distinct(); + }, /skip cannot be used with distinct/); + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 }).distinct(); + }, /batchSize cannot be used with distinct/); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery').distinct(); + }, /comment cannot be used with distinct/); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300).distinct(); + }, /maxScan cannot be used with distinct/); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot().distinct(); + }, /snapshot cannot be used with distinct/); + done(); + }) + + it('hint', function(done){ + assert.throws(function(){ + var m = mquery().hint({ x: 1 }).distinct(); + }, /hint cannot be used with distinct/); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable().distinct(); + }, /tailable cannot be used with distinct/); + done(); + }) + }) + }) + + describe('update', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.update({ name: 'old' }, { name: 'updated' }, { multi: true }) + }) + assert.doesNotThrow(function () { + m.update({ name: 'old' }, { name: 'updated' }) + }) + assert.doesNotThrow(function () { + m.update({ name: 'updated' }) + }) + assert.doesNotThrow(function () { + m.update() + }) + }) + }) + + it('is chainable', function(){ + var m = mquery({x:1}).update({ y: 2 }); + var n = m.where({y:2}); + assert.equal(m, n); + assert.deepEqual(n._conditions, {x:1, y:2}); + assert.deepEqual({ y: 2 }, n._update); + assert.equal('update', n.op); + }); + + it('merges update doc arg', function(){ + var a = [1,2]; + var m = mquery().where({ name: 'mquery' }).update({ x: 'stuff', a: a }); + m.update({ z: 'stuff' }); + assert.deepEqual(m._update, { z: 'stuff', x: 'stuff', a: a }); + assert.deepEqual(m._conditions, { name: 'mquery' }); + assert.ok(!m.options.overwrite); + m.update({}, { z: 'renamed' }, { overwrite: true }); + assert.ok(m.options.overwrite === true); + assert.deepEqual(m._conditions, { name: 'mquery' }); + assert.deepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); + a.push(3); + assert.notDeepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); + }) + + it('merges other options', function(){ + var m = mquery(); + m.setOptions({ overwrite: true }); + m.update({ age: 77 }, { name: 'pagemill' }, { multi: true }) + assert.deepEqual({ age: 77 }, m._conditions); + assert.deepEqual({ name: 'pagemill' }, m._update); + assert.deepEqual({ overwrite: true, multi: true }, m.options); + }) + + describe('executes', function(){ + var id; + before(function (done) { + col.insert({ name: 'mquery update', age: 1 }, { safe: true }, function (err, docs) { + var elem = docs[0]; + id = elem._id; + done(); + }); + }); + + after(function(done){ + col.remove({ _id: id }, done); + }) + + describe('when conds + doc + opts + callback passed', function(){ + it('works', function(done){ + var m = mquery(col).where({ _id: id }) + m.update({}, { name: 'Sparky' }, { safe: true }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'Sparky'); + done(); + }) + }) + }) + }) + + describe('when conds + doc + callback passed', function(){ + it('works', function (done) { + var m = mquery(col).update({ _id: id }, { name: 'fairgrounds' }, function (err, num, doc) { + assert.ifError(err); + assert.ok(1, num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'fairgrounds'); + done(); + }) + }) + }) + }) + + describe('when doc + callback passed', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }).update({ name: 'changed' }, function (err, num, doc) { + assert.ifError(err); + assert.ok(1, num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'changed'); + done(); + }) + }) + }) + }) + + describe('when just callback passed', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true }); + m.update({ name: 'Frankenweenie' }); + m.update(function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'Frankenweenie'); + done(); + }) + }) + }) + }) + + describe('without a callback', function(){ + it('when forced by exec()', function(done){ + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, multi: true }); + m.update({ name: 'forced' }); + + var update = m._collection.update; + m._collection.update = function (conds, doc, opts, cb) { + m._collection.update = update; + + assert.ok(!opts.safe); + assert.ok(true === opts.multi); + assert.equal('forced', doc.$set.name); + done(); + } + + m.exec() + }) + }) + + describe('except when update doc is empty and missing overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true }); + m.update({ }, function (err, num) { + assert.ifError(err); + assert.ok(0 === num); + setTimeout(function(){ + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(3, mquery.utils.keys(doc).length); + assert.equal(id, doc._id.toString()); + assert.equal('Frankenweenie', doc.name); + done(); + }) + }, 300); + }) + }) + }); + + describe('when update doc is set with overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, overwrite: true }); + m.update({ all: 'yep', two: 2 }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(3, mquery.utils.keys(doc).length); + assert.equal('yep', doc.all); + assert.equal(2, doc.two); + assert.equal(id, doc._id.toString()); + done(); + }) + }) + }) + }) + + describe('when update doc is empty with overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, overwrite: true }); + m.update({ }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(1, mquery.utils.keys(doc).length); + assert.equal(id, doc._id.toString()); + done(); + }) + }) + }) + }) + + describe('when boolean (true) - exec()', function(){ + it('works', function(done){ + var m = mquery(col).where({ _id: id }); + m.update({ name: 'bool' }).update(true); + setTimeout(function () { + m.findOne(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('bool', doc.name); + done(); + }) + }, 300) + }) + }) + }) + }) + + describe('remove', function(){ + describe('with 0 args', function(){ + var name = 'remove: no args test' + before(function(done){ + col.insert({ name: name }, { safe: true }, done) + }) + after(function(done){ + col.remove({ name: name }, { safe: true }, done) + }) + + it('does not execute', function(done){ + var remove = col.remove; + col.remove = function () { + col.remove = remove; + done(new Error('remove executed!')); + } + + var m = mquery(col).where({ name: name }).remove() + setTimeout(function () { + col.remove = remove; + done(); + }, 10); + }) + + it('chains', function(){ + var m = mquery(); + assert.equal(m, m.remove()); + }) + }) + + describe('with 1 argument', function(){ + var name = 'remove: 1 arg test' + before(function(done){ + col.insert({ name: name }, { safe: true }, done) + }) + after(function(done){ + col.remove({ name: name }, { safe: true }, done) + }) + + describe('that is a', function(){ + it('plain object', function(){ + var m = mquery(col).remove({ name: 'Whiskers' }); + m.remove({ color: '#fff' }) + assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); + }) + + it('query', function(){ + var q = mquery({ color: '#fff' }); + var m = mquery(col).remove({ name: 'Whiskers' }); + m.remove(q) + assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); + }) + + it('function', function(done){ + mquery(col, { safe: true }).where({name: name}).remove(function (err) { + assert.ifError(err); + mquery(col).findOne({ name: name }, function (err, doc) { + assert.ifError(err); + assert.equal(null, doc); + done(); + }) + }); + }) + + it('boolean (true) - execute', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + mquery(col).findOne({ name: name }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + mquery(col).remove(true); + setTimeout(function () { + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(0, docs.length); + done(); + }) + }, 300) + }) + }) + }) + }) + }) + + describe('with 2 arguments', function(){ + var name = 'remove: 2 arg test' + beforeEach(function(done){ + col.remove({}, { safe: true }, function (err) { + assert.ifError(err); + col.insert([{ name: 'shelly' }, { name: name }], { safe: true }, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + }) + }) + + describe('plain object + callback', function(){ + it('works', function(done){ + mquery(col).remove({ name: name }, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(1, docs.length); + assert.equal('shelly', docs[0].name); + done(); + }) + }); + }) + }) + + describe('mquery + callback', function(){ + it('works', function(done){ + var m = mquery({ name: name }); + mquery(col).remove(m, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(1, docs.length); + assert.equal('shelly', docs[0].name); + done(); + }) + }); + }) + }) + }) + }) + + function validateFindAndModifyOptions (method) { + describe('validates its option', function(){ + it('sort', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().sort('x')[method](); + }) + done(); + }) + + it('select', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().select('x')[method](); + }) + done(); + }) + + it('limit', function(done){ + assert.throws(function(){ + var m = mquery().limit(3)[method](); + }, new RegExp('limit cannot be used with ' + method)); + done(); + }) + + it('skip', function(done){ + assert.throws(function(){ + var m = mquery().skip(3)[method](); + }, new RegExp('skip cannot be used with ' + method)); + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 })[method](); + }, new RegExp('batchSize cannot be used with ' + method)); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300)[method](); + }, new RegExp('maxScan cannot be used with ' + method)); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot()[method](); + }, new RegExp('snapshot cannot be used with ' + method)); + done(); + }) + + it('hint', function(done){ + assert.throws(function(){ + var m = mquery().hint({ x: 1 })[method](); + }, new RegExp('hint cannot be used with ' + method)); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable()[method](); + }, new RegExp('tailable cannot be used with ' + method)); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery')[method](); + }, new RegExp('comment cannot be used with ' + method)); + done(); + }) + }) + } + + describe('findOneAndUpdate', function(){ + var name = 'findOneAndUpdate + fn' + + validateFindAndModifyOptions('findOneAndUpdate'); + + describe('with 0 args', function(){ + it('makes no changes', function(){ + var m = mquery(); + var n = m.findOneAndUpdate(); + assert.deepEqual(m, n); + }) + }) + describe('with 1 arg', function(){ + describe('that is an object', function(){ + it('updates the doc', function(){ + var m = mquery(); + var n = m.findOneAndUpdate({ $set: { name: '1 arg' }}); + assert.deepEqual(n._update, { $set: { name: '1 arg' }}); + }) + }) + describe('that is a query', function(){ + it('updates the doc', function(){ + var m = mquery({ name: name }).update({ x: 1 }); + var n = mquery().findOneAndUpdate(m); + assert.deepEqual(n._update, { x: 1 }); + }) + }) + it('that is a function', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery({ name: name }).collection(col); + name = '1 arg'; + var n = m.update({ $set: { name: name }}); + n.findOneAndUpdate(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + describe('with 2 args', function(){ + it('conditions + update', function(){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { age: 100 }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ age: 100 }, m._update); + }) + it('query + update', function(){ + var n = mquery({ name: name }); + var m = mquery(col); + m.findOneAndUpdate(n, { age: 100 }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ age: 100 }, m._update); + }) + it('update + callback', function(done){ + var m = mquery(col).where({ name: name }); + m.findOneAndUpdate({ $inc: { age: 10 }}, function (err, doc) { + assert.ifError(err); + assert.equal(10, doc.age); + done(); + }); + }) + }) + describe('with 3 args', function(){ + it('conditions + update + options', function(){ + var m = mquery(); + var n = m.findOneAndUpdate({ name: name }, { works: true }, { new: false }); + assert.deepEqual({ name: name}, n._conditions); + assert.deepEqual({ works: true }, n._update); + assert.deepEqual({ new: false }, n.options); + }) + it('conditions + update + callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { works: true }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + assert.ok(true === doc.works); + done(); + }); + }) + }) + describe('with 4 args', function(){ + it('conditions + update + options + callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { works: false }, { new: false }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + assert.ok(true === doc.works); + done(); + }); + }) + }) + }) + + describe('findOneAndRemove', function(){ + var name = 'findOneAndRemove' + + validateFindAndModifyOptions('findOneAndRemove'); + + describe('with 0 args', function(){ + it('makes no changes', function(){ + var m = mquery(); + var n = m.findOneAndRemove(); + assert.deepEqual(m, n); + }) + }) + describe('with 1 arg', function(){ + describe('that is an object', function(){ + it('updates the doc', function(){ + var m = mquery(); + var n = m.findOneAndRemove({ name: '1 arg' }); + assert.deepEqual(n._conditions, { name: '1 arg' }); + }) + }) + describe('that is a query', function(){ + it('updates the doc', function(){ + var m = mquery({ name: name }); + var n = m.findOneAndRemove(m); + assert.deepEqual(n._conditions, { name: name }); + }) + }) + it('that is a function', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery({ name: name }).collection(col); + m.findOneAndRemove(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + describe('with 2 args', function(){ + it('conditions + options', function(){ + var m = mquery(col); + m.findOneAndRemove({ name: name }, { new: false }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ new: false }, m.options); + }) + it('query + options', function(){ + var n = mquery({ name: name }); + var m = mquery(col); + m.findOneAndRemove(n, { sort: { x: 1 }}); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ sort: { 'x': 1 }}, m.options); + }) + it('conditions + callback', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery(col); + m.findOneAndRemove({ name: name }, function (err, doc) { + assert.ifError(err); + assert.equal(name, doc.name); + done(); + }); + }); + }) + it('query + callback', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var n = mquery({ name: name }) + var m = mquery(col); + m.findOneAndRemove(n, function (err, doc) { + assert.ifError(err); + assert.equal(name, doc.name); + done(); + }); + }); + }) + }) + describe('with 3 args', function(){ + it('conditions + options + callback', function(done){ + name = 'findOneAndRemove + conds + options + cb'; + col.insert([{ name: name }, { name: 'a' }], { safe: true }, function (err) { + assert.ifError(err); + var m = mquery(col); + m.findOneAndRemove({ name: name }, { sort: { name: 1 }}, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + }) + + describe('exec', function(){ + beforeEach(function(done){ + col.insert([{ name: 'exec', age: 1 }, { name: 'exec', age: 2 }], done); + }) + + afterEach(function(done){ + mquery(col).remove(done); + }) + + it('requires an op', function(){ + assert.throws(function () { + mquery().exec() + }, /Missing query type/); + }) + + describe('find', function() { + it('works', function(done){ + var m = mquery(col).find({ name: 'exec' }); + m.exec(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + + it('works with readPreferences', function (done) { + var m = mquery(col).find({ name: 'exec' }); + try { + var rp = new require('mongodb').ReadPreference('primary'); + m.read(rp); + } catch (e) { + if (e.code === 'MODULE_NOT_FOUND') + e = null; + done(e); + return; + } + m.exec(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + }); + + it('findOne', function(done){ + var m = mquery(col).findOne({ age: 2 }); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal(2, doc.age); + done(); + }) + }) + + it('count', function(done){ + var m = mquery(col).count({ name: 'exec' }); + m.exec(function (err, count) { + assert.ifError(err); + assert.equal(2, count); + done(); + }) + }) + + it('distinct', function(done){ + var m = mquery({ name: 'exec' }); + m.collection(col); + m.distinct('age'); + m.exec(function (err, array) { + assert.ifError(err); + assert.ok(Array.isArray(array)); + assert.equal(2, array.length); + assert(~array.indexOf(1)); + assert(~array.indexOf(2)); + done(); + }); + }) + + describe('update', function(){ + var num; + + it('with a callback', function(done){ + var m = mquery(col); + m.where({ name: 'exec' }) + + m.count(function (err, _num) { + assert.ifError(err); + num = _num; + m.setOptions({ multi: true }) + m.update({ name: 'exec + update' }); + m.exec(function (err, res) { + assert.ifError(err); + assert.equal(num, res); + mquery(col).find({ name: 'exec + update' }, function (err, docs) { + assert.ifError(err); + assert.equal(num, docs.length); + done(); + }) + }) + }) + }) + + it('without a callback', function(done){ + var m = mquery(col) + m.where({ name: 'exec + update' }).setOptions({ multi: true }) + m.update({ name: 'exec' }); + + // unsafe write + m.exec(); + + setTimeout(function () { + mquery(col).find({ name: 'exec' }, function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }, 200) + }) + it('preserves key ordering', function(done) { + var m = mquery(col); + + var m2 = m.update({ _id : 'something' }, { '1' : 1, '2' : 2, '3' : 3}); + var doc = m2._updateForExec().$set; + var count = 0; + for (var i in doc) { + if (count == 0) { + assert.equal('1', i); + } else if (count == 1) { + assert.equal('2', i); + } else if (count ==2) { + assert.equal('3', i); + } + count++; + } + done(); + }); + }) + + describe('remove', function(){ + it('with a callback', function(done){ + var m = mquery(col).where({ age: 2 }).remove(); + m.exec(function (err, num) { + assert.ifError(err); + assert.equal(1, num); + done(); + }) + }) + + it('without a callback', function(done){ + var m = mquery(col).where({ age: 1 }).remove(); + m.exec(); + + setTimeout(function () { + mquery(col).where('name', 'exec').count(function(err, num) { + assert.equal(1, num); + done(); + }) + }, 200) + }) + }) + + describe('findOneAndUpdate', function(){ + it('with a callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: 'exec', age: 1 }, { $set: { name: 'findOneAndUpdate' }}); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal('findOneAndUpdate', doc.name); + done(); + }); + }) + }) + + describe('findOneAndRemove', function(){ + it('with a callback', function(done){ + var m = mquery(col); + m.findOneAndRemove({ name: 'exec', age: 2 }); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal('exec', doc.name); + assert.equal(2, doc.age); + mquery(col).count({ name: 'exec' }, function (err, num) { + assert.ifError(err); + assert.equal(1, num); + done(); + }); + }); + }) + }) + }) + + describe('setTraceFunction', function() { + beforeEach(function(done){ + col.insert([{ name: 'trace', age: 93 }], done); + }) + + it('calls trace function when executing query', function(done) { + var m = mquery(col); + + var resultTraceCalled; + + m.setTraceFunction(function (method, queryInfo) { + try { + assert.equal('findOne', method); + assert.equal('trace', queryInfo.conditions.name); + } catch (e) { + done(e); + } + + return function(err, result, millis) { + try { + assert.equal(93, result.age); + } catch (e) { + done(e); + } + resultTraceCalled = true; + }; + }); + + m.findOne({name: 'trace'}, function (err, doc) { + assert.ifError(err); + assert.equal(resultTraceCalled, true); + assert.equal(93, doc.age); + done(); + }); + }); + + it('inherits trace function when calling toConstructor', function(done) { + function traceFunction () { return function() {} }; + + var tracedQuery = mquery().setTraceFunction(traceFunction).toConstructor(); + + var query = tracedQuery(); + assert.equal(traceFunction, query._traceFunction); + + done(); + }); + }); + + describe('thunk', function() { + it('returns a function', function(done) { + assert.equal('function', typeof mquery().thunk()); + done(); + }); + + it('passes the fn arg to `exec`', function(done) { + function cb() {} + var m = mquery(); + + m.exec = function testing(fn) { + assert.equal(this, m); + assert.equal(cb, fn); + done(); + } + + m.thunk()(cb); + }); + }); + + describe('then', function() { + before(function(done){ + col.insert([{ name: 'then', age: 1 }, { name: 'then', age: 2 }], done); + }) + + after(function(done){ + mquery(col).remove({ name: 'then' }).exec(done); + }) + + it('returns a promise A+ compat object', function(done) { + var m = mquery(col).find(); + assert.equal('function', typeof m.then); + done(); + }); + + it('creates a promise that is resolved on success', function(done) { + var promise = mquery(col).count({ name: 'then' }).then(); + promise.then(function(count){ + assert.equal(2, count); + done(); + }, done); + }); + + it('supports exec() cb being called synchronously #66', function(done) { + var query = mquery(col).count({ name: 'then' }); + query.exec = function(cb) { + cb(null, 66); + } + + query.then(success, done); + function success(count){ + assert.equal(66, count); + done(); + } + }); + + it('supports other Promise libs', function(done) { + var bluebird = mquery.Promise; + + // hack for testing + mquery.Promise = function P() { + mquery.Promise = bluebird; + this.then = function(x, y) { + return x + y; + } + } + + var val = mquery(col).count({ name: 'exec' }).then(1, 2); + assert.equal(val, 3); + done(); + }); + }); + + describe('stream', function() { + before(function(done){ + col.insert([{ name: 'stream', age: 1 }, { name: 'stream', age: 2 }], done); + }) + + after(function(done){ + mquery(col).remove({ name: 'stream' }).exec(done); + }) + + describe('throws', function() { + describe('if used with non-find operations', function() { + var ops = ['update', 'findOneAndUpdate', 'remove', 'count', 'distinct']; + + ops.forEach(function(op) { + assert.throws(function(){ + mquery(col)[op]().stream(); + }); + }); + }); + }); + + it('returns a stream', function(done) { + var stream = mquery(col).find({ name: 'stream' }).stream(); + var count = 0; + var err; + + stream.on('data', function(doc){ + assert.equal('stream', doc.name); + ++count; + }); + + stream.on('error', function(er) { + err = er; + }); + + stream.on('close', function(){ + if (err) return done(err); + assert.equal(2, count); + done(); + }); + }); + + it('supports find options', function(done) { + var stream = mquery(col) + .find({ name: 'stream' }) + .limit(1) + .select('-_id') + .stream({ transform: xform }); + + function xform(doc) { + doc.name = doc.name + '-xformed'; + return doc; + } + + var count = 0; + var err; + + stream.on('data', function(doc){ + assert(!doc._id); + assert.equal('stream-xformed', doc.name); + ++count; + }); + + stream.on('error', function(er) { + err = er; + }); + + stream.on('close', function(){ + if (err) return done(err); + assert.equal(1, count); + done(); + }); + }); + + }); + + function noDistinct (type) { + it('cannot be used with distinct()', function(done){ + assert.throws(function () { + mquery().distinct('name')[type](4); + }, new RegExp(type + ' cannot be used with distinct')); + done(); + }) + } + + function no (method, type) { + it('cannot be used with ' + method + '()', function(done){ + assert.throws(function () { + mquery()[method]()[type](4); + }, new RegExp(type + ' cannot be used with ' + method)); + done(); + }) + } + + // query internal + + describe('_updateForExec', function(){ + it('returns a clone of the update object with same key order #19', function(done){ + var update = {}; + update.$push = { n: { $each: [{x:10}], $slice: -1, $sort: {x:1}}}; + + var q = mquery().update({ x: 1 }, update); + + // capture original key order + var order = []; + for (var key in q._update.$push.n) { + order.push(key); + } + + // compare output + var doc = q._updateForExec(); + var i = 0; + for (var key in doc.$push.n) { + assert.equal(key, order[i]); + i++; + } + + done(); + }) + }) +}) diff --git a/5-3/node_modules/mongoose/node_modules/mquery/test/utils.test.js b/5-3/node_modules/mongoose/node_modules/mquery/test/utils.test.js new file mode 100644 index 0000000..fa5972a --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/mquery/test/utils.test.js @@ -0,0 +1,143 @@ + +var utils = require('../lib/utils'); +var assert = require('assert'); + +var mongo; +try { + mongo = new require('mongodb'); +} catch (e) {} + +describe('lib/utils', function() { + describe('clone', function() { + it('clones constructors named ObjectId', function(done) { + function ObjectId (id) { + this.id = id; + } + + var o1 = new ObjectId('1234'); + var o2 = utils.clone(o1); + assert.ok(o2 instanceof ObjectId); + + done(); + }); + + it('clones constructors named ObjectID', function(done) { + function ObjectID (id) { + this.id = id; + } + + var o1 = new ObjectID('1234'); + var o2 = utils.clone(o1); + + assert.ok(o2 instanceof ObjectID); + done(); + }); + + it('does not clone constructors named ObjectIdd', function(done) { + function ObjectIdd (id) { + this.id = id; + } + + var o1 = new ObjectIdd('1234'); + var o2 = utils.clone(o1); + assert.ok(!(o2 instanceof ObjectIdd)); + + done(); + }); + + it('optionally clones ObjectId constructors using its clone method', function(done) { + function ObjectID (id) { + this.id = id; + this.cloned = false; + } + + ObjectID.prototype.clone = function () { + var ret = new ObjectID(this.id); + ret.cloned = true; + return ret; + } + + var id = 1234; + var o1 = new ObjectID(id); + assert.equal(id, o1.id); + assert.equal(false, o1.cloned); + + var o2 = utils.clone(o1); + assert.ok(o2 instanceof ObjectID); + assert.equal(id, o2.id); + assert.ok(o2.cloned); + done(); + }); + + it('clones mongodb.ReadPreferences', function (done) { + if (!mongo) return done(); + + var tags = [ + {dc: 'tag1'} + ]; + var prefs = [ + new mongo.ReadPreference("primary"), + new mongo.ReadPreference(mongo.ReadPreference.PRIMARY_PREFERRED), + new mongo.ReadPreference("primary", tags), + mongo.ReadPreference("primary", tags) + ]; + + var prefsCloned = utils.clone(prefs); + + for (var i = 0; i < prefsCloned.length; i++) { + assert.notEqual(prefs[i], prefsCloned[i]); + assert.ok(prefsCloned[i] instanceof mongo.ReadPreference); + assert.ok(prefsCloned[i].isValid()); + if (prefs[i].tags) { + assert.ok(prefsCloned[i].tags); + assert.notEqual(prefs[i].tags, prefsCloned[i].tags); + assert.notEqual(prefs[i].tags[0], prefsCloned[i].tags[0]); + } else { + assert.equal(prefsCloned[i].tags, null); + } + } + + done(); + }); + + it('clones mongodb.Binary', function(done){ + if (!mongo) return done(); + + var buf = new Buffer('hi'); + var binary= new mongo.Binary(buf, 2); + var clone = utils.clone(binary); + assert.equal(binary.sub_type, clone.sub_type); + assert.equal(String(binary.buffer), String(buf)); + assert.ok(binary !== clone); + done(); + }) + + it('handles objects with no constructor', function(done) { + var name ='335'; + + var o = Object.create(null); + o.name = name; + + var clone; + assert.doesNotThrow(function() { + clone = utils.clone(o); + }); + + assert.equal(name, clone.name); + assert.ok(o != clone); + done(); + }); + + it('handles buffers', function(done){ + var buff = new Buffer(10); + buff.fill(1); + var clone = utils.clone(buff); + + for (var i = 0; i < buff.length; i++) { + assert.equal(buff[i], clone[i]); + } + + done(); + }); + }); +}); diff --git a/5-3/node_modules/mongoose/node_modules/ms/.npmignore b/5-3/node_modules/mongoose/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/5-3/node_modules/mongoose/node_modules/ms/History.md b/5-3/node_modules/mongoose/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/5-3/node_modules/mongoose/node_modules/ms/LICENSE b/5-3/node_modules/mongoose/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/5-3/node_modules/mongoose/node_modules/ms/README.md b/5-3/node_modules/mongoose/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/5-3/node_modules/mongoose/node_modules/ms/index.js b/5-3/node_modules/mongoose/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/5-3/node_modules/mongoose/node_modules/ms/package.json b/5-3/node_modules/mongoose/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/muri/.npmignore b/5-3/node_modules/mongoose/node_modules/muri/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/muri/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/5-3/node_modules/mongoose/node_modules/muri/.travis.yml b/5-3/node_modules/mongoose/node_modules/muri/.travis.yml new file mode 100644 index 0000000..895dbd3 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/muri/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/5-3/node_modules/mongoose/node_modules/muri/History.md b/5-3/node_modules/mongoose/node_modules/muri/History.md new file mode 100644 index 0000000..87b7053 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/muri/History.md @@ -0,0 +1,52 @@ + +1.0.0 / 2014-10-18 +================== + + * fixed; compatibility w/ strict mode #4 [vkarpov15](https://github.com/vkarpov15) + +0.3.1 / 2013-02-17 +================== + + * fixed; allow '#' in username and password #3 + +0.3.0 / 2013-01-14 +================== + + * fixed; default db logic #2 + +0.2.0 / 2013-01-09 +================== + + * changed; default db is now 'test' + +0.1.0 / 2012-12-18 +================== + + * changed; include .sock in UDS + +0.0.5 / 2012-12-18 +================== + + * fixed; unix domain sockets used with db names + +0.0.4 / 2012-12-01 +================== + + * handle multple specified protocols + +0.0.3 / 2012-11-29 +================== + + * validate mongodb:///db + * more detailed error message + +0.0.2 / 2012-11-02 +================== + + * add readPreferenceTags support + * add unix domain support + +0.0.1 / 2012-11-01 +================== + + * initial release diff --git a/5-3/node_modules/mongoose/node_modules/muri/LICENSE b/5-3/node_modules/mongoose/node_modules/muri/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/muri/LICENSE @@ -0,0 +1,22 @@ +(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/5-3/node_modules/mongoose/node_modules/muri/Makefile b/5-3/node_modules/mongoose/node_modules/muri/Makefile new file mode 100644 index 0000000..e6337bd --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/muri/Makefile @@ -0,0 +1,5 @@ + +test: + @node_modules/mocha/bin/mocha $(T) + +.PHONY: test diff --git a/5-3/node_modules/mongoose/node_modules/muri/README.md b/5-3/node_modules/mongoose/node_modules/muri/README.md new file mode 100644 index 0000000..3757419 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/muri/README.md @@ -0,0 +1,46 @@ +#Meet Muri! + +Muri is your friendly neighborhood [MongoDB URI](http://www.mongodb.org/display/DOCS/Connections) parser for Node.js. + + +###Install + + $ npm install muri + +###Use + +```js + var muri = require('muri'); + var o = muri('mongodb://user:pass@local,remote:27018,japan:27019/neatdb?replicaSet=myreplset&journal=true&w=2&wtimeoutMS=50'); + + console.log(o); + + { hosts: [ { host: 'local', port: 27017 }, + { host: 'remote', port: 27018 }, + { host: 'japan', port: 27019 } ], + db: 'neatdb', + options: { + replicaSet: 'myreplset', + journal: true, + w: 2, + wtimeoutMS: 50 + }, + auth: { + user: 'user', + pass: 'pass' + } + } +``` + +### Details + +The returned object contains the following properties: + +- db: the name of the database. defaults to "admin" if not specified +- auth: if auth is specified, this object will exist `{ user: 'username', pass: 'password' }` +- hosts: array of host/port objects, one for each specified `[{ host: 'local', port: 27107 }, { host: '..', port: port }]` + - if a port is not specified for a given host, the default port (27017) is used + - if a unix domain socket is passed, host/port will be undefined and `ipc` will be set to the value specified `[{ ipc: '/tmp/mongodb-27017' }]` +- options: this is a hash of all options specified in the querystring + +[LICENSE](https://github.com/aheckmann/muri/blob/master/LICENSE) diff --git a/5-3/node_modules/mongoose/node_modules/muri/index.js b/5-3/node_modules/mongoose/node_modules/muri/index.js new file mode 100644 index 0000000..f7b65dd --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/muri/index.js @@ -0,0 +1 @@ +module.exports = exports = require('./lib'); diff --git a/5-3/node_modules/mongoose/node_modules/muri/lib/index.js b/5-3/node_modules/mongoose/node_modules/muri/lib/index.js new file mode 100644 index 0000000..59cb396 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/muri/lib/index.js @@ -0,0 +1,241 @@ +// muri + +/** + * MongoDB URI parser as described here: + * http://www.mongodb.org/display/DOCS/Connections + */ + +/** + * Module dependencies + */ + +var qs = require('querystring'); + +/** + * Defaults + */ + +var DEFAULT_PORT = 27017; +var DEFAULT_DB = 'test'; +var ADMIN_DB = 'admin'; + +/** + * Muri + */ + +module.exports = exports = function muri (str) { + if (!/^mongodb:\/\//.test(str)) { + throw new Error('Invalid mongodb uri. Must begin with "mongodb://"' + + '\n Received: ' + str); + } + + var ret = { + hosts: [] + , db: DEFAULT_DB + , options: {} + } + + var match = /^mongodb:\/\/([^?]+)(\??.*)$/.exec(str); + if (!match || '/' == match[1]) { + throw new Error('Invalid mongodb uri. Missing hostname'); + } + + var uris = match[1]; + var path = match[2]; + var db; + + uris.split(',').forEach(function (uri) { + var o = parse(uri); + + if (o.host) { + ret.hosts.push({ + host: o.host + , port: parseInt(o.port, 10) + }) + + if (!db && o.db) { + db = o.db; + } + } else if (o.ipc) { + ret.hosts.push({ ipc: o.ipc }); + } + + if (o.auth) { + ret.auth = { + user: o.auth.user + , pass: o.auth.pass + } + } + }) + + if (!ret.hosts.length) { + throw new Error('Invalid mongodb uri. Missing hostname'); + } + + var parts = path.split('?'); + + if (!db) { + if (parts[0]) { + db = parts[0].replace(/^\//, ''); + } else { + // deal with ipc formats + db = /\/([^\.]+)$/.exec(match[1]); + if (db && db[1]) { + db = db[1]; + } + } + } + + if (db) { + ret.db = db; + } else if (ret.auth) { + ret.db = ADMIN_DB; + } + + if (parts[1]) { + ret.options = options(parts[1]); + } + + return ret; +} + +/** + * Parse str into key/val pairs casting values appropriately. + */ + +function options (str) { + var sep = /;/.test(str) + ? ';' + : '&'; + + var ret = qs.parse(str, sep); + + Object.keys(ret).forEach(function (key) { + var val = ret[key]; + if ('readPreferenceTags' == key) { + val = readPref(val); + if (val) { + ret[key] = Array.isArray(val) + ? val + : [val]; + } + } else { + ret[key] = format(val); + } + }); + + return ret; +} + +function format (val) { + var num; + + if ('true' == val) { + return true; + } else if ('false' == val) { + return false; + } else { + num = parseInt(val, 10); + if (!isNaN(num)) { + return num; + } + } + + return val; +} + +function readPref (val) { + var ret; + + if (Array.isArray(val)) { + ret = val.map(readPref).filter(Boolean); + return ret.length + ? ret + : undefined + } + + var pair = val.split(','); + var hasKeys; + ret = {}; + + pair.forEach(function (kv) { + kv = (kv || '').trim(); + if (!kv) return; + hasKeys = true; + var split = kv.split(':'); + ret[split[0]] = format(split[1]); + }); + + return hasKeys && ret; +} + +var ipcRgx = /\.sock/; + +function parse (uriString) { + // do not use require('url').parse b/c it can't handle # in username or pwd + // mongo uris are strange + + var uri = uriString; + var ret = {}; + var parts; + var auth; + var ipcs; + + // skip protocol + uri = uri.replace(/^mongodb:\/\//, ''); + + // auth + if (/@/.test(uri)) { + parts = uri.split(/@/); + auth = parts[0]; + uri = parts[1]; + + parts = auth.split(':'); + ret.auth = {}; + ret.auth.user = parts[0]; + ret.auth.pass = parts[1]; + } + + // unix domain sockets + if (ipcRgx.test(uri)) { + ipcs = uri.split(ipcRgx); + ret.ipc = ipcs[0] + '.sock'; + + // included a database? + if (ipcs[1]) { + // strip leading / from database name + ipcs[1] = ipcs[1].replace(/^\//, ''); + + if (ipcs[1]) { + ret.db = ipcs[1]; + } + } + + return ret; + } + + // database name + parts = uri.split('/'); + if (parts[1]) ret.db = parts[1]; + + // ipv6, [ip]:host + if (/^\[[^\]]+\]:\d+/.test(parts[0])) { + ret.host = parts[0].substring(1, parts[0].indexOf(']:')); + ret.port = parts[0].substring(parts[0].indexOf(']:') + ']:'.length); + } else { + // host:port + parts = parts[0].split(':'); + ret.host = parts[0]; + ret.port = parts[1] || DEFAULT_PORT; + } + + return ret; +} + +/** + * Version + */ + +module.exports.version = JSON.parse( + require('fs').readFileSync(__dirname + '/../package.json', 'utf8') +).version; diff --git a/5-3/node_modules/mongoose/node_modules/muri/package.json b/5-3/node_modules/mongoose/node_modules/muri/package.json new file mode 100644 index 0000000..1d8e74d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/muri/package.json @@ -0,0 +1,57 @@ +{ + "name": "muri", + "version": "1.1.0", + "description": "MongoDB URI parser", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/muri.git" + }, + "keywords": [ + "mongodb", + "uri", + "parser" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.21.5" + }, + "gitHead": "8f373948ef317865044994aaa98a013e769b2952", + "bugs": { + "url": "https://github.com/aheckmann/muri/issues" + }, + "homepage": "https://github.com/aheckmann/muri", + "_id": "muri@1.1.0", + "_shasum": "a3a6d74e68a880f433a249a74969cbb665cc0add", + "_from": "muri@1.1.0", + "_npmVersion": "2.5.1", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "vkarpov15", + "email": "val@karpov.io" + } + ], + "dist": { + "shasum": "a3a6d74e68a880f433a249a74969cbb665cc0add", + "tarball": "http://registry.npmjs.org/muri/-/muri-1.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/muri/-/muri-1.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/node_modules/muri/test/index.js b/5-3/node_modules/mongoose/node_modules/muri/test/index.js new file mode 100644 index 0000000..65a4cfc --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/muri/test/index.js @@ -0,0 +1,321 @@ + +var muri = require('../') +var assert = require('assert') + +describe('muri', function(){ + it('must begin with mongodb://', function(done){ + assert.throws(function () { + muri('localhost:27017'); + }, /Invalid mongodb uri/); + assert.doesNotThrow(function () { + muri('mongodb://localhost:27017'); + }) + done(); + }) + + describe('user:password', function(done){ + it('is optional', function(done){ + var uri = 'mongodb://local:27017'; + var val = muri(uri); + assert.ok(!val.auth); + done(); + }) + + it('parses properly', function(done){ + var uri = 'mongodb://user:password@local:27017'; + var val = muri(uri); + assert.ok(val.auth); + assert.equal('user', val.auth.user); + assert.equal('password', val.auth.pass); + done(); + }) + + it('handles # in the username', function(done){ + var uri = 'mongodb://us#er:password@local:27017'; + var val = muri(uri); + assert.ok(val.auth); + assert.equal('us#er', val.auth.user); + assert.equal('password', val.auth.pass); + done(); + }) + + it('handles # in the password', function(done){ + var uri = 'mongodb://user:pa#ssword@local:27017'; + var val = muri(uri); + assert.ok(val.auth); + assert.equal('user', val.auth.user); + assert.equal('pa#ssword', val.auth.pass); + done(); + }) + }) + + describe('host', function(){ + it('must be specified', function(done){ + assert.throws(function () { + muri('mongodb://'); + }, /Missing host/) + assert.throws(function () { + muri('mongodb:///fake'); + }, /Missing host/) + assert.throws(function () { + muri('mongodb://?yep'); + }, /Missing host/) + assert.throws(function () { + muri('mongodb:///?yep'); + }, /Missing host/) + + var val = muri('mongodb://local'); + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal('local', val.hosts[0].host); + done(); + }) + + it('supports replica sets', function(done){ + var val = muri('mongodb://local:27017,remote:27018,japan:99999'); + assert.ok(Array.isArray(val.hosts)); + assert.equal(3, val.hosts.length); + assert.equal('local', val.hosts[0].host); + assert.equal(27017, val.hosts[0].port); + assert.equal('remote', val.hosts[1].host); + assert.equal(27018, val.hosts[1].port); + assert.equal('japan', val.hosts[2].host); + assert.equal(99999, val.hosts[2].port); + done(); + }) + }) + + describe('port', function(){ + + describe('with single host', function(){ + it('defaults to 27017 if not specified', function(done){ + var val = muri('mongodb://local/'); + assert.equal(27017, val.hosts[0].port); + done(); + }) + + it('uses what is specified', function(done){ + var val = muri('mongodb://local:27018'); + assert.equal(27018, val.hosts[0].port); + done(); + }) + }) + + describe('with replica sets', function(){ + var val; + + before(function(){ + val = muri('mongodb://local,remote:27018,another'); + }) + + it('defaults to 27017 if not specified', function(done){ + assert.equal(27017, val.hosts[0].port); + assert.equal(27017, val.hosts[2].port); + done(); + }) + + it('uses what is specified', function(done){ + assert.equal(27018, val.hosts[1].port); + done(); + }) + }) + }) + + describe('database', function(){ + it('default', function(done){ + var val = muri('mongodb://localhost/'); + assert.equal('test', val.db); + var val = muri('mongodb://localhost'); + assert.equal('test', val.db); + done(); + }) + it('is overridable', function(done){ + var val = muri('mongodb://localhost,a,x:34343,b/muri'); + assert.equal('muri', val.db); + done(); + }) + it('works with multiple specified protocols', function(done){ + var uri = 'mongodb://localhost:27020/testing,mongodb://localhost:27019,mongodb://localhost:27018' + var val = muri(uri); + assert.equal('testing', val.db); + done(); + }) + }) + + describe('querystring separator', function(){ + it('can be ; ', function(done){ + var val = muri('mongodb://muri/?replicaSet=myreplset;slaveOk=true;x=1'); + assert.ok(val.options); + assert.equal(true, val.options.slaveOk); + assert.equal('myreplset', val.options.replicaSet); + assert.equal(1, val.options.x); + done(); + }) + it('can be & ', function(done){ + var val = muri('mongodb://muri/?replicaSet=myreplset&slaveOk=true&x=1'); + assert.ok(val.options); + assert.equal(true, val.options.slaveOk); + assert.equal('myreplset', val.options.replicaSet); + assert.equal(1, val.options.x); + done(); + }) + }) + + describe('readPref tags', function(){ + describe('with & ', function(){ + it('mongodb://localhost/?readPreferenceTags=dc:ny', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny'); + assert.equal('test', val.db); + assert.deepEqual([{ dc: 'ny' }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1'); + assert.deepEqual([{ dc: 'ny', rack: 1 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2'); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2&readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2&readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny&readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny&readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'ny' }], val.options.readPreferenceTags); + done(); + }) + }) + describe('with ; ', function(){ + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2'); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2;readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2;readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'ny' }], val.options.readPreferenceTags); + done(); + }) + }) + }) + + describe('unix domain sockets', function(){ + it('without auth', function(done){ + var val = muri('mongodb:///tmp/mongodb-27017.sock?safe=false'); + assert.equal(val.db, 'test') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('without auth with a database name', function(done){ + var val = muri('mongodb:///tmp/mongodb-27017.sock/tester?safe=false'); + assert.equal(val.db, 'tester') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock?safe=false'); + assert.equal(val.db, 'admin') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth with a db name', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock/tester?safe=false'); + assert.equal(val.db, 'tester') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth + repl sets', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock,/tmp/another-27018.sock?safe=false'); + assert.equal(val.db, 'admin') + assert.ok(Array.isArray(val.hosts)); + assert.equal(2, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(val.hosts[1].ipc, '/tmp/another-27018.sock') + assert.equal(val.hosts[1].host, undefined); + assert.equal(val.hosts[1].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth + repl sets with a db name', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock,/tmp/another-27018.sock/tester?safe=false'); + assert.equal(val.db, 'tester') + assert.ok(Array.isArray(val.hosts)); + assert.equal(2, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(val.hosts[1].ipc, '/tmp/another-27018.sock') + assert.equal(val.hosts[1].host, undefined); + assert.equal(val.hosts[1].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + }) + + it('all together now', function(done){ + var uri = 'mongodb://u#ser:pas#s@local,remote:27018,japan:27019/neatdb' + uri += '?replicaSet=myreplset&journal=true&w=2&wtimeoutMS=50' + var val = muri(uri); + + assert.equal('u#ser', val.auth.user); + assert.equal('pas#s', val.auth.pass); + assert.equal('neatdb', val.db); + assert.equal(3, val.hosts.length); + assert.equal('local', val.hosts[0].host); + assert.strictEqual(27017, val.hosts[0].port); + assert.equal('remote', val.hosts[1].host); + assert.strictEqual(27018, val.hosts[1].port); + assert.equal('japan', val.hosts[2].host); + assert.strictEqual(27019, val.hosts[2].port); + assert.equal('myreplset', val.options.replicaSet); + assert.equal(true, val.options.journal); + assert.equal(50, val.options.wtimeoutMS); + done(); + }); + + it('ipv6', function(done) { + var uri = 'mongodb://[::1]:27017/test'; + var val = muri(uri); + assert.equal(1, val.hosts.length); + assert.equal('::1', val.hosts[0].host); + assert.equal(27017, val.hosts[0].port); + done(); + }); + + it('has a version', function(done){ + assert.ok(muri.version); + done(); + }) +}) diff --git a/5-3/node_modules/mongoose/node_modules/regexp-clone/.npmignore b/5-3/node_modules/mongoose/node_modules/regexp-clone/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/regexp-clone/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/5-3/node_modules/mongoose/node_modules/regexp-clone/.travis.yml b/5-3/node_modules/mongoose/node_modules/regexp-clone/.travis.yml new file mode 100644 index 0000000..58f2371 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/regexp-clone/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.6 + - 0.8 + - 0.10 diff --git a/5-3/node_modules/mongoose/node_modules/regexp-clone/History.md b/5-3/node_modules/mongoose/node_modules/regexp-clone/History.md new file mode 100644 index 0000000..0beedfc --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/regexp-clone/History.md @@ -0,0 +1,5 @@ + +0.0.1 / 2013-04-17 +================== + + * initial commit diff --git a/5-3/node_modules/mongoose/node_modules/regexp-clone/LICENSE b/5-3/node_modules/mongoose/node_modules/regexp-clone/LICENSE new file mode 100644 index 0000000..98c7c89 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/regexp-clone/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 [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/5-3/node_modules/mongoose/node_modules/regexp-clone/Makefile b/5-3/node_modules/mongoose/node_modules/regexp-clone/Makefile new file mode 100644 index 0000000..6c8fb75 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/regexp-clone/Makefile @@ -0,0 +1,5 @@ + +test: + @./node_modules/.bin/mocha $(T) --async-only $(TESTS) + +.PHONY: test diff --git a/5-3/node_modules/mongoose/node_modules/regexp-clone/README.md b/5-3/node_modules/mongoose/node_modules/regexp-clone/README.md new file mode 100644 index 0000000..2aabe5c --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/regexp-clone/README.md @@ -0,0 +1,18 @@ +#regexp-clone +============== + +Clones RegExps with flag preservation + +```js +var regexpClone = require('regexp-clone'); + +var a = /somethin/g; +console.log(a.global); // true + +var b = regexpClone(a); +console.log(b.global); // true +``` + +## License + +[MIT](https://github.com/aheckmann/regexp-clone/blob/master/LICENSE) diff --git a/5-3/node_modules/mongoose/node_modules/regexp-clone/index.js b/5-3/node_modules/mongoose/node_modules/regexp-clone/index.js new file mode 100644 index 0000000..e5850ca --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/regexp-clone/index.js @@ -0,0 +1,20 @@ + +var toString = Object.prototype.toString; + +function isRegExp (o) { + return 'object' == typeof o + && '[object RegExp]' == toString.call(o); +} + +module.exports = exports = function (regexp) { + if (!isRegExp(regexp)) { + throw new TypeError('Not a RegExp'); + } + + var flags = []; + if (regexp.global) flags.push('g'); + if (regexp.multiline) flags.push('m'); + if (regexp.ignoreCase) flags.push('i'); + return new RegExp(regexp.source, flags.join('')); +} + diff --git a/5-3/node_modules/mongoose/node_modules/regexp-clone/package.json b/5-3/node_modules/mongoose/node_modules/regexp-clone/package.json new file mode 100644 index 0000000..29b6d17 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/regexp-clone/package.json @@ -0,0 +1,51 @@ +{ + "name": "regexp-clone", + "version": "0.0.1", + "description": "Clone RegExps with options", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/regexp-clone.git" + }, + "keywords": [ + "RegExp", + "clone" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.8.1" + }, + "readme": "#regexp-clone\n==============\n\nClones RegExps with flag preservation\n\n```js\nvar regexpClone = require('regexp-clone');\n\nvar a = /somethin/g;\nconsole.log(a.global); // true\n\nvar b = regexpClone(a);\nconsole.log(b.global); // true\n```\n\n## License\n\n[MIT](https://github.com/aheckmann/regexp-clone/blob/master/LICENSE)\n", + "readmeFilename": "README.md", + "_id": "regexp-clone@0.0.1", + "dist": { + "shasum": "a7c2e09891fdbf38fbb10d376fb73003e68ac589", + "tarball": "http://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz" + }, + "_from": "regexp-clone@0.0.1", + "_npmVersion": "1.2.14", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "directories": {}, + "_shasum": "a7c2e09891fdbf38fbb10d376fb73003e68ac589", + "_resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz", + "bugs": { + "url": "https://github.com/aheckmann/regexp-clone/issues" + }, + "homepage": "https://github.com/aheckmann/regexp-clone#readme" +} diff --git a/5-3/node_modules/mongoose/node_modules/regexp-clone/test/index.js b/5-3/node_modules/mongoose/node_modules/regexp-clone/test/index.js new file mode 100644 index 0000000..264a776 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/regexp-clone/test/index.js @@ -0,0 +1,112 @@ + +var assert = require('assert') +var clone = require('../'); + +describe('regexp-clone', function(){ + function hasEqualSource (a, b) { + assert.ok(a !== b); + assert.equal(a.source, b.source); + } + + function isInsensitive (a) { + assert.ok(a.ignoreCase); + } + + function isGlobal (a) { + assert.ok(a.global); + } + + function isMultiline (a) { + assert.ok(a.multiline); + } + + function insensitiveFlag (a) { + var b = clone(a); + hasEqualSource(a, b); + isInsensitive(a); + isInsensitive(b); + } + + function globalFlag (a) { + var b = clone(a); + hasEqualSource(a, b); + isGlobal(a); + isGlobal(b); + } + + function multilineFlag (a) { + var b = clone(a); + hasEqualSource(a, b); + isMultiline(a); + isMultiline(b); + } + + describe('literals', function(){ + it('insensitive flag', function(done){ + var a = /hello/i; + insensitiveFlag(a); + done(); + }) + it('global flag', function(done){ + var a = /hello/g; + globalFlag(a); + done(); + }) + it('multiline flag', function(done){ + var a = /hello/m; + multilineFlag(a); + done(); + }) + it('no flags', function(done){ + var a = /hello/; + var b = clone(a); + hasEqualSource(a, b); + assert.ok(!a.insensitive); + assert.ok(!a.global); + assert.ok(!a.global); + done(); + }) + it('all flags', function(done){ + var a = /hello/gim; + insensitiveFlag(a); + globalFlag(a); + multilineFlag(a); + done(); + }) + }) + + describe('instances', function(){ + it('insensitive flag', function(done){ + var a = new RegExp('hello', 'i'); + insensitiveFlag(a); + done(); + }) + it('global flag', function(done){ + var a = new RegExp('hello', 'g'); + globalFlag(a); + done(); + }) + it('multiline flag', function(done){ + var a = new RegExp('hello', 'm'); + multilineFlag(a); + done(); + }) + it('no flags', function(done){ + var a = new RegExp('hmm'); + var b = clone(a); + hasEqualSource(a, b); + assert.ok(!a.insensitive); + assert.ok(!a.global); + assert.ok(!a.global); + done(); + }) + it('all flags', function(done){ + var a = new RegExp('hello', 'gim'); + insensitiveFlag(a); + globalFlag(a); + multilineFlag(a); + done(); + }) + }) +}) + diff --git a/5-3/node_modules/mongoose/node_modules/sliced/History.md b/5-3/node_modules/mongoose/node_modules/sliced/History.md new file mode 100644 index 0000000..e45cefe --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/sliced/History.md @@ -0,0 +1,41 @@ + +1.0.1 / 2015-07-14 +================== + + * fixed; missing file introduced in 4f5cea1 + +1.0.0 / 2015-07-12 +================== + + * Remove unnecessary files from npm package - #6 via joaquimserafim + * updated readme stats + +0.0.5 / 2013-02-05 +================== + + * optimization: remove use of arguments [jkroso](https://github.com/jkroso) + * add scripts to component.json [jkroso](https://github.com/jkroso) + * tests; remove time for travis + +0.0.4 / 2013-01-07 +================== + + * added component.json #1 [jkroso](https://github.com/jkroso) + * reversed array loop #1 [jkroso](https://github.com/jkroso) + * remove fn params + +0.0.3 / 2012-09-29 +================== + + * faster with negative start args + +0.0.2 / 2012-09-29 +================== + + * support full [].slice semantics + +0.0.1 / 2012-09-29 +=================== + + * initial release + diff --git a/5-3/node_modules/mongoose/node_modules/sliced/LICENSE b/5-3/node_modules/mongoose/node_modules/sliced/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/sliced/LICENSE @@ -0,0 +1,22 @@ +(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/5-3/node_modules/mongoose/node_modules/sliced/README.md b/5-3/node_modules/mongoose/node_modules/sliced/README.md new file mode 100644 index 0000000..b6ff85e --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/sliced/README.md @@ -0,0 +1,62 @@ +#sliced +========== + +A faster alternative to `[].slice.call(arguments)`. + +[![Build Status](https://secure.travis-ci.org/aheckmann/sliced.png)](http://travis-ci.org/aheckmann/sliced) + +Example output from [benchmark.js](https://github.com/bestiejs/benchmark.js) + + Array.prototype.slice.call x 1,401,820 ops/sec ±2.16% (90 runs sampled) + [].slice.call x 1,313,116 ops/sec ±2.04% (96 runs sampled) + cached slice.call x 10,297,910 ops/sec ±1.81% (96 runs sampled) + sliced x 19,906,019 ops/sec ±1.23% (89 runs sampled) + fastest is sliced + + Array.prototype.slice.call(arguments, 1) x 1,373,238 ops/sec ±1.84% (95 runs sampled) + [].slice.call(arguments, 1) x 1,395,336 ops/sec ±1.36% (93 runs sampled) + cached slice.call(arguments, 1) x 9,926,018 ops/sec ±1.67% (92 runs sampled) + sliced(arguments, 1) x 20,747,990 ops/sec ±1.16% (93 runs sampled) + fastest is sliced(arguments, 1) + + Array.prototype.slice.call(arguments, -1) x 1,319,908 ops/sec ±2.12% (91 runs sampled) + [].slice.call(arguments, -1) x 1,336,170 ops/sec ±1.33% (97 runs sampled) + cached slice.call(arguments, -1) x 10,078,718 ops/sec ±1.21% (98 runs sampled) + sliced(arguments, -1) x 20,471,474 ops/sec ±1.81% (92 runs sampled) + fastest is sliced(arguments, -1) + + Array.prototype.slice.call(arguments, -2, -10) x 1,369,246 ops/sec ±1.68% (97 runs sampled) + [].slice.call(arguments, -2, -10) x 1,387,935 ops/sec ±1.70% (95 runs sampled) + cached slice.call(arguments, -2, -10) x 9,593,428 ops/sec ±1.23% (97 runs sampled) + sliced(arguments, -2, -10) x 23,178,931 ops/sec ±1.70% (92 runs sampled) + fastest is sliced(arguments, -2, -10) + + Array.prototype.slice.call(arguments, -2, -1) x 1,441,300 ops/sec ±1.26% (98 runs sampled) + [].slice.call(arguments, -2, -1) x 1,410,326 ops/sec ±1.96% (93 runs sampled) + cached slice.call(arguments, -2, -1) x 9,854,419 ops/sec ±1.02% (97 runs sampled) + sliced(arguments, -2, -1) x 22,550,801 ops/sec ±1.86% (91 runs sampled) + fastest is sliced(arguments, -2, -1) + +_Benchmark [source](https://github.com/aheckmann/sliced/blob/master/bench.js)._ + +##Usage + +`sliced` accepts the same arguments as `Array#slice` so you can easily swap it out. + +```js +function zing () { + var slow = [].slice.call(arguments, 1, 8); + var args = slice(arguments, 1, 8); + + var slow = Array.prototype.slice.call(arguments); + var args = slice(arguments); + // etc +} +``` + +## install + + npm install sliced + + +[LICENSE](https://github.com/aheckmann/sliced/blob/master/LICENSE) diff --git a/5-3/node_modules/mongoose/node_modules/sliced/index.js b/5-3/node_modules/mongoose/node_modules/sliced/index.js new file mode 100644 index 0000000..d88c85b --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/sliced/index.js @@ -0,0 +1,33 @@ + +/** + * An Array.prototype.slice.call(arguments) alternative + * + * @param {Object} args something with a length + * @param {Number} slice + * @param {Number} sliceEnd + * @api public + */ + +module.exports = function (args, slice, sliceEnd) { + var ret = []; + var len = args.length; + + if (0 === len) return ret; + + var start = slice < 0 + ? Math.max(0, slice + len) + : slice || 0; + + if (sliceEnd !== undefined) { + len = sliceEnd < 0 + ? sliceEnd + len + : sliceEnd + } + + while (len-- > start) { + ret[len - start] = args[len]; + } + + return ret; +} + diff --git a/5-3/node_modules/mongoose/node_modules/sliced/package.json b/5-3/node_modules/mongoose/node_modules/sliced/package.json new file mode 100644 index 0000000..8eaec88 --- /dev/null +++ b/5-3/node_modules/mongoose/node_modules/sliced/package.json @@ -0,0 +1,60 @@ +{ + "name": "sliced", + "version": "1.0.1", + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "main": "index.js", + "files": [ + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/sliced.git" + }, + "keywords": [ + "arguments", + "slice", + "array" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.5.0", + "benchmark": "~1.0.0" + }, + "dependencies": {}, + "gitHead": "e7c989016d2062995cd102322b65784ba8977ee3", + "bugs": { + "url": "https://github.com/aheckmann/sliced/issues" + }, + "homepage": "https://github.com/aheckmann/sliced", + "_id": "sliced@1.0.1", + "_shasum": "0b3a662b5d04c3177b1926bea82b03f837a2ef41", + "_from": "sliced@1.0.1", + "_npmVersion": "2.8.3", + "_nodeVersion": "1.8.1", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "dist": { + "shasum": "0b3a662b5d04c3177b1926bea82b03f837a2ef41", + "tarball": "http://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/package.json b/5-3/node_modules/mongoose/package.json new file mode 100644 index 0000000..9d66d03 --- /dev/null +++ b/5-3/node_modules/mongoose/package.json @@ -0,0 +1,134 @@ +{ + "name": "mongoose", + "description": "Mongoose MongoDB ODM", + "version": "4.4.3", + "author": { + "name": "Guillermo Rauch", + "email": "guillermo@learnboost.com" + }, + "keywords": [ + "mongodb", + "document", + "model", + "schema", + "database", + "odm", + "data", + "datastore", + "query", + "nosql", + "orm", + "db" + ], + "license": "MIT", + "dependencies": { + "async": "1.5.2", + "bson": "0.4.21", + "hooks-fixed": "1.1.0", + "kareem": "1.0.1", + "mongodb": "2.1.6", + "mpath": "0.2.1", + "mpromise": "0.5.5", + "mquery": "1.6.3", + "ms": "0.7.1", + "muri": "1.1.0", + "regexp-clone": "0.0.1", + "sliced": "1.0.1" + }, + "devDependencies": { + "acquit": "0.4.1", + "acquit-ignore": "0.0.3", + "benchmark": "2.0.0", + "bluebird": "3.1.4", + "co": "4.6.0", + "dox": "0.3.1", + "eslint": "2.0.0-beta.3", + "highlight.js": "7.0.1", + "istanbul": "0.4.2", + "jade": "0.26.3", + "markdown": "0.3.1", + "marked": "0.3.5", + "mocha": "2.3.4", + "node-static": "0.7.7", + "power-assert": "1.2.0", + "q": "1.4.1", + "tbd": "0.6.4", + "uglify-js": "2.6.1", + "underscore": "1.8.3" + }, + "browserDependencies": { + "browserify": "4.1.10", + "chai": "3.5.0", + "karma": "0.12.16", + "karma-chai": "0.1.0", + "karma-mocha": "0.1.4", + "karma-chrome-launcher": "0.1.4", + "karma-sauce-launcher": "0.2.8" + }, + "directories": { + "lib": "./lib/mongoose" + }, + "scripts": { + "fix-lint": "eslint . --fix", + "install-browser": "npm install `node format_deps.js`", + "test": "mocha test/*.test.js test/**/*.test.js", + "posttest": "eslint . --quiet", + "test-cov": "istanbul cover --report text --report html _mocha test/*.test.js" + }, + "main": "./index.js", + "engines": { + "node": ">=0.6.19" + }, + "bugs": { + "url": "https://github.com/Automattic/mongoose/issues/new", + "email": "mongoose-orm@googlegroups.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/Automattic/mongoose.git" + }, + "homepage": "http://mongoosejs.com", + "browser": "lib/browser.js", + "gitHead": "059520ff1c2242c02e1bf9f00ddb9a962947dd37", + "_id": "mongoose@4.4.3", + "_shasum": "0c7aeb37615cb631307cd2dff5d76c8681dac9ea", + "_from": "mongoose@*", + "_npmVersion": "3.3.12", + "_nodeVersion": "5.4.1", + "_npmUser": { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + "dist": { + "shasum": "0c7aeb37615cb631307cd2dff5d76c8681dac9ea", + "tarball": "http://registry.npmjs.org/mongoose/-/mongoose-4.4.3.tgz" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-6-west.internal.npmjs.com", + "tmp": "tmp/mongoose-4.4.3.tgz_1455061137802_0.8885454896371812" + }, + "_resolved": "https://registry.npmjs.org/mongoose/-/mongoose-4.4.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/5-3/node_modules/mongoose/release-items.md b/5-3/node_modules/mongoose/release-items.md new file mode 100644 index 0000000..3dc270e --- /dev/null +++ b/5-3/node_modules/mongoose/release-items.md @@ -0,0 +1,29 @@ +## mongoose release procedure + +1. tests must pass +2. update package.json version +3. update History.md using `git changelog` or similar. list the related ticket(s) # as well as a link to the github user who fixed it if applicable. +4. git commit -m 'release x.x.x' +5. git tag x.x.x +6. git push origin BRANCH --tags && npm publish +7. update mongoosejs.com (see "updating the website" below) +8. announce to google groups - include the relevant change log and links to issues +9. tweet google group announcement from [@mongoosejs](https://twitter.com/mongoosejs) +10. change package.json version to next patch version suffixed with '-pre' and commit "now working on x.x.x" +11. if this is a legacy release, `git merge` changes into master. + +## updating the website + +For 4.x + +0. Change to the master branch +1. execute `make docs` (when this process completes you'll be on the gh-pages branch) +2. `git commit -a -m 'website; regen <4.x.x>'` +3. `git push origin gh-pages` + +For 3.8.x: + +0. Change to the 3.8.x branch +1. execute `make docs_legacy` (when this process completes you'll be on the gh-pages branch) +2. `git commit -a -m 'website; regen '` +3. `git push origin gh-pages` diff --git a/5-3/node_modules/mongoose/static.js b/5-3/node_modules/mongoose/static.js new file mode 100644 index 0000000..d84e59f --- /dev/null +++ b/5-3/node_modules/mongoose/static.js @@ -0,0 +1,24 @@ + +var static = require('node-static'); +var server = new static.Server('.', {cache: 0}); + +require('http').createServer(function(req, res) { + if (req.url === '/favicon.ico') { + req.destroy(); + res.statusCode = 204; + return res.end(); + } + + req.on('end', function() { + server.serve(req, res, function(err) { + if (err) { + console.error(err, req.url); + res.writeHead(err.status, err.headers); + res.end(); + } + }); + }); + req.resume(); +}).listen(8088); + +console.error('now listening on http://localhost:8088'); diff --git a/5-3/node_modules/mongoose/website.js b/5-3/node_modules/mongoose/website.js new file mode 100644 index 0000000..a1186a5 --- /dev/null +++ b/5-3/node_modules/mongoose/website.js @@ -0,0 +1,87 @@ +var fs = require('fs'); +var jade = require('jade'); +var package = require('./package'); +var hl = require('./docs/helpers/highlight'); +var linktype = require('./docs/helpers/linktype'); +var href = require('./docs/helpers/href'); +var klass = require('./docs/helpers/klass'); + +// add custom jade filters +require('./docs/helpers/filters')(jade); + +function getVersion() { + var hist = fs.readFileSync('./History.md', 'utf8').replace(/\r/g, '\n').split('\n'); + for (var i = 0; i < hist.length; ++i) { + var line = (hist[i] || '').trim(); + if (!line) { + continue; + } + var match = /^\s*([^\s]+)\s/.exec(line); + if (match && match[1]) { + return match[1]; + } + } + throw new Error('no match found'); +} + +function getUnstable(ver) { + ver = ver.replace('-pre'); + var spl = ver.split('.'); + spl = spl.map(function(i) { + return parseInt(i, 10); + }); + spl[1]++; + spl[2] = 'x'; + return spl.join('.'); +} + +// use last release +package.version = getVersion(); +package.unstable = getUnstable(package.version); + +var filemap = require('./docs/source'); +var files = Object.keys(filemap); + +function jadeify(filename, options, newfile) { + options = options || {}; + options.package = package; + options.hl = hl; + options.linktype = linktype; + options.href = href; + options.klass = klass; + jade.renderFile(filename, options, function(err, str) { + if (err) { + console.error(err.stack); + return; + } + + newfile = newfile || filename.replace('.jade', '.html'); + fs.writeFile(newfile, str, function(err) { + if (err) { + console.error('could not write', err.stack); + } else { + console.log('%s : rendered ', new Date, newfile); + } + }); + }); +} + +files.forEach(function(file) { + var filename = __dirname + '/' + file; + jadeify(filename, filemap[file]); + + if (process.argv[2] === '--watch') { + fs.watchFile(filename, {interval: 1000}, function(cur, prev) { + if (cur.mtime > prev.mtime) { + jadeify(filename, filemap[file]); + } + }); + } +}); + +var acquit = require('./docs/source/acquit'); +var acquitFiles = Object.keys(acquit); +acquitFiles.forEach(function(file) { + var filename = __dirname + '/docs/acquit.jade'; + jadeify(filename, acquit[file], __dirname + '/docs/' + file); +}); diff --git a/5-3/node_modules/superagent/.npmignore b/5-3/node_modules/superagent/.npmignore new file mode 100644 index 0000000..90d998b --- /dev/null +++ b/5-3/node_modules/superagent/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +*.sock +lib-cov +coverage.html diff --git a/5-3/node_modules/superagent/.travis.yml b/5-3/node_modules/superagent/.travis.yml new file mode 100644 index 0000000..0262c01 --- /dev/null +++ b/5-3/node_modules/superagent/.travis.yml @@ -0,0 +1,18 @@ +sudo: false +language: node_js +node_js: + - "5.4" + - "4.2" + - "0.12" + - "0.10" + - "iojs" + +env: + global: + - SAUCE_USERNAME='shtylman-superagent' + - SAUCE_ACCESS_KEY='39a45464-cb1d-4b8d-aa1f-83c7c04fa673' + +matrix: + include: + - node_js: "4.2" + env: BROWSER=1 diff --git a/5-3/node_modules/superagent/.zuul.yml b/5-3/node_modules/superagent/.zuul.yml new file mode 100644 index 0000000..031c56a --- /dev/null +++ b/5-3/node_modules/superagent/.zuul.yml @@ -0,0 +1,15 @@ +ui: mocha-bdd +server: ./test/support/server.js +browsers: + - name: chrome + version: latest + - name: firefox + version: latest + - name: safari + version: latest + - name: iphone + version: latest + - name: android + version: latest + - name: ie + version: 9..latest diff --git a/5-3/node_modules/superagent/Contributing.md b/5-3/node_modules/superagent/Contributing.md new file mode 100644 index 0000000..1eca592 --- /dev/null +++ b/5-3/node_modules/superagent/Contributing.md @@ -0,0 +1,7 @@ +When submitting a PR, your chance of acceptance increases if you do the following: + +* Code style is consistent with existing in the file. +* Tests are passing (client and server). +* You add a test for the failing issue you are fixing. +* Code changes are focused on the area of discussion. +* Do not rebuild the distribution files or increment version numbers. diff --git a/5-3/node_modules/superagent/History.md b/5-3/node_modules/superagent/History.md new file mode 100644 index 0000000..8483f96 --- /dev/null +++ b/5-3/node_modules/superagent/History.md @@ -0,0 +1,532 @@ +# 1.7.2 (2016-01-26) + + * Fix case-sensitivity of header fields introduced by a4ddd6a. (Edward J. Jinotti) + * bump extend dependency, as former version did not contain any license information (Lukas Eipert) + +# 1.7.1 (2016-01-21) + + * Fixed a conflict with express when using npm 3.x (Glenn) + * Fixed redirects after a multipart/form-data POST request (cyclist2) + +# 1.7.0 (2016-01-18) + + * When attaching files, read default filename from the `File` object (JD Isaacks) + * Add `direction` property to `progress` events (Joseph Dykstra) + * Update component-emitter & formidable (Kornel Lesiński) + * Don't re-encode query string needlessly (Ruben Verborgh) + * ensure querystring is appended when doing `stream.pipe(request)` (Keith Grennan) + * change set header function, not call `this.request()` until call `this.end()` (vicanso) + * Add no-op `withCredentials` to Node API (markdalgleish) + * fix `delete` breaking on ie8 (kenjiokabe) + * Don't let request error override responses (Clay Reimann) + * Increased number of tests shared between node and client (Kornel Lesiński) + +# 1.6.0/1.6.1 (2015-12-09) + + * avoid misleading CORS error message + * added 'progress' event on file/form upload in Node (Olivier Lalonde) + * return raw response if the response parsing fails (Rei Colina) + * parse content-types ending with `+json` as JSON (Eiryyy) + * fix to avoid throwing errors on aborted requests (gjurgens) + * retain cookies on redirect when hosts match (Tom Conroy) + * added Bower manifest (Johnny Freeman) + * upgrade to latest cookiejar (Andy Burke) + +# 1.5.0 (2015-11-30) + + * encode array values as `key=1&key=2&key=3` etc... (aalpern, Davis Kim) + * avoid the error which is omitted from 'socket hang up' + * faster JSON parsing, handling of zlib errors (jbellenger) + * fix IE11 sends 'undefined' string if data was undefined (Vadim Goncharov) + * alias `del()` method as `delete()` (Aaron Krause) + * revert Request#parse since it was actually Response#parse + +# 1.4.0 (2015-09-14) + + * add Request#parse method to client library + * add missing statusCode in client response + * don't apply JSON heuristics if a valid parser is found + * fix detection of root object for webworkers + +# 1.3.0 (2015-08-05) + + * fix incorrect content-length of data set to buffer + * serialize request data takes into account charsets + * add basic promise support via a `then` function + +# 1.2.0 (2015-04-13) + + * add progress events to downlodas + * make usable in webworkers + * add support for 308 redirects + * update node-form-data dependency + * update to work in react native + * update node-mime dependency + +# 1.1.0 (2015-03-13) + + * Fix responseType checks without xhr2 and ie9 tests (rase-) + * errors have .status and .response fields if applicable (defunctzombie) + * fix end callback called before saving cookies (rase-) + +1.0.0 / 2015-03-08 +================== + + * All non-200 responses are treated as errors now. (The callback is called with an error when the response has a status < 200 or >= 300 now. In previous versions this would not have raised an error and the client would have to check the `res` object. See [#283](https://github.com/visionmedia/superagent/issues/283). + * keep timeouts intact across redirects (hopkinsth) + * handle falsy json values (themaarten) + * fire response events in browser version (Schoonology) + * getXHR exported in client version (KidsKilla) + * remove arity check on `.end()` callbacks (defunctzombie) + * avoid setting content-type for host objects (rexxars) + * don't index array strings in querystring (travisjeffery) + * fix pipe() with redirects (cyrilis) + * add xhr2 file download (vstirbu) + * set default response type to text/plain if not specified (warrenseine) + +0.21.0 / 2014-11-11 +================== + + * Trim text before parsing json (gjohnson) + * Update tests to express 4 (gaastonsr) + * Prevent double callback when error is thrown (pgn-vole) + * Fix missing clearTimeout (nickdima) + * Update debug (TooTallNate) + +0.20.0 / 2014-10-02 +================== + + * Add toJSON() to request and response instances. (yields) + * Prevent HEAD requests from getting parsed. (gjohnson) + * Update debug. (TooTallNate) + +0.19.1 / 2014-09-24 +================== + + * Fix basic auth issue when password is falsey value. (gjohnson) + +0.19.0 / 2014-09-24 +================== + + * Add unset() to browser. (shesek) + * Prefer XHR over ActiveX. (omeid) + * Catch parse errors. (jacwright) + * Update qs dependency. (wercker) + * Add use() to node. (Financial-Times) + * Add response text to errors. (yields) + * Don't send empty cookie headers. (undoZen) + * Don't parse empty response bodies. (DveMac) + * Use hostname when setting cookie host. (prasunsultania) + +0.18.2 / 2014-07-12 +================== + + * Handle parser errors. (kof) + * Ensure not to use default parsers when there is a user defined one. (kof) + +0.18.1 / 2014-07-05 +================== + + * Upgrade cookiejar dependency (juanpin) + * Support image mime types (nebulade) + * Make .agent chainable (kof) + * Upgrade debug (TooTallNate) + * Fix docs (aheckmann) + +0.18.0 / 2014-04-29 +=================== + +* Use "form-data" module for the multipart/form-data implementation. (TooTallNate) +* Add basic `field()` and `attach()` functions for HTML5 FormData. (TooTallNate) +* Deprecate `part()`. (TooTallNate) +* Set default user-agent header. (bevacqua) +* Add `unset()` method for removing headers. (bevacqua) +* Update cookiejar. (missinglink) +* Fix response error formatting. (shesek) + +0.17.0 / 2014-03-06 +=================== + + * supply uri malformed error to the callback (yields) + * add request event (yields) + * allow simple auth (yields) + * add request event (yields) + * switch to component/reduce (visionmedia) + * fix part content-disposition (mscdex) + * add browser testing via zuul (defunctzombie) + * adds request.use() (johntron) + +0.16.0 / 2014-01-07 +================== + + * remove support for 0.6 (superjoe30) + * fix CORS withCredentials (wejendorp) + * add "test" script (superjoe30) + * add request .accept() method (nickl-) + * add xml to mime types mappings (nickl-) + * fix parse body error on HEAD requests (gjohnson) + * fix documentation typos (matteofigus) + * fix content-type + charset (bengourley) + * fix null values on query parameters (cristiandouce) + +0.15.7 / 2013-10-19 +================== + + * pin should.js to 1.3.0 due to breaking change in 2.0.x + * fix browserify regression + +0.15.5 / 2013-10-09 +================== + + * add browser field to support browserify + * fix .field() value number support + +0.15.4 / 2013-07-09 +================== + + * node: add a Request#agent() function to set the http Agent to use + +0.15.3 / 2013-07-05 +================== + + * fix .pipe() unzipping on more recent nodes. Closes #240 + * fix passing an empty object to .query() no longer appends "?" + * fix formidable error handling + * update formidable + +0.15.2 / 2013-07-02 +================== + + * fix: emit 'end' when piping. + +0.15.1 / 2013-06-26 +================== + + * add try/catch around parseLinks + +0.15.0 / 2013-06-25 +================== + + * make `Response#toError()` have a more meaningful `message` + +0.14.9 / 2013-06-15 +================== + + * add debug()s to the node client + * add .abort() method to node client + +0.14.8 / 2013-06-13 +================== + + * set .agent = false always + * remove X-Requested-With. Closes #189 + +0.14.7 / 2013-06-06 +================== + + * fix unzip error handling + +0.14.6 / 2013-05-23 +================== + + * fix HEAD unzip bug + +0.14.5 / 2013-05-23 +================== + + * add flag to ensure the callback is __never__ invoked twice + +0.14.4 / 2013-05-22 +================== + + * add superagent.js build output + * update qs + * update emitter-component + * revert "add browser field to support browserify" see GH-221 + +0.14.3 / 2013-05-18 +================== + + * add browser field to support browserify + +0.14.2/ 2013-05-07 +================== + + * add host object check to fix serialization of File/Blobs etc as json + +0.14.1 / 2013-04-09 +================== + + * update qs + +0.14.0 / 2013-04-02 +================== + + * add client-side basic auth + * fix retaining of .set() header field case + +0.13.0 / 2013-03-13 +================== + + * add progress events to client + * add simple example + * add res.headers as alias of res.header for browser client + * add res.get(field) to node/client + +0.12.4 / 2013-02-11 +================== + + * fix get content-type even if can't get other headers in firefox. fixes #181 + +0.12.3 / 2013-02-11 +================== + + * add quick "progress" event support + +0.12.2 / 2013-02-04 +================== + + * add test to check if response acts as a readable stream + * add ReadableStream in the Response prototype. + * add test to assert correct redirection when the host changes in the location header. + * add default Accept-Encoding. Closes #155 + * fix req.pipe() return value of original stream for node parity. Closes #171 + * remove the host header when cleaning headers to properly follow the redirection. + +0.12.1 / 2013-01-10 +================== + + * add x-domain error handling + +0.12.0 / 2013-01-04 +================== + + * add header persistence on redirects + +0.11.0 / 2013-01-02 +================== + + * add .error Error object. Closes #156 + * add forcing of res.text removal for FF HEAD responses. Closes #162 + * add reduce component usage. Closes #90 + * move better-assert dep to development deps + +0.10.0 / 2012-11-14 +================== + + * add req.timeout(ms) support for the client + +0.9.10 / 2012-11-14 +================== + + * fix client-side .query(str) support + +0.9.9 / 2012-11-14 +================== + + * add .parse(fn) support + * fix socket hangup with dates in querystring. Closes #146 + * fix socket hangup "error" event when a callback of arity 2 is provided + +0.9.8 / 2012-11-03 +================== + + * add emission of error from `Request#callback()` + * add a better fix for nodes weird socket hang up error + * add PUT/POST/PATCH data support to client short-hand functions + * add .license property to component.json + * change client portion to build using component(1) + * fix GET body support [guille] + +0.9.7 / 2012-10-19 +================== + + * fix `.buffer()` `res.text` when no parser matches + +0.9.6 / 2012-10-17 +================== + + * change: use `this` when `window` is undefined + * update to new component spec [juliangruber] + * fix emission of "data" events for compressed responses without encoding. Closes #125 + +0.9.5 / 2012-10-01 +================== + + * add field name to .attach() + * add text "parser" + * refactor isObject() + * remove wtf isFunction() helper + +0.9.4 / 2012-09-20 +================== + + * fix `Buffer` responses [TooTallNate] + * fix `res.type` when a "type" param is present [TooTallNate] + +0.9.3 / 2012-09-18 +================== + + * remove __GET__ `.send()` == `.query()` special-case (__API__ change !!!) + +0.9.2 / 2012-09-17 +================== + + * add `.aborted` prop + * add `.abort()`. Closes #115 + +0.9.1 / 2012-09-07 +================== + + * add `.forbidden` response property + * add component.json + * change emitter-component to 0.0.5 + * fix client-side tests + +0.9.0 / 2012-08-28 +================== + + * add `.timeout(ms)`. Closes #17 + +0.8.2 / 2012-08-28 +================== + + * fix pathname relative redirects. Closes #112 + +0.8.1 / 2012-08-21 +================== + + * fix redirects when schema is specified + +0.8.0 / 2012-08-19 +================== + + * add `res.buffered` flag + * add buffering of text/*, json and forms only by default. Closes #61 + * add `.buffer(false)` cancellation + * add cookie jar support [hunterloftis] + * add agent functionality [hunterloftis] + +0.7.0 / 2012-08-03 +================== + + * allow `query()` to be called after the internal `req` has been created [tootallnate] + +0.6.0 / 2012-07-17 +================== + + * add `res.send('foo=bar')` default of "application/x-www-form-urlencoded" + +0.5.1 / 2012-07-16 +================== + + * add "methods" dep + * add `.end()` arity check to node callbacks + * fix unzip support due to weird node internals + +0.5.0 / 2012-06-16 +================== + + * Added "Link" response header field parsing, exposing `res.links` + +0.4.3 / 2012-06-15 +================== + + * Added 303, 305 and 307 as redirect status codes [slaskis] + * Fixed passing an object as the url + +0.4.2 / 2012-06-02 +================== + + * Added component support + * Fixed redirect data + +0.4.1 / 2012-04-13 +================== + + * Added HTTP PATCH support + * Fixed: GET / HEAD when following redirects. Closes #86 + * Fixed Content-Length detection for multibyte chars + +0.4.0 / 2012-03-04 +================== + + * Added `.head()` method [browser]. Closes #78 + * Added `make test-cov` support + * Added multipart request support. Closes #11 + * Added all methods that node supports. Closes #71 + * Added "response" event providing a Response object. Closes #28 + * Added `.query(obj)`. Closes #59 + * Added `res.type` (browser). Closes #54 + * Changed: default `res.body` and `res.files` to {} + * Fixed: port existing query-string fix (browser). Closes #57 + +0.3.0 / 2012-01-24 +================== + + * Added deflate/gzip support [guillermo] + * Added `res.type` (Content-Type void of params) + * Added `res.statusCode` to mirror node + * Added `res.headers` to mirror node + * Changed: parsers take callbacks + * Fixed optional schema support. Closes #49 + +0.2.0 / 2012-01-05 +================== + + * Added url auth support + * Added `.auth(username, password)` + * Added basic auth support [node]. Closes #41 + * Added `make test-docs` + * Added guillermo's EventEmitter. Closes #16 + * Removed `Request#data()` for SS, renamed to `send()` + * Removed `Request#data()` from client, renamed to `send()` + * Fixed array support. [browser] + * Fixed array support. Closes #35 [node] + * Fixed `EventEmitter#emit()` + +0.1.3 / 2011-10-25 +================== + + * Added error to callback + * Bumped node dep for 0.5.x + +0.1.2 / 2011-09-24 +================== + + * Added markdown documentation + * Added `request(url[, fn])` support to the client + * Added `qs` dependency to package.json + * Added options for `Request#pipe()` + * Added support for `request(url, callback)` + * Added `request(url)` as shortcut for `request.get(url)` + * Added `Request#pipe(stream)` + * Added inherit from `Stream` + * Added multipart support + * Added ssl support (node) + * Removed Content-Length field from client + * Fixed buffering, `setEncoding()` to utf8 [reported by stagas] + * Fixed "end" event when piping + +0.1.1 / 2011-08-20 +================== + + * Added `res.redirect` flag (node) + * Added redirect support (node) + * Added `Request#redirects(n)` (node) + * Added `.set(object)` header field support + * Fixed `Content-Length` support + +0.1.0 / 2011-08-09 +================== + + * Added support for multiple calls to `.data()` + * Added support for `.get(uri, obj)` + * Added GET `.data()` querystring support + * Added IE{6,7,8} support [alexyoung] + +0.0.1 / 2011-08-05 +================== + + * Initial commit + diff --git a/5-3/node_modules/superagent/LICENSE b/5-3/node_modules/superagent/LICENSE new file mode 100644 index 0000000..1b188ba --- /dev/null +++ b/5-3/node_modules/superagent/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/5-3/node_modules/superagent/Makefile b/5-3/node_modules/superagent/Makefile new file mode 100644 index 0000000..bac2be5 --- /dev/null +++ b/5-3/node_modules/superagent/Makefile @@ -0,0 +1,57 @@ + +NODETESTS ?= test/*.js test/node/*.js +BROWSERTESTS ?= test/*.js test/client/*.js +REPORTER = spec + +all: superagent.js + +test: + @if [ "x$(BROWSER)" = "x" ]; then make test-node; else make test-browser; fi + +test-node: + @NODE_ENV=test NODE_TLS_REJECT_UNAUTHORIZED=0 ./node_modules/.bin/mocha \ + --require should \ + --reporter $(REPORTER) \ + --timeout 5000 \ + --growl \ + $(NODETESTS) + +test-cov: lib-cov + SUPERAGENT_COV=1 $(MAKE) test REPORTER=html-cov > coverage.html + +test-browser: + ./node_modules/.bin/zuul -- $(BROWSERTESTS) + +test-browser-local: + ./node_modules/.bin/zuul --local 4000 -- $(BROWSERTESTS) + +lib-cov: + jscoverage lib lib-cov + +superagent.js: lib/node/*.js lib/node/parsers/*.js + @./node_modules/.bin/browserify \ + --standalone superagent \ + --outfile superagent.js . + +test-server: + @node test/server + +docs: index.html test-docs + +index.html: docs/index.md + marked < $< \ + | cat docs/head.html - docs/tail.html \ + > $@ + +docclean: + rm -f index.html test.html + +test-docs: + make test REPORTER=doc \ + | cat docs/head.html - docs/tail.html \ + > test.html + +clean: + rm -fr superagent.js components + +.PHONY: test-cov test docs test-docs clean test-browser-local diff --git a/5-3/node_modules/superagent/Readme.md b/5-3/node_modules/superagent/Readme.md new file mode 100644 index 0000000..56eac0c --- /dev/null +++ b/5-3/node_modules/superagent/Readme.md @@ -0,0 +1,113 @@ +# SuperAgent [![Build Status](https://travis-ci.org/visionmedia/superagent.svg?branch=master)](https://travis-ci.org/visionmedia/superagent) + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/shtylman-superagent.svg)](https://saucelabs.com/u/shtylman-superagent) + +SuperAgent is a small progressive __client-side__ HTTP request library, and __Node.js__ module with the same API, sporting many high-level HTTP client features. View the [docs](http://visionmedia.github.io/superagent/). + +![super agent](http://f.cl.ly/items/3d282n3A0h0Z0K2w0q2a/Screenshot.png) + +## Installation + +node: + +``` +$ npm install superagent +``` + +component: + +``` +$ component install visionmedia/superagent +``` + +Works with [browserify](https://github.com/substack/node-browserify) and should work with [webpack](https://github.com/visionmedia/superagent/wiki/Superagent-for-Webpack) + +```js +request + .post('/api/pet') + .send({ name: 'Manny', species: 'cat' }) + .set('X-API-Key', 'foobar') + .set('Accept', 'application/json') + .end(function(err, res){ + // Calling the end function will send the request + }); +``` + +## Supported browsers + +Tested browsers: + +- Latest Android +- Latest Firefox +- Latest Chrome +- IE9 through latest +- Latest iPhone +- Latest Safari + +Even though IE9 is supported, a polyfill `window.btoa` is needed to use basic auth. + +# Plugins + +Superagent is easily extended via plugins. + +```js +var nocache = require('superagent-no-cache'); +var request = require('superagent'); +var prefix = require('superagent-prefix')('/static'); + +request +.get('/some-url') +.use(prefix) // Prefixes *only* this request +.use(nocache) // Prevents caching of *only* this request +.end(function(err, res){ + // Do something +}); +``` + +Existing plugins: + * [superagent-no-cache](https://github.com/johntron/superagent-no-cache) - prevents caching by including Cache-Control header + * [superagent-prefix](https://github.com/johntron/superagent-prefix) - prefixes absolute URLs (useful in test environment) + * [superagent-mock](https://github.com/M6Web/superagent-mock) - simulate HTTP calls by returning data fixtures based on the requested URL + * [superagent-mocker](https://github.com/shuvalov-anton/superagent-mocker) — simulate REST API + * [superagent-cache](https://github.com/jpodwys/superagent-cache) - superagent with built-in, flexible caching + * [superagent-jsonapify](https://github.com/alex94puchades/superagent-jsonapify) - A lightweight [json-api](http://jsonapi.org/format/) client addon for superagent + * [superagent-serializer](https://github.com/zzarcon/superagent-serializer) - Converts server payload into different cases + +Please prefix your plugin with `superagent-*` so that it can easily be found by others. + +For superagent extensions such as couchdb and oauth visit the [wiki](https://github.com/visionmedia/superagent/wiki). + +## Running node tests + +Install dependencies: + +```shell +$ npm install +``` +Run em! + +```shell +$ make test +``` + +## Running browser tests + +Install dependencies: + +```shell +$ npm install +``` + +Start the test runner: + +```shell +$ make test-browser-local +``` + +Visit `http://localhost:4000/__zuul` in your browser. + +Edit tests and refresh your browser. You do not have to restart the test runner. + +## License + +MIT diff --git a/5-3/node_modules/superagent/bower.json b/5-3/node_modules/superagent/bower.json new file mode 100644 index 0000000..f1f1eb5 --- /dev/null +++ b/5-3/node_modules/superagent/bower.json @@ -0,0 +1,4 @@ +{ + "name": "superagent", + "main": "lib/client.js" +} \ No newline at end of file diff --git a/5-3/node_modules/superagent/component.json b/5-3/node_modules/superagent/component.json new file mode 100644 index 0000000..e5ec7d4 --- /dev/null +++ b/5-3/node_modules/superagent/component.json @@ -0,0 +1,21 @@ +{ + "name": "superagent", + "repo": "visionmedia/superagent", + "description": "awesome http requests", + "version": "1.2.0", + "keywords": [ + "http", + "ajax", + "request", + "agent" + ], + "scripts": [ + "lib/client.js" + ], + "main": "lib/client.js", + "dependencies": { + "component/emitter": "*", + "component/reduce": "*" + }, + "license": "MIT" +} diff --git a/5-3/node_modules/superagent/docs/head.html b/5-3/node_modules/superagent/docs/head.html new file mode 100644 index 0000000..4d3bc50 --- /dev/null +++ b/5-3/node_modules/superagent/docs/head.html @@ -0,0 +1,21 @@ + + + + SuperAgent - Ajax with less suck + + + + + + + + + +
diff --git a/5-3/node_modules/superagent/docs/highlight.js b/5-3/node_modules/superagent/docs/highlight.js new file mode 100644 index 0000000..b37eefb --- /dev/null +++ b/5-3/node_modules/superagent/docs/highlight.js @@ -0,0 +1,17 @@ + +$(function(){ + $('code').each(function(){ + $(this).html(highlight($(this).text())); + }); +}); + +function highlight(js) { + return js + .replace(//g, '>') + .replace(/('.*?')/gm, '$1') + .replace(/(\d+\.\d+)/gm, '$1') + .replace(/(\d+)/gm, '$1') + .replace(/\bnew *(\w+)/gm, 'new $1') + .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') +} \ No newline at end of file diff --git a/5-3/node_modules/superagent/docs/images/bg.png b/5-3/node_modules/superagent/docs/images/bg.png new file mode 100644 index 0000000..ca3d267 Binary files /dev/null and b/5-3/node_modules/superagent/docs/images/bg.png differ diff --git a/5-3/node_modules/superagent/docs/index.md b/5-3/node_modules/superagent/docs/index.md new file mode 100644 index 0000000..3dc9843 --- /dev/null +++ b/5-3/node_modules/superagent/docs/index.md @@ -0,0 +1,448 @@ + +# SuperAgent + + Super Agent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs. It also works with Node.js! + + request + .post('/api/pet') + .send({ name: 'Manny', species: 'cat' }) + .set('X-API-Key', 'foobar') + .set('Accept', 'application/json') + .end(function(err, res){ + if (err || !res.ok) { + alert('Oh no! error'); + } else { + alert('yay got ' + JSON.stringify(res.body)); + } + }); + +## Test documentation + + The following [test documentation](docs/test.html) was generated with [Mocha's](http://visionmedia.github.com/mocha) "doc" reporter, and directly reflects the test suite. This provides an additional source of documentation. + +## Request basics + + A request can be initiated by invoking the appropriate method on the `request` object, then calling `.end()` to send the request. For example a simple GET request: + + request + .get('/search') + .end(function(err, res){ + + }); + + A method string may also be passed: + + request('GET', '/search').end(callback); + + The __node__ client may also provide absolute urls: + + request + .get('http://example.com/search') + .end(function(err, res){ + + }); + + __DELETE__, __HEAD__, __POST__, __PUT__ and other __HTTP__ verbs may also be used, simply change the method name: + + request + .head('/favicon.ico') + .end(function(err, res){ + + }); + + __DELETE__ is a special-case, as it's a reserved word, so the method is named `.del()`: + + request + .del('/user/1') + .end(function(err, res){ + + }); + + The HTTP method defaults to __GET__, so if you wish, the following is valid: + + request('/search', function(err, res){ + + }); + +## Setting header fields + + Setting header fields is simple, invoke `.set()` with a field name and value: + + request + .get('/search') + .set('API-Key', 'foobar') + .set('Accept', 'application/json') + .end(callback); + + You may also pass an object to set several fields in a single call: + + request + .get('/search') + .set({ 'API-Key': 'foobar', Accept: 'application/json' }) + .end(callback); + +## GET requests + + The `.query()` method accepts objects, which when used with the __GET__ method will form a query-string. The following will produce the path `/search?query=Manny&range=1..5&order=desc`. + + request + .get('/search') + .query({ query: 'Manny' }) + .query({ range: '1..5' }) + .query({ order: 'desc' }) + .end(function(err, res){ + + }); + + Or as a single object: + + request + .get('/search') + .query({ query: 'Manny', range: '1..5', order: 'desc' }) + .end(function(err, res){ + + }); + + The `.query()` method accepts strings as well: + + request + .get('/querystring') + .query('search=Manny&range=1..5') + .end(function(err, res){ + + }); + + Or joined: + + request + .get('/querystring') + .query('search=Manny') + .query('range=1..5') + .end(function(err, res){ + + }); + +## HEAD requests + +You can also use the `.query()` method for HEAD requests. The following will produce the path `/users?email=joe@smith.com`. + + request + .head('/users') + .query({ email: 'joe@smith.com' }) + .end(function(err, res){ + + }); + +## POST / PUT requests + + A typical JSON __POST__ request might look a little like the following, where we set the Content-Type header field appropriately, and "write" some data, in this case just a JSON string. + + request.post('/user') + .set('Content-Type', 'application/json') + .send('{"name":"tj","pet":"tobi"}') + .end(callback) + + Since JSON is undoubtably the most common, it's the _default_! The following example is equivalent to the previous. + + request.post('/user') + .send({ name: 'tj', pet: 'tobi' }) + .end(callback) + + Or using multiple `.send()` calls: + + request.post('/user') + .send({ name: 'tj' }) + .send({ pet: 'tobi' }) + .end(callback) + + By default sending strings will set the Content-Type to `application/x-www-form-urlencoded`, + multiple calls will be concatenated with `&`, here resulting in `name=tj&pet=tobi`: + + request.post('/user') + .send('name=tj') + .send('pet=tobi') + .end(callback); + + SuperAgent formats are extensible, however by default "json" and "form" are supported. To send the data as `application/x-www-form-urlencoded` simply invoke `.type()` with "form", where the default is "json". This request will POST the body "name=tj&pet=tobi". + + request.post('/user') + .type('form') + .send({ name: 'tj' }) + .send({ pet: 'tobi' }) + .end(callback) + + Note: "form" is aliased as "form-data" and "urlencoded" for backwards compat. + +## Setting the Content-Type + + The obvious solution is to use the `.set()` method: + + request.post('/user') + .set('Content-Type', 'application/json') + + As a short-hand the `.type()` method is also available, accepting + the canonicalized MIME type name complete with type/subtype, or + simply the extension name such as "xml", "json", "png", etc: + + request.post('/user') + .type('application/json') + + request.post('/user') + .type('json') + + request.post('/user') + .type('png') + +## Setting Accept + +In a similar fashion to the `.type()` method it is also possible to set the Accept header via the short hand method `.accept()`. Which references `request.types` as well allowing you to specify either the full canonicalized MIME type name as type/subtype, or the extension suffix form as "xml", "json", "png", etc for convenience: + + request.get('/user') + .accept('application/json') + + request.get('/user') + .accept('json') + + request.post('/user') + .accept('png') + +## Query strings + + `res.query(obj)` is a method which may be used to build up a query-string. For example populating `?format=json&dest=/login` on a __POST__: + + request + .post('/') + .query({ format: 'json' }) + .query({ dest: '/login' }) + .send({ post: 'data', here: 'wahoo' }) + .end(callback); + +## Parsing response bodies + + Super Agent will parse known response-body data for you, currently supporting _application/x-www-form-urlencoded_, _application/json_, and _multipart/form-data_. + +### JSON / Urlencoded + + The property `res.body` is the parsed object, for example if a request responded with the JSON string '{"user":{"name":"tobi"}}', `res.body.user.name` would be "tobi". Likewise the x-www-form-urlencoded value of "user[name]=tobi" would yield the same result. + +### Multipart + + The Node client supports _multipart/form-data_ via the [Formidable](https://github.com/felixge/node-formidable) module. When parsing multipart responses, the object `res.files` is also available to you. Suppose for example a request responds with the following multipart body: + + --whoop + Content-Disposition: attachment; name="image"; filename="tobi.png" + Content-Type: image/png + + ... data here ... + --whoop + Content-Disposition: form-data; name="name" + Content-Type: text/plain + + Tobi + --whoop-- + + You would have the values `res.body.name` provided as "Tobi", and `res.files.image` as a `File` object containing the path on disk, filename, and other properties. + +## Response properties + + Many helpful flags and properties are set on the `Response` object, ranging from the response text, parsed response body, header fields, status flags and more. + +### Response text + + The `res.text` property contains the unparsed response body string. This + property is always present for the client API, and only when the mime type + matches "text/*", "*/json", or "x-www-form-urlencoding" by default for node. The + reasoning is to conserve memory, as buffering text of large bodies such as multipart files or images is extremely inefficient. + + To force buffering see the "Buffering responses" section. + +### Response body + + Much like SuperAgent can auto-serialize request data, it can also automatically parse it. When a parser is defined for the Content-Type, it is parsed, which by default includes "application/json" and "application/x-www-form-urlencoded". The parsed object is then available via `res.body`. + +### Response header fields + + The `res.header` contains an object of parsed header fields, lowercasing field names much like node does. For example `res.header['content-length']`. + +### Response Content-Type + + The Content-Type response header is special-cased, providing `res.type`, which is void of the charset (if any). For example the Content-Type of "text/html; charset=utf8" will provide "text/html" as `res.type`, and the `res.charset` property would then contain "utf8". + +### Response status + + The response status flags help determine if the request was a success, among other useful information, making SuperAgent ideal for interacting with RESTful web services. These flags are currently defined as: + + var type = status / 100 | 0; + + // status / class + res.status = status; + res.statusType = type; + + // basics + res.info = 1 == type; + res.ok = 2 == type; + res.clientError = 4 == type; + res.serverError = 5 == type; + res.error = 4 == type || 5 == type; + + // sugar + res.accepted = 202 == status; + res.noContent = 204 == status || 1223 == status; + res.badRequest = 400 == status; + res.unauthorized = 401 == status; + res.notAcceptable = 406 == status; + res.notFound = 404 == status; + res.forbidden = 403 == status; + +## Aborting requests + + To abort requests simply invoke the `req.abort()` method. + +## Request timeouts + + A timeout can be applied by invoking `req.timeout(ms)`, after which an error + will be triggered. To differentiate between other errors the `err.timeout` property + is set to the `ms` value. __NOTE__ that this is a timeout applied to the request + and all subsequent redirects, not per request. + +## Basic authentication + + Basic auth is currently provided by the _node_ client in two forms, first via the URL as "user:pass": + + request.get('http://tobi:learnboost@local').end(callback); + + As well as via the `.auth()` method: + + request + .get('http://local') + .auth('tobi', 'learnboost') + .end(callback); + +## Following redirects + + By default up to 5 redirects will be followed, however you may specify this with the `res.redirects(n)` method: + + request + .get('/some.png') + .redirects(2) + .end(callback); + +## Piping data + + The Node client allows you to pipe data to and from the request. For example piping a file's contents as the request: + + var request = require('superagent') + , fs = require('fs'); + + var stream = fs.createReadStream('path/to/my.json'); + var req = request.post('/somewhere'); + req.type('json'); + stream.pipe(req); + + Or piping the response to a file: + + var request = require('superagent') + , fs = require('fs'); + + var stream = fs.createWriteStream('path/to/my.json'); + var req = request.get('/some.json'); + req.pipe(stream); + +## Multipart requests + + Super Agent is also great for _building_ multipart requests for which it provides methods `.attach()` and `.field()`. + +### Attaching files + + As mentioned a higher-level API is also provided, in the form of `.attach(name, [path], [filename])` and `.field(name, value)`. Attaching several files is simple, you can also provide a custom filename for the attachment, otherwise the basename of the attached file is used. + + request + .post('/upload') + .attach('avatar', 'path/to/tobi.png', 'user.png') + .attach('image', 'path/to/loki.png') + .attach('file', 'path/to/jane.png') + .end(callback); + +### Field values + + Much like form fields in HTML, you can set field values with the `.field(name, value)` method. Suppose you want to upload a few images with your name and email, your request might look something like this: + + request + .post('/upload') + .field('user[name]', 'Tobi') + .field('user[email]', 'tobi@learnboost.com') + .attach('image', 'path/to/tobi.png') + .end(callback); + +## Compression + + The node client supports compressed responses, best of all, you don't have to do anything! It just works. + +## Buffering responses + + To force buffering of response bodies as `res.text` you may invoke `req.buffer()`. To undo the default of buffering for text responses such + as "text/plain", "text/html" etc you may invoke `req.buffer(false)`. + + When buffered the `res.buffered` flag is provided, you may use this to + handle both buffered and unbuffered responses in the same callback. + +## CORS + + The `.withCredentials()` method enables the ability to send cookies + from the origin, however only when "Access-Control-Allow-Origin" is + _not_ a wildcard ("*"), and "Access-Control-Allow-Credentials" is "true". + + request + .get('http://localhost:4001/') + .withCredentials() + .end(function(err, res){ + assert(200 == res.status); + assert('tobi' == res.text); + next(); + }) + +## Error handling + +Your callback function will always be passed two arguments: error and response. If no error occurred, the first argument will be null: + + request + .post('/upload') + .attach('image', 'path/to/tobi.png') + .end(function(err, res){ + + }); + + An "error" event is also emitted, with you can listen for: + + request + .post('/upload') + .attach('image', 'path/to/tobi.png') + .on('error', handle) + .end(function(err, res){ + + }); + + Note that a 4xx or 5xx response with super agent **are** considered an error by default. For example if you get a 500 or 403 response, this status information will be available via `err.status`. Errors from such responses also contain an `err.response` field with all of the properties mentioned in "Response properties". The library behaves in this way to handle the common case of wanting success responses and treating HTTP error status codes as errors while still allowing for custom logic around specific error conditions. + + Network failures, timeouts, and other errors that produce no response will contain no `err.status` or `err.response` fields. + + If you wish to handle 404 or other HTTP error responses, you can query the `err.status` property. + When an HTTP error occurs (4xx or 5xx response) the `res.error` property is an `Error` object, + this allows you to perform checks such as: + + if (err && err.status === 404) { + alert('oh no ' + res.body.message); + } + else if (err) { + // all other error types we handle generically + } + +## Generator support + +Superagent now supports easier control flow using generators. By using a generator control flow +like [co](https://github.com/tj/co) or a web framework like [koa](https://github.com/koajs/koa), +you can `yield` on any superagent method: + + var res = yield request + .get('http://local') + .auth('tobi', 'learnboost') diff --git a/5-3/node_modules/superagent/docs/jquery-ui.min.js b/5-3/node_modules/superagent/docs/jquery-ui.min.js new file mode 100644 index 0000000..932f867 --- /dev/null +++ b/5-3/node_modules/superagent/docs/jquery-ui.min.js @@ -0,0 +1,6 @@ +/*! jQuery UI - v1.11.4 - 2015-11-20 +* http://jqueryui.com +* Includes: widget.js +* Copyright jQuery Foundation and other contributors; Licensed MIT */ + +(function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){var t=0,i=Array.prototype.slice;e.cleanData=function(t){return function(i){var s,n,a;for(a=0;null!=(n=i[a]);a++)try{s=e._data(n,"events"),s&&s.remove&&e(n).triggerHandler("remove")}catch(o){}t(i)}}(e.cleanData),e.widget=function(t,i,s){var n,a,o,r,h={},l=t.split(".")[0];return t=t.split(".")[1],n=l+"-"+t,s||(s=i,i=e.Widget),e.expr[":"][n.toLowerCase()]=function(t){return!!e.data(t,n)},e[l]=e[l]||{},a=e[l][t],o=e[l][t]=function(e,t){return this._createWidget?(arguments.length&&this._createWidget(e,t),void 0):new o(e,t)},e.extend(o,a,{version:s.version,_proto:e.extend({},s),_childConstructors:[]}),r=new i,r.options=e.widget.extend({},r.options),e.each(s,function(t,s){return e.isFunction(s)?(h[t]=function(){var e=function(){return i.prototype[t].apply(this,arguments)},n=function(e){return i.prototype[t].apply(this,e)};return function(){var t,i=this._super,a=this._superApply;return this._super=e,this._superApply=n,t=s.apply(this,arguments),this._super=i,this._superApply=a,t}}(),void 0):(h[t]=s,void 0)}),o.prototype=e.widget.extend(r,{widgetEventPrefix:a?r.widgetEventPrefix||t:t},h,{constructor:o,namespace:l,widgetName:t,widgetFullName:n}),a?(e.each(a._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete a._childConstructors):i._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){for(var s,n,a=i.call(arguments,1),o=0,r=a.length;r>o;o++)for(s in a[o])n=a[o][s],a[o].hasOwnProperty(s)&&void 0!==n&&(t[s]=e.isPlainObject(n)?e.isPlainObject(t[s])?e.widget.extend({},t[s],n):e.widget.extend({},n):n);return t},e.widget.bridge=function(t,s){var n=s.prototype.widgetFullName||t;e.fn[t]=function(a){var o="string"==typeof a,r=i.call(arguments,1),h=this;return o?this.each(function(){var i,s=e.data(this,n);return"instance"===a?(h=s,!1):s?e.isFunction(s[a])&&"_"!==a.charAt(0)?(i=s[a].apply(s,r),i!==s&&void 0!==i?(h=i&&i.jquery?h.pushStack(i.get()):i,!1):void 0):e.error("no such method '"+a+"' for "+t+" widget instance"):e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+a+"'")}):(r.length&&(a=e.widget.extend.apply(null,[a].concat(r))),this.each(function(){var t=e.data(this,n);t?(t.option(a||{}),t._init&&t._init()):e.data(this,n,new s(a,this))})),h}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"
",options:{disabled:!1,create:null},_createWidget:function(i,s){s=e(s||this.defaultElement||this)[0],this.element=e(s),this.uuid=t++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=e(),this.hoverable=e(),this.focusable=e(),s!==this&&(e.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===s&&this.destroy()}}),this.document=e(s.style?s.ownerDocument:s.document||s),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this.options=e.widget.extend({},this.options,this._getCreateOptions(),i),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(t,i){var s,n,a,o=t;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof t)if(o={},s=t.split("."),t=s.shift(),s.length){for(n=o[t]=e.widget.extend({},this.options[t]),a=0;s.length-1>a;a++)n[s[a]]=n[s[a]]||{},n=n[s[a]];if(t=s.pop(),1===arguments.length)return void 0===n[t]?null:n[t];n[t]=i}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=i}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,i,s){var n,a=this;"boolean"!=typeof t&&(s=i,i=t,t=!1),s?(i=n=e(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),e.each(s,function(s,o){function r(){return t||a.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?a[o]:o).apply(a,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||e.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+a.eventNamespace,u=h[2];u?n.delegate(u,l,r):i.bind(l,r)})},_off:function(t,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(i).undelegate(i),this.bindings=e(this.bindings.not(t).get()),this.focusable=e(this.focusable.not(t).get()),this.hoverable=e(this.hoverable.not(t).get())},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var n,a,o=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(e.isFunction(o)&&o.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,n,a){"string"==typeof n&&(n={effect:n});var o,r=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),o=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),o&&e.effects&&e.effects.effect[r]?s[t](n):r!==t&&s[r]?s[r](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}}),e.widget}); \ No newline at end of file diff --git a/5-3/node_modules/superagent/docs/jquery.js b/5-3/node_modules/superagent/docs/jquery.js new file mode 100644 index 0000000..d2424e6 --- /dev/null +++ b/5-3/node_modules/superagent/docs/jquery.js @@ -0,0 +1,4 @@ +/*! jQuery v1.7 jquery.com | jquery.org/license */ +(function(a,b){function cA(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cx(a){if(!cm[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cn||(cn=c.createElement("iframe"),cn.frameBorder=cn.width=cn.height=0),b.appendChild(cn);if(!co||!cn.createElement)co=(cn.contentWindow||cn.contentDocument).document,co.write((c.compatMode==="CSS1Compat"?"":"")+""),co.close();d=co.createElement(a),co.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cn)}cm[a]=e}return cm[a]}function cw(a,b){var c={};f.each(cs.concat.apply([],cs.slice(0,b)),function(){c[this]=a});return c}function cv(){ct=b}function cu(){setTimeout(cv,0);return ct=f.now()}function cl(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ck(){try{return new a.XMLHttpRequest}catch(b){}}function ce(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bB(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function br(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bi,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bq(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bp(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bp)}function bp(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bo(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bn(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bm(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d=0===c})}function V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(){return!0}function M(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z]|[0-9])/ig,x=/^-ms-/,y=function(a,b){return(b+"").toUpperCase()},z=d.userAgent,A,B,C,D=Object.prototype.toString,E=Object.prototype.hasOwnProperty,F=Array.prototype.push,G=Array.prototype.slice,H=String.prototype.trim,I=Array.prototype.indexOf,J={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=n.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7",length:0,size:function(){return this.length},toArray:function(){return G.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?F.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),B.add(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(G.apply(this,arguments),"slice",G.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:F,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;B.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!B){B=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",C,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",C),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&K()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return a!=null&&m.test(a)&&!isNaN(a)},type:function(a){return a==null?String(a):J[D.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!E.call(a,"constructor")&&!E.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||E.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(x,"ms-").replace(w,y)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,unknownElems:!!a.getElementsByTagName("nav").length,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",enctype:!!c.createElement("form").enctype,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.lastChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},m&&f.extend(p,{position:"absolute",left:"-999px",top:"-999px"});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="
",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="
t
",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;f(function(){var a,b,d,e,g,h,i=1,j="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",l="visibility:hidden;border:0;",n="style='"+j+"border:5px solid #000;padding:0;'",p="
"+""+"
";m=c.getElementsByTagName("body")[0];!m||(a=c.createElement("div"),a.style.cssText=l+"width:0;height:0;position:static;top:0;margin-top:"+i+"px",m.insertBefore(a,m.firstChild),o=c.createElement("div"),o.style.cssText=j+l,o.innerHTML=p,a.appendChild(o),b=o.firstChild,d=b.firstChild,g=b.nextSibling.firstChild.firstChild,h={doesNotAddBorder:d.offsetTop!==5,doesAddBorderForTableAndCells:g.offsetTop===5},d.style.position="fixed",d.style.top="20px",h.fixedPosition=d.offsetTop===20||d.offsetTop===15,d.style.position=d.style.top="",b.style.overflow="hidden",b.style.position="relative",h.subtractsBorderForOverflowNotVisible=d.offsetTop===-5,h.doesNotIncludeMarginInBodyOffset=m.offsetTop!==i,m.removeChild(a),o=a=null,f.extend(k,h))}),o.innerHTML="",n.removeChild(o),o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[f.expando]:a[f.expando]&&f.expando,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[f.expando]=n=++f.uuid:n=f.expando),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[f.expando]:f.expando;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)?b=b:b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" "));for(e=0,g=b.length;e-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];if(!arguments.length){if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}return b}e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!a||j===3||j===8||j===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g},removeAttr:function(a,b){var c,d,e,g,h=0;if(a.nodeType===1){d=(b||"").split(p),g=d.length;for(;h=0}})});var z=/\.(.*)$/,A=/^(?:textarea|input|select)$/i,B=/\./g,C=/ /g,D=/[^\w\s.|`]/g,E=/^([^\.]*)?(?:\.(.+))?$/,F=/\bhover(\.\S+)?/,G=/^key/,H=/^(?:mouse|contextmenu)|click/,I=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,J=function(a){var b=I.exec(a);b&& +(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},K=function(a,b){return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||a.id===b[2])&&(!b[3]||b[3].test(a.className))},L=function(a){return f.event.special.hover?a:a.replace(F,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=L(c).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"",(g||!e)&&c.preventDefault();if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,n=null;for(m=e.parentNode;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l=0:t===b&&(t=o[s]=r.quick?K(m,r.quick):f(m).is(s)),t&&q.push(r);q.length&&j.push({elem:m,matches:q})}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),G.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),H.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(V(c[0])||V(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var Y="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",Z=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,_=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,ba=/<([\w:]+)/,bb=/",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bk=X(c);bj.optgroup=bj.option,bj.tbody=bj.tfoot=bj.colgroup=bj.caption=bj.thead,bj.th=bj.td,f.support.htmlSerialize||(bj._default=[1,"div
","
"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){f(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after" +,arguments);a.push.apply(a,f(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Z,""):null;if(typeof a=="string"&&!bd.test(a)&&(f.support.leadingWhitespace||!$.test(a))&&!bj[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(_,"<$1>");try{for(var c=0,d=this.length;c1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bn(a,d),e=bo(a),g=bo(d);for(h=0;e[h];++h)g[h]&&bn(e[h],g[h])}if(b){bm(a,d);if(c){e=bo(a),g=bo(d);for(h=0;e[h];++h)bm(e[h],g[h])}}e=g=null;return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!bc.test(k))k=b.createTextNode(k);else{k=k.replace(_,"<$1>");var l=(ba.exec(k)||["",""])[1].toLowerCase(),m=bj[l]||bj._default,n=m[0],o=b.createElement("div");b===c?bk.appendChild(o):X(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=bb.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]===""&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&$.test(k)&&o.insertBefore(b.createTextNode($.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bt.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bs,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bs.test(g)?g.replace(bs,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bB(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bC=function(a,c){var d,e,g;c=c.replace(bu,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bD=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bv.test(f)&&bw.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bB=bC||bD,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bF=/%20/g,bG=/\[\]$/,bH=/\r?\n/g,bI=/#.*$/,bJ=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bK=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bL=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bM=/^(?:GET|HEAD)$/,bN=/^\/\//,bO=/\?/,bP=/)<[^<]*)*<\/script>/gi,bQ=/^(?:select|textarea)/i,bR=/\s+/,bS=/([?&])_=[^&]*/,bT=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bU=f.fn.load,bV={},bW={},bX,bY,bZ=["*/"]+["*"];try{bX=e.href}catch(b$){bX=c.createElement("a"),bX.href="",bX=bX.href}bY=bT.exec(bX.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bU)return bU.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
").append(c.replace(bP,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bQ.test(this.nodeName)||bK.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bH,"\r\n")}}):{name:b.name,value:c.replace(bH,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?cb(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),cb(a,b);return a},ajaxSettings:{url:bX,isLocal:bL.test(bY[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bZ},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:b_(bV),ajaxTransport:b_(bW),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cd(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=ce(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bJ.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bI,"").replace(bN,bY[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bR),d.crossDomain==null&&(r=bT.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bY[1]&&r[2]==bY[2]&&(r[3]||(r[1]==="http:"?80:443))==(bY[3]||(bY[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),ca(bV,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bM.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bO.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bS,"$1_="+x);d.url=y+(y===d.url?(bO.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bZ+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=ca(bW,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){s<2?w(-1,z):f.error(z)}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)cc(g,a[g],c,e);return d.join("&").replace(bF,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cf=f.now(),cg=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cf++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cg.test(b.url)||e&&cg.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cg,l),b.url===j&&(e&&(k=k.replace(cg,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ch=a.ActiveXObject?function(){for(var a in cj)cj[a](0,1)}:!1,ci=0,cj;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ck()||cl()}:ck,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ch&&delete cj[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++ci,ch&&(cj||(cj={},f(a).unload(ch)),cj[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cm={},cn,co,cp=/^(?:toggle|show|hide)$/,cq=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cr,cs=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],ct;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cw("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cz.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cz.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cA(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cA(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window); \ No newline at end of file diff --git a/5-3/node_modules/superagent/docs/jquery.tocify.min.js b/5-3/node_modules/superagent/docs/jquery.tocify.min.js new file mode 100755 index 0000000..0fc0442 --- /dev/null +++ b/5-3/node_modules/superagent/docs/jquery.tocify.min.js @@ -0,0 +1,4 @@ +/*! jquery.tocify - v1.9.0 - 2013-10-01 +* http://gregfranko.com/jquery.tocify.js/ +* Copyright (c) 2013 Greg Franko; Licensed MIT*/ +(function(e){"use strict";e(window.jQuery,window,document)})(function(e,t,s){"use strict";var i="tocify",o="tocify-focus",n="tocify-hover",a="tocify-hide",l="tocify-header",h="."+l,r="tocify-subheader",d="."+r,c="tocify-item",f="."+c,u="tocify-extend-page",p="."+u;e.widget("toc.tocify",{version:"1.9.0",options:{context:"body",ignoreSelector:null,selectors:"h1, h2, h3",showAndHide:!0,showEffect:"slideDown",showEffectSpeed:"medium",hideEffect:"slideUp",hideEffectSpeed:"medium",smoothScroll:!0,smoothScrollSpeed:"medium",scrollTo:0,showAndHideOnScroll:!0,highlightOnScroll:!0,highlightOffset:40,theme:"bootstrap",extendPage:!0,extendPageOffset:100,history:!0,scrollHistory:!1,hashGenerator:"compact",highlightDefault:!0},_create:function(){var s=this;s.extendPageScroll=!0,s.items=[],s._generateToc(),s._addCSSClasses(),s.webkit=function(){for(var e in t)if(e&&-1!==e.toLowerCase().indexOf("webkit"))return!0;return!1}(),s._setEventHandlers(),e(t).load(function(){s._setActiveElement(!0),e("html, body").promise().done(function(){setTimeout(function(){s.extendPageScroll=!1},0)})})},_generateToc:function(){var t,s,o=this,n=o.options.ignoreSelector;return t=-1!==this.options.selectors.indexOf(",")?e(this.options.context).find(this.options.selectors.replace(/ /g,"").substr(0,this.options.selectors.indexOf(","))):e(this.options.context).find(this.options.selectors.replace(/ /g,"")),t.length?(o.element.addClass(i),t.each(function(t){e(this).is(n)||(s=e("
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
The following features can be disabled
Feature(s)Command line identifier
.any and Promise.anyany
.race and Promise.racerace
.call and .getcall_get
.filter and Promise.filterfilter
.map and Promise.mapmap
.reduce and Promise.reducereduce
.props and Promise.propsprops
.settle and Promise.settlesettle
.some and Promise.somesome
.nodeifynodeify
Promise.coroutine and Promise.spawngenerators
Progressionprogress
Promisificationpromisify
Cancellationcancel
Timerstimers
Resource managementusing
+ + +Make sure you have cloned the repo somewhere and did `npm install` successfully. + +After that you can run: + + node tools/build --features="core" + + +The above builds the most minimal build you can get. You can add more features separated by spaces from the above list: + + node tools/build --features="core filter map reduce" + +The custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features. + +Note that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build +a full version afterwards (after having taken a copy of the bluebird.js somewhere): + + node tools/build --debug --main --zalgo --browser --minify + +#### Supported options by the build tool + +The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`. + + - `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`. + - `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`. + - `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`. + - `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`. + - `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`. + - `--features=String` - See [custom builds](#custom-builds) + +
+ +## For library authors + +Building a library that depends on bluebird? You should know about a few features. + +If your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require("bluebird")`. Instead you should create a file +that creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains: + +```js + //NOTE the function call right after +module.exports = require("bluebird/js/main/promise")(); +``` + +Your library can then use `var Promise = require("bluebird-extended");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic. + +You should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---promise) which makes it easy to provide a dual callback/promise API. + +
+ +## What is the sync build? + +You may now use sync build by: + + var Promise = require("bluebird/zalgo"); + +The sync build is provided to see how forced asynchronity affects benchmarks. It should not be used in real code due to the implied hazards. + +The normal async build gives Promises/A+ guarantees about asynchronous resolution of promises. Some people think this affects performance or just plain love their code having a possibility +of stack overflow errors and non-deterministic behavior. + +The sync build skips the async call trampoline completely, e.g code like: + + async.invoke( this.fn, this, val ); + +Appears as this in the sync build: + + this.fn(val); + +This should pressure the CPU slightly less and thus the sync build should perform better. Indeed it does, but only marginally. The biggest performance boosts are from writing efficient Javascript, not from compromising determinism. + +Note that while some benchmarks are waiting for the next event tick, the CPU is actually not in use during that time. So the resulting benchmark result is not completely accurate because on node.js you only care about how much the CPU is taxed. Any time spent on CPU is time the whole process (or server) is paralyzed. And it is not graceful like it would be with threads. + + +```js +var cache = new Map(); //ES6 Map or DataStructures/Map or whatever... +function getResult(url) { + var resolver = Promise.pending(); + if (cache.has(url)) { + resolver.resolve(cache.get(url)); + } + else { + http.get(url, function(err, content) { + if (err) resolver.reject(err); + else { + cache.set(url, content); + resolver.resolve(content); + } + }); + } + return resolver.promise; +} + + + +//The result of console.log is truly random without async guarantees +function guessWhatItPrints( url ) { + var i = 3; + getResult(url).then(function(){ + i = 4; + }); + console.log(i); +} +``` + +# Optimization guide + +Articles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome. + +A single cohesive guide compiled from the articles will probably be done eventually. + +# License + +The MIT License (MIT) + +Copyright (c) 2014 Petka Antonov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..46729e1 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/changelog.md @@ -0,0 +1,1643 @@ +## 2.9.26 (2015-05-25) + +Bugfixes: + + - Fix crash in NW [#624](.) + - Fix [`.return()`](.) not supporting `undefined` as return value [#627](.) + +## 2.9.25 (2015-04-28) + +Bugfixes: + + - Fix crash in node 0.8 + +## 2.9.24 (2015-04-02) + +Bugfixes: + + - Fix not being able to load multiple bluebird copies introduced in 2.9.22 ([#559](.), [#561](.), [#560](.)). + +## 2.9.23 (2015-04-02) + +Bugfixes: + + - Fix node.js domain propagation ([#521](.)). + +## 2.9.22 (2015-04-02) + + - Fix `.promisify` crashing in phantom JS ([#556](.)) + +## 2.9.21 (2015-03-30) + + - Fix error object's `'stack'`' overwriting causing an error when its defined to be a setter that throws an error ([#552](.)). + +## 2.9.20 (2015-03-29) + +Bugfixes: + + - Fix regression where there is a long delay between calling `.cancel()` and promise actually getting cancelled in Chrome when long stack traces are enabled + +## 2.9.19 (2015-03-29) + +Bugfixes: + + - Fix crashing in Chrome when long stack traces are disabled + +## 2.9.18 (2015-03-29) + +Bugfixes: + + - Fix settlePromises using trampoline + +## 2.9.17 (2015-03-29) + + +Bugfixes: + + - Fix Chrome DevTools async stack traceability ([#542](.)). + +## 2.9.16 (2015-03-28) + +Features: + + - Use setImmediate if available + +## 2.9.15 (2015-03-26) + +Features: + + - Added `.asCallback` alias for `.nodeify`. + +Bugfixes: + + - Don't always use nextTick, but try to pick up setImmediate or setTimeout in NW. Fixes [#534](.), [#525](.) + - Make progress a core feature. Fixes [#535](.) Note that progress has been removed in 3.x - this is only a fix necessary for 2.x custom builds. + +## 2.9.14 (2015-03-12) + +Bugfixes: + + - Always use process.nextTick. Fixes [#525](.) + +## 2.9.13 (2015-02-27) + +Bugfixes: + + - Fix .each, .filter, .reduce and .map callbacks being called synchornously if the input is immediate. ([#513](.)) + +## 2.9.12 (2015-02-19) + +Bugfixes: + + - Fix memory leak introduced in 2.9.0 ([#502](.)) + +## 2.9.11 (2015-02-19) + +Bugfixes: + + - Fix [#503](.) + +## 2.9.10 (2015-02-18) + +Bugfixes: + + - Fix [#501](.) + +## 2.9.9 (2015-02-12) + +Bugfixes: + + - Fix `TypeError: Cannot assign to read only property 'length'` when jsdom has declared a read-only length for all objects to inherit. + +## 2.9.8 (2015-02-10) + +Bugfixes: + + - Fix regression introduced in 2.9.7 where promisify didn't properly dynamically look up methods on `this` + +## 2.9.7 (2015-02-08) + +Bugfixes: + + - Fix `promisify` not retaining custom properties of the function. This enables promisifying the `"request"` module's export function and its methods at the same time. + - Fix `promisifyAll` methods being dependent on `this` when they are not originally dependent on `this`. This enables e.g. passing promisified `fs` functions directly as callbacks without having to bind them to `fs`. + - Fix `process.nextTick` being used over `setImmediate` in node. + +## 2.9.6 (2015-02-02) + +Bugfixes: + + - Node environment detection can no longer be fooled + +## 2.9.5 (2015-02-02) + +Misc: + + - Warn when [`.then()`](.) is passed non-functions + +## 2.9.4 (2015-01-30) + +Bugfixes: + + - Fix [.timeout()](.) not calling `clearTimeout` with the proper handle in node causing the process to wait for unneeded timeout. This was a regression introduced in 2.9.1. + +## 2.9.3 (2015-01-27) + +Bugfixes: + + - Fix node-webkit compatibility issue ([#467](https://github.com/petkaantonov/bluebird/pull/467)) + - Fix long stack trace support in recent firefox versions + +## 2.9.2 (2015-01-26) + +Bugfixes: + + - Fix critical bug regarding to using promisifyAll in browser that was introduced in 2.9.0 ([#466](https://github.com/petkaantonov/bluebird/issues/466)). + +Misc: + + - Add `"browser"` entry point to package.json + +## 2.9.1 (2015-01-24) + +Features: + + - If a bound promise is returned by the callback to [`Promise.method`](#promisemethodfunction-fn---function) and [`Promise.try`](#promisetryfunction-fn--arraydynamicdynamic-arguments--dynamic-ctx----promise), the returned promise will be bound to the same value + +## 2.9.0 (2015-01-24) + +Features: + + - Add [`Promise.fromNode`](API.md#promisefromnodefunction-resolver---promise) + - Add new paramter `value` for [`Promise.bind`](API.md#promisebinddynamic-thisarg--dynamic-value---promise) + +Bugfixes: + + - Fix several issues with [`cancellation`](API.md#cancellation) and [`.bind()`](API.md#binddynamic-thisarg---promise) interoperation when `thisArg` is a promise or thenable + - Fix promises created in [`disposers`](API#disposerfunction-disposer---disposer) not having proper long stack trace context + - Fix [`Promise.join`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) sometimes passing the passed in callback function as the last argument to itself. + +Misc: + + - Reduce minified full browser build file size by not including unused code generation functionality. + - Major internal refactoring related to testing code and source code file layout + +## 2.8.2 (2015-01-20) + +Features: + + - [Global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) are now fired both as DOM3 events and as legacy events in browsers + +## 2.8.1 (2015-01-20) + +Bugfixes: + + - Fix long stack trace stiching consistency when rejected from thenables + +## 2.8.0 (2015-01-19) + +Features: + + - Major debuggability improvements: + - Long stack traces have been re-designed. They are now much more readable, + succint, relevant and consistent across bluebird features. + - Long stack traces are supported now in IE10+ + +## 2.7.1 (2015-01-15) + +Bugfixes: + + - Fix [#447](https://github.com/petkaantonov/bluebird/issues/447) + +## 2.7.0 (2015-01-15) + +Features: + + - Added more context to stack traces originating from coroutines ([#421](https://github.com/petkaantonov/bluebird/issues/421)) + - Implemented [global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) ([#428](https://github.com/petkaantonov/bluebird/issues/428), [#357](https://github.com/petkaantonov/bluebird/issues/357)) + - [Custom promisifiers](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-promisifier) are now passed the default promisifier which can be used to add enhancements on top of normal node promisification + - [Promisification filters](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-filter) are now passed `passesDefaultFilter` boolean + +Bugfixes: + + - Fix `.noConflict()` call signature ([#446]()) + - Fix `Promise.method`ified functions being called with `undefined` when they were called with no arguments + +## 2.6.4 (2015-01-12) + +Bugfixes: + + - `OperationalErrors` thrown by promisified functions retain custom properties, such as `.code` and `.path`. + +## 2.6.3 (2015-01-12) + +Bugfixes: + + - Fix [#429](https://github.com/petkaantonov/bluebird/issues/429) + - Fix [#432](https://github.com/petkaantonov/bluebird/issues/432) + - Fix [#433](https://github.com/petkaantonov/bluebird/issues/433) + +## 2.6.2 (2015-01-07) + +Bugfixes: + + - Fix [#426](https://github.com/petkaantonov/bluebird/issues/426) + +## 2.6.1 (2015-01-07) + +Bugfixes: + + - Fixed built browser files not being included in the git tag release for bower + +## 2.6.0 (2015-01-06) + +Features: + + - Significantly improve parallel promise performance and memory usage (+50% faster, -50% less memory) + + +## 2.5.3 (2014-12-30) + +## 2.5.2 (2014-12-29) + +Bugfixes: + + - Fix bug where already resolved promise gets attached more handlers while calling its handlers resulting in some handlers not being called + - Fix bug where then handlers are not called in the same order as they would run if Promises/A+ 2.3.2 was implemented as adoption + - Fix bug where using `Object.create(null)` as a rejection reason would crash bluebird + +## 2.5.1 (2014-12-29) + +Bugfixes: + + - Fix `.finally` throwing null error when it is derived from a promise that is resolved with a promise that is resolved with a promise + +## 2.5.0 (2014-12-28) + +Features: + + - [`.get`](#API.md#https://github.com/petkaantonov/bluebird/blob/master/API.md#getstring-propertyname---promise) now supports negative indexing. + +Bugfixes: + + - Fix bug with `Promise.method` wrapped function returning a promise that never resolves if the function returns a promise that is resolved with another promise + - Fix bug with `Promise.delay` never resolving if the value is a promise that is resolved with another promise + +## 2.4.3 (2014-12-28) + +Bugfixes: + + - Fix memory leak as described in [this Promises/A+ spec issue](https://github.com/promises-aplus/promises-spec/issues/179). + +## 2.4.2 (2014-12-21) + +Bugfixes: + + - Fix bug where spread rejected handler is ignored in case of rejection + - Fix synchronous scheduler passed to `setScheduler` causing infinite loop + +## 2.4.1 (2014-12-20) + +Features: + + - Error messages now have links to wiki pages for additional information + - Promises now clean up all references (to handlers, child promises etc) as soon as possible. + +## 2.4.0 (2014-12-18) + +Features: + + - Better filtering of bluebird internal calls in long stack traces, especially when using minified file in browsers + - Small performance improvements for all collection methods + - Promises now delete references to handlers attached to them as soon as possible + - Additional stack traces are now output on stderr/`console.warn` for errors that are thrown in the process/window from rejected `.done()` promises. See [#411](https://github.com/petkaantonov/bluebird/issues/411) + +## 2.3.11 (2014-10-31) + +Bugfixes: + + - Fix [#371](https://github.com/petkaantonov/bluebird/issues/371), [#373](https://github.com/petkaantonov/bluebird/issues/373) + + +## 2.3.10 (2014-10-28) + +Features: + + - `Promise.method` no longer wraps primitive errors + - `Promise.try` no longer wraps primitive errors + +## 2.3.7 (2014-10-25) + +Bugfixes: + + - Fix [#359](https://github.com/petkaantonov/bluebird/issues/359), [#362](https://github.com/petkaantonov/bluebird/issues/362) and [#364](https://github.com/petkaantonov/bluebird/issues/364) + +## 2.3.6 (2014-10-15) + +Features: + + - Implement [`.reflect()`](API.md#reflect---promisepromiseinspection) + +## 2.3.5 (2014-10-06) + +Bugfixes: + + - Fix issue when promisifying methods whose names contain the string 'args' + +## 2.3.4 (2014-09-27) + + - `P` alias was not declared inside WebWorkers + +## 2.3.3 (2014-09-27) + +Bugfixes: + + - Fix [#318](https://github.com/petkaantonov/bluebird/issues/318), [#314](https://github.com/petkaantonov/bluebird/issues/#314) + +## 2.3.2 (2014-08-25) + +Bugfixes: + + - `P` alias for `Promise` now exists in global scope when using browser builds without a module loader, fixing an issue with firefox extensions + +## 2.3.1 (2014-08-23) + +Features: + + - `.using` can now be used with disposers created from different bluebird copy + +## 2.3.0 (2014-08-13) + +Features: + + - [`.bind()`](API.md#binddynamic-thisarg---promise) and [`Promise.bind()`](API.md#promisebinddynamic-thisarg---promise) now await for the resolution of the `thisArg` if it's a promise or a thenable + +Bugfixes: + + - Fix [#276](https://github.com/petkaantonov/bluebird/issues/276) + +## 2.2.2 (2014-07-14) + + - Fix [#259](https://github.com/petkaantonov/bluebird/issues/259) + +## 2.2.1 (2014-07-07) + + - Fix multiline error messages only showing the first line + +## 2.2.0 (2014-07-07) + +Bugfixes: + + - `.any` and `.some` now consistently reject with RangeError when input array contains too few promises + - Fix iteration bug with `.reduce` when input array contains already fulfilled promises + +## 2.1.3 (2014-06-18) + +Bugfixes: + + - Fix [#235](https://github.com/petkaantonov/bluebird/issues/235) + +## 2.1.2 (2014-06-15) + +Bugfixes: + + - Fix [#232](https://github.com/petkaantonov/bluebird/issues/232) + +## 2.1.1 (2014-06-11) + +## 2.1.0 (2014-06-11) + +Features: + + - Add [`promisifier`](API.md#option-promisifier) option to `Promise.promisifyAll()` + - Improve performance of `.props()` and collection methods when used with immediate values + + +Bugfixes: + + - Fix a bug where .reduce calls the callback for an already visited item + - Fix a bug where stack trace limit is calculated to be too small, which resulted in too short stack traces + +Add undocumented experimental `yieldHandler` option to `Promise.coroutine` + +## 2.0.7 (2014-06-08) +## 2.0.6 (2014-06-07) +## 2.0.5 (2014-06-05) +## 2.0.4 (2014-06-05) +## 2.0.3 (2014-06-05) +## 2.0.2 (2014-06-04) +## 2.0.1 (2014-06-04) + +## 2.0.0 (2014-06-04) + +#What's new in 2.0 + +- [Resource management](API.md#resource-management) - never leak resources again +- [Promisification](API.md#promisification) on steroids - entire modules can now be promisified with one line of code +- [`.map()`](API.md#mapfunction-mapper--object-options---promise), [`.each()`](API.md#eachfunction-iterator---promise), [`.filter()`](API.md#filterfunction-filterer--object-options---promise), [`.reduce()`](API.md#reducefunction-reducer--dynamic-initialvalue---promise) reimagined from simple sugar to powerful concurrency coordination tools +- [API Documentation](API.md) has been reorganized and more elaborate examples added +- Deprecated [progression](#progression-migration) and [deferreds](#deferred-migration) +- Improved performance and readability + +Features: + +- Added [`using()`](API.md#promiseusingpromisedisposer-promise-promisedisposer-promise--function-handler---promise) and [`disposer()`](API.md#disposerfunction-disposer---disposer) +- [`.map()`](API.md#mapfunction-mapper--object-options---promise) now calls the handler as soon as items in the input array become fulfilled +- Added a concurrency option to [`.map()`](API.md#mapfunction-mapper--object-options---promise) +- [`.filter()`](API.md#filterfunction-filterer--object-options---promise) now calls the handler as soon as items in the input array become fulfilled +- Added a concurrency option to [`.filter()`](API.md#filterfunction-filterer--object-options---promise) +- [`.reduce()`](API.md#reducefunction-reducer--dynamic-initialvalue---promise) now calls the handler as soon as items in the input array become fulfilled, but in-order +- Added [`.each()`](API.md#eachfunction-iterator---promise) +- [`Promise.resolve()`](API.md#promiseresolvedynamic-value---promise) behaves like `Promise.cast`. `Promise.cast` deprecated. +- [Synchronous inspection](API.md#synchronous-inspection): Removed `.inspect()`, added [`.value()`](API.md#value---dynamic) and [`.reason()`](API.md#reason---dynamic) +- [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) now takes a function as the last argument +- Added [`Promise.setScheduler()`](API.md#promisesetschedulerfunction-scheduler---void) +- [`.cancel()`](API.md#cancelerror-reason---promise) supports a custom cancellation reason +- [`.timeout()`](API.md#timeoutint-ms--string-message---promise) now cancels the promise instead of rejecting it +- [`.nodeify()`](API.md#nodeifyfunction-callback--object-options---promise) now supports passing multiple success results when mapping promises to nodebacks +- Added `suffix` and `filter` options to [`Promise.promisifyAll()`](API.md#promisepromisifyallobject-target--object-options---object) + +Breaking changes: + +- Sparse array holes are not skipped by collection methods but treated as existing elements with `undefined` value +- `.map()` and `.filter()` do not call the given mapper or filterer function in any specific order +- Removed the `.inspect()` method +- Yielding an array from a coroutine is not supported by default. You can use [`coroutine.addYieldHandler()`](API.md#promisecoroutineaddyieldhandlerfunction-handler---void) to configure the old behavior (or any behavior you want). +- [`.any()`](API.md#any---promise) and [`.some()`](API.md#someint-count---promise) no longer use an array as the rejection reason. [`AggregateError`](API.md#aggregateerror) is used instead. + + +## 1.2.4 (2014-04-27) + +Bugfixes: + + - Fix promisifyAll causing a syntax error when a method name is not a valid identifier + - Fix syntax error when es5.js is used in strict mode + +## 1.2.3 (2014-04-17) + +Bugfixes: + + - Fix [#179](https://github.com/petkaantonov/bluebird/issues/179) + +## 1.2.2 (2014-04-09) + +Bugfixes: + + - Promisified methods from promisifyAll no longer call the original method when it is overriden + - Nodeify doesn't pass second argument to the callback if the promise is fulfilled with `undefined` + +## 1.2.1 (2014-03-31) + +Bugfixes: + + - Fix [#168](https://github.com/petkaantonov/bluebird/issues/168) + +## 1.2.0 (2014-03-29) + +Features: + + - New method: [`.value()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#value---dynamic) + - New method: [`.reason()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#reason---dynamic) + - New method: [`Promise.onUnhandledRejectionHandled()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promiseonunhandledrejectionhandledfunction-handler---undefined) + - `Promise.map()`, `.map()`, `Promise.filter()` and `.filter()` start calling their callbacks as soon as possible while retaining a correct order. See [`8085922f`](https://github.com/petkaantonov/bluebird/commit/8085922fb95a9987fda0cf2337598ab4a98dc315). + +Bugfixes: + + - Fix [#165](https://github.com/petkaantonov/bluebird/issues/165) + - Fix [#166](https://github.com/petkaantonov/bluebird/issues/166) + +## 1.1.1 (2014-03-18) + +Bugfixes: + + - [#138](https://github.com/petkaantonov/bluebird/issues/138) + - [#144](https://github.com/petkaantonov/bluebird/issues/144) + - [#148](https://github.com/petkaantonov/bluebird/issues/148) + - [#151](https://github.com/petkaantonov/bluebird/issues/151) + +## 1.1.0 (2014-03-08) + +Features: + + - Implement [`Promise.prototype.tap()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#tapfunction-handler---promise) + - Implement [`Promise.coroutine.addYieldHandler()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisecoroutineaddyieldhandlerfunction-handler---void) + - Deprecate `Promise.prototype.spawn` + +Bugfixes: + + - Fix already rejected promises being reported as unhandled when handled through collection methods + - Fix browserisfy crashing from checking `process.version.indexOf` + +## 1.0.8 (2014-03-03) + +Bugfixes: + + - Fix active domain being lost across asynchronous boundaries in Node.JS 10.xx + +## 1.0.7 (2014-02-25) + +Bugfixes: + + - Fix handled errors being reported + +## 1.0.6 (2014-02-17) + +Bugfixes: + + - Fix bug with unhandled rejections not being reported + when using `Promise.try` or `Promise.method` without + attaching further handlers + +## 1.0.5 (2014-02-15) + +Features: + + - Node.js performance: promisified functions try to check amount of passed arguments in most optimal order + - Node.js promisified functions will have same `.length` as the original function minus one (for the callback parameter) + +## 1.0.4 (2014-02-09) + +Features: + + - Possibly unhandled rejection handler will always get a stack trace, even if the rejection or thrown error was not an error + - Unhandled rejections are tracked per promise, not per error. So if you create multiple branches from a single ancestor and that ancestor gets rejected, each branch with no error handler with the end will cause a possibly unhandled rejection handler invocation + +Bugfixes: + + - Fix unhandled non-writable objects or primitives not reported by possibly unhandled rejection handler + +## 1.0.3 (2014-02-05) + +Bugfixes: + + - [#93](https://github.com/petkaantonov/bluebird/issues/88) + +## 1.0.2 (2014-02-04) + +Features: + + - Significantly improve performance of foreign bluebird thenables + +Bugfixes: + + - [#88](https://github.com/petkaantonov/bluebird/issues/88) + +## 1.0.1 (2014-01-28) + +Features: + + - Error objects that have property `.isAsync = true` will now be caught by `.error()` + +Bugfixes: + + - Fix TypeError and RangeError shims not working without `new` operator + +## 1.0.0 (2014-01-12) + +Features: + + - `.filter`, `.map`, and `.reduce` no longer skip sparse array holes. This is a backwards incompatible change. + - Like `.map` and `.filter`, `.reduce` now allows returning promises and thenables from the iteration function. + +Bugfixes: + + - [#58](https://github.com/petkaantonov/bluebird/issues/58) + - [#61](https://github.com/petkaantonov/bluebird/issues/61) + - [#64](https://github.com/petkaantonov/bluebird/issues/64) + - [#60](https://github.com/petkaantonov/bluebird/issues/60) + +## 0.11.6-1 (2013-12-29) + +## 0.11.6-0 (2013-12-29) + +Features: + + - You may now return promises and thenables from the filterer function used in `Promise.filter` and `Promise.prototype.filter`. + + - `.error()` now catches additional sources of rejections: + + - Rejections originating from `Promise.reject` + + - Rejections originating from thenables using + the `reject` callback + + - Rejections originating from promisified callbacks + which use the `errback` argument + + - Rejections originating from `new Promise` constructor + where the `reject` callback is called explicitly + + - Rejections originating from `PromiseResolver` where + `.reject()` method is called explicitly + +Bugfixes: + + - Fix `captureStackTrace` being called when it was `null` + - Fix `Promise.map` not unwrapping thenables + +## 0.11.5-1 (2013-12-15) + +## 0.11.5-0 (2013-12-03) + +Features: + + - Improve performance of collection methods + - Improve performance of promise chains + +## 0.11.4-1 (2013-12-02) + +## 0.11.4-0 (2013-12-02) + +Bugfixes: + + - Fix `Promise.some` behavior with arguments like negative integers, 0... + - Fix stack traces of synchronously throwing promisified functions' + +## 0.11.3-0 (2013-12-02) + +Features: + + - Improve performance of generators + +Bugfixes: + + - Fix critical bug with collection methods. + +## 0.11.2-0 (2013-12-02) + +Features: + + - Improve performance of all collection methods + +## 0.11.1-0 (2013-12-02) + +Features: + +- Improve overall performance. +- Improve performance of promisified functions. +- Improve performance of catch filters. +- Improve performance of .finally. + +Bugfixes: + +- Fix `.finally()` rejecting if passed non-function. It will now ignore non-functions like `.then`. +- Fix `.finally()` not converting thenables returned from the handler to promises. +- `.spread()` now rejects if the ultimate value given to it is not spreadable. + +## 0.11.0-0 (2013-12-02) + +Features: + + - Improve overall performance when not using `.bind()` or cancellation. + - Promises are now not cancellable by default. This is backwards incompatible change - see [`.cancellable()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#cancellable---promise) + - [`Promise.delay`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisedelaydynamic-value-int-ms---promise) + - [`.delay()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#delayint-ms---promise) + - [`.timeout()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#timeoutint-ms--string-message---promise) + +## 0.10.14-0 (2013-12-01) + +Bugfixes: + + - Fix race condition when mixing 3rd party asynchrony. + +## 0.10.13-1 (2013-11-30) + +## 0.10.13-0 (2013-11-30) + +Bugfixes: + + - Fix another bug with progression. + +## 0.10.12-0 (2013-11-30) + +Bugfixes: + + - Fix bug with progression. + +## 0.10.11-4 (2013-11-29) + +## 0.10.11-2 (2013-11-29) + +Bugfixes: + + - Fix `.race()` not propagating bound values. + +## 0.10.11-1 (2013-11-29) + +Features: + + - Improve performance of `Promise.race` + +## 0.10.11-0 (2013-11-29) + +Bugfixes: + + - Fixed `Promise.promisifyAll` invoking property accessors. Only data properties with function values are considered. + +## 0.10.10-0 (2013-11-28) + +Features: + + - Disable long stack traces in browsers by default. Call `Promise.longStackTraces()` to enable them. + +## 0.10.9-1 (2013-11-27) + +Bugfixes: + + - Fail early when `new Promise` is constructed incorrectly + +## 0.10.9-0 (2013-11-27) + +Bugfixes: + + - Promise.props now takes a [thenable-for-collection](https://github.com/petkaantonov/bluebird/blob/f41edac61b7c421608ff439bb5a09b7cffeadcf9/test/mocha/props.js#L197-L217) + - All promise collection methods now reject when a promise-or-thenable-for-collection turns out not to give a collection + +## 0.10.8-0 (2013-11-25) + +Features: + + - All static collection methods take thenable-for-collection + +## 0.10.7-0 (2013-11-25) + +Features: + + - throw TypeError when thenable resolves with itself + - Make .race() and Promise.race() forever pending on empty collections + +## 0.10.6-0 (2013-11-25) + +Bugfixes: + + - Promise.resolve and PromiseResolver.resolve follow thenables too. + +## 0.10.5-0 (2013-11-24) + +Bugfixes: + + - Fix infinite loop when thenable resolves with itself + +## 0.10.4-1 (2013-11-24) + +Bugfixes: + + - Fix a file missing from build. (Critical fix) + +## 0.10.4-0 (2013-11-24) + +Features: + + - Remove dependency of es5-shim and es5-sham when using ES3. + +## 0.10.3-0 (2013-11-24) + +Features: + + - Improve performance of `Promise.method` + +## 0.10.2-1 (2013-11-24) + +Features: + + - Rename PromiseResolver#asCallback to PromiseResolver#callback + +## 0.10.2-0 (2013-11-24) + +Features: + + - Remove memoization of thenables + +## 0.10.1-0 (2013-11-21) + +Features: + + - Add methods `Promise.resolve()`, `Promise.reject()`, `Promise.defer()` and `.resolve()`. + +## 0.10.0-1 (2013-11-17) + +## 0.10.0-0 (2013-11-17) + +Features: + + - Implement `Promise.method()` + - Implement `.return()` + - Implement `.throw()` + +Bugfixes: + + - Fix promises being able to use themselves as resolution or follower value + +## 0.9.11-1 (2013-11-14) + +Features: + + - Implicit `Promise.all()` when yielding an array from generators + +## 0.9.11-0 (2013-11-13) + +Bugfixes: + + - Fix `.spread` not unwrapping thenables + +## 0.9.10-2 (2013-11-13) + +Features: + + - Improve performance of promisified functions on V8 + +Bugfixes: + + - Report unhandled rejections even when long stack traces are disabled + - Fix `.error()` showing up in stack traces + +## 0.9.10-1 (2013-11-05) + +Bugfixes: + + - Catch filter method calls showing in stack traces + +## 0.9.10-0 (2013-11-05) + +Bugfixes: + + - Support primitives in catch filters + +## 0.9.9-0 (2013-11-05) + +Features: + + - Add `Promise.race()` and `.race()` + +## 0.9.8-0 (2013-11-01) + +Bugfixes: + + - Fix bug with `Promise.try` not unwrapping returned promises and thenables + +## 0.9.7-0 (2013-10-29) + +Bugfixes: + + - Fix bug with build files containing duplicated code for promise.js + +## 0.9.6-0 (2013-10-28) + +Features: + + - Improve output of reporting unhandled non-errors + - Implement RejectionError wrapping and `.error()` method + +## 0.9.5-0 (2013-10-27) + +Features: + + - Allow fresh copies of the library to be made + +## 0.9.4-1 (2013-10-27) + +## 0.9.4-0 (2013-10-27) + +Bugfixes: + + - Rollback non-working multiple fresh copies feature + +## 0.9.3-0 (2013-10-27) + +Features: + + - Allow fresh copies of the library to be made + - Add more components to customized builds + +## 0.9.2-1 (2013-10-25) + +## 0.9.2-0 (2013-10-25) + +Features: + + - Allow custom builds + +## 0.9.1-1 (2013-10-22) + +Bugfixes: + + - Fix unhandled rethrown exceptions not reported + +## 0.9.1-0 (2013-10-22) + +Features: + + - Improve performance of `Promise.try` + - Extend `Promise.try` to accept arguments and ctx to make it more usable in promisification of synchronous functions. + +## 0.9.0-0 (2013-10-18) + +Features: + + - Implement `.bind` and `Promise.bind` + +Bugfixes: + + - Fix `.some()` when argument is a pending promise that later resolves to an array + +## 0.8.5-1 (2013-10-17) + +Features: + + - Enable process wide long stack traces through BLUEBIRD_DEBUG environment variable + +## 0.8.5-0 (2013-10-16) + +Features: + + - Improve performance of all collection methods + +Bugfixes: + + - Fix .finally passing the value to handlers + - Remove kew from benchmarks due to bugs in the library breaking the benchmark + - Fix some bluebird library calls potentially appearing in stack traces + +## 0.8.4-1 (2013-10-15) + +Bugfixes: + + - Fix .pending() call showing in long stack traces + +## 0.8.4-0 (2013-10-15) + +Bugfixes: + + - Fix PromiseArray and its sub-classes swallowing possibly unhandled rejections + +## 0.8.3-3 (2013-10-14) + +Bugfixes: + + - Fix AMD-declaration using named module. + +## 0.8.3-2 (2013-10-14) + +Features: + + - The mortals that can handle it may now release Zalgo by `require("bluebird/zalgo");` + +## 0.8.3-1 (2013-10-14) + +Bugfixes: + + - Fix memory leak when using the same promise to attach handlers over and over again + +## 0.8.3-0 (2013-10-13) + +Features: + + - Add `Promise.props()` and `Promise.prototype.props()`. They work like `.all()` for object properties. + +Bugfixes: + + - Fix bug with .some returning garbage when sparse arrays have rejections + +## 0.8.2-2 (2013-10-13) + +Features: + + - Improve performance of `.reduce()` when `initialValue` can be synchronously cast to a value + +## 0.8.2-1 (2013-10-12) + +Bugfixes: + + - Fix .npmignore having irrelevant files + +## 0.8.2-0 (2013-10-12) + +Features: + + - Improve performance of `.some()` + +## 0.8.1-0 (2013-10-11) + +Bugfixes: + + - Remove uses of dynamic evaluation (`new Function`, `eval` etc) when strictly not necessary. Use feature detection to use static evaluation to avoid errors when dynamic evaluation is prohibited. + +## 0.8.0-3 (2013-10-10) + +Features: + + - Add `.asCallback` property to `PromiseResolver`s + +## 0.8.0-2 (2013-10-10) + +## 0.8.0-1 (2013-10-09) + +Features: + + - Improve overall performance. Be able to sustain infinite recursion when using promises. + +## 0.8.0-0 (2013-10-09) + +Bugfixes: + + - Fix stackoverflow error when function calls itself "synchronously" from a promise handler + +## 0.7.12-2 (2013-10-09) + +Bugfixes: + + - Fix safari 6 not using `MutationObserver` as a scheduler + - Fix process exceptions interfering with internal queue flushing + +## 0.7.12-1 (2013-10-09) + +Bugfixes: + + - Don't try to detect if generators are available to allow shims to be used + +## 0.7.12-0 (2013-10-08) + +Features: + + - Promisification now consider all functions on the object and its prototype chain + - Individual promisifcation uses current `this` if no explicit receiver is given + - Give better stack traces when promisified callbacks throw or errback primitives such as strings by wrapping them in an `Error` object. + +Bugfixes: + + - Fix runtime APIs throwing synchronous errors + +## 0.7.11-0 (2013-10-08) + +Features: + + - Deprecate `Promise.promisify(Object target)` in favor of `Promise.promisifyAll(Object target)` to avoid confusion with function objects + - Coroutines now throw error when a non-promise is `yielded` + +## 0.7.10-1 (2013-10-05) + +Features: + + - Make tests pass Internet Explorer 8 + +## 0.7.10-0 (2013-10-05) + +Features: + + - Create browser tests + +## 0.7.9-1 (2013-10-03) + +Bugfixes: + + - Fix promise cast bug when thenable fulfills using itself as the fulfillment value + +## 0.7.9-0 (2013-10-03) + +Features: + + - More performance improvements when long stack traces are enabled + +## 0.7.8-1 (2013-10-02) + +Features: + + - Performance improvements when long stack traces are enabled + +## 0.7.8-0 (2013-10-02) + +Bugfixes: + + - Fix promisified methods not turning synchronous exceptions into rejections + +## 0.7.7-1 (2013-10-02) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.7-0 (2013-10-01) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.6-0 (2013-09-29) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.5-0 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.4-1 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.4-0 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.3-1 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.3-0 (2013-09-27) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.2-0 (2013-09-27) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-5 (2013-09-26) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-4 (2013-09-25) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-3 (2013-09-25) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-2 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-1 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-0 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.0-1 (2013-09-23) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.0-0 (2013-09-23) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-2 (2013-09-20) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-1 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-0 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.4-1 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.4-0 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-4 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-3 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-2 (2013-09-16) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-1 (2013-09-16) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-0 (2013-09-15) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.2-1 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.2-0 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.1-0 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.0-0 (2013-09-13) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-6 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-5 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-4 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-3 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-2 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-1 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.8-1 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.8-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.7-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.6-1 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.6-0 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.5-1 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.5-0 (2013-09-09) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.4-1 (2013-09-08) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.4-0 (2013-09-08) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.3-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.2-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.1-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.0-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.4.0-0 (2013-09-06) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.3.0-1 (2013-09-06) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.3.0 (2013-09-06) diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js new file mode 100644 index 0000000..69a6ffd --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.js @@ -0,0 +1,5105 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2014 Petka Antonov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions:

+ * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +/** + * bluebird build version 2.9.26 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers +*/ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + } +}; + +Async.prototype._getDomain = function() {}; + +if (!true) { +if (util.isNode) { + var EventsModule = _dereq_("events"); + + var domainGetter = function() { + var domain = process.domain; + if (domain === null) return undefined; + return domain; + }; + + if (EventsModule.usingDomains) { + Async.prototype._getDomain = domainGetter; + } else { + var descriptor = + Object.getOwnPropertyDescriptor(EventsModule, "usingDomains"); + + if (descriptor) { + if (!descriptor.configurable) { + process.on("domainsActivated", function() { + Async.prototype._getDomain = domainGetter; + }); + } else { + var usingDomains = false; + Object.defineProperty(EventsModule, "usingDomains", { + configurable: false, + enumerable: true, + get: function() { + return usingDomains; + }, + set: function(value) { + if (usingDomains || !value) return; + usingDomains = true; + Async.prototype._getDomain = domainGetter; + util.toFastProperties(process); + process.emit("domainsActivated"); + } + }); + } + } + } +} +} + +function AsyncInvokeLater(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + var domain = this._getDomain(); + if (domain !== undefined) { + var fn = domain.bind(promise._settlePromises); + this._normalQueue.push(fn, promise, undefined); + } else { + this._normalQueue._pushOne(promise); + } + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 0); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + setTimeout(function() { + promise._settlePromises(); + }, 0); + } + }; +} + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = new Async(); +module.exports.firstLineError = firstLineError; + +},{"./queue.js":28,"./schedule.js":31,"./util.js":38,"events":39}],3:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + this._setBoundTo(thisArg); + if (this._isPending()) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, ret._progress, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, ret._progress, ret, context); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 131072; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~131072); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.bind = function (thisArg, value) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + + if (maybePromise instanceof Promise) { + maybePromise._then(function(thisArg) { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + }, ret._reject, ret._progress, ret, null); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + } + return ret; +}; +}; + +},{}],4:[function(_dereq_,module,exports){ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = _dereq_("./promise.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; + +},{"./promise.js":23}],5:[function(_dereq_,module,exports){ +"use strict"; +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} + +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!true) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; + } + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; + } + } + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + if (!true) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } + } + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; + +function namedGetter(obj) { + return obj[this]; +} +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; + +},{"./util.js":38}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var errors = _dereq_("./errors.js"); +var async = _dereq_("./async.js"); +var CancellationError = errors.CancellationError; + +Promise.prototype._cancel = function (reason) { + if (!this.isCancellable()) return this; + var parent; + var promiseToReject = this; + while ((parent = promiseToReject._cancellationParent) !== undefined && + parent.isCancellable()) { + promiseToReject = parent; + } + this._unsetCancellable(); + promiseToReject._target()._rejectCallback(reason, false, true); +}; + +Promise.prototype.cancel = function (reason) { + if (!this.isCancellable()) return this; + if (reason === undefined) reason = new CancellationError(); + async.invokeLater(this._cancel, this, reason); + return this; +}; + +Promise.prototype.cancellable = function () { + if (this._cancellable()) return this; + async.enableTrampoline(); + this._setCancellable(); + this._cancellationParent = undefined; + return this; +}; + +Promise.prototype.uncancellable = function () { + var ret = this.then(); + ret._unsetCancellable(); + return ret; +}; + +Promise.prototype.fork = function (didFulfill, didReject, didProgress) { + var ret = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + + ret._setCancellable(); + ret._cancellationParent = undefined; + return ret; +}; +}; + +},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var warn; + +function CapturedTrace(parent) { + this._parent = parent; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.parent = function() { + return this._parent; +}; + +CapturedTrace.prototype.hasParent = function() { + return this._parent !== undefined; +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = CapturedTrace.parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = stackFramePattern.test(line) || + " (No stack trace)" === line; + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +CapturedTrace.parseStackAndMessage = function(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +}; + +CapturedTrace.formatAndLogError = function(error, title) { + if (typeof console !== "undefined") { + var message; + if (typeof error === "object" || typeof error === "function") { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof warn === "function") { + warn(message); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +}; + +CapturedTrace.unhandledRejection = function (reason) { + CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: "); +}; + +CapturedTrace.isSupported = function () { + return typeof captureStackTrace === "function"; +}; + +CapturedTrace.fireRejectionEvent = +function(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); + } + } + + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + } +}; + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj.toString(); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} +CapturedTrace.setBounds = function(firstLineError, lastLineError) { + if (!CapturedTrace.isSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow) { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); + } + }; + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; + } + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); + } + return true; + }; + } +})(); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + warn = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + warn = function(message) { + process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + warn = function(message) { + console.warn("%c" + message, "color: red"); + }; + } +} + +return CapturedTrace; +}; + +},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util.js"); +var errors = _dereq_("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = _dereq_("./es5.js").keys; +var TypeError = errors.TypeError; + +function CatchFilter(instances, callback, promise) { + this._instances = instances; + this._callback = callback; + this._promise = promise; +} + +function safePredicate(predicate, e) { + var safeObject = {}; + var retfilter = tryCatch(predicate).call(safeObject, e); + + if (retfilter === errorObj) return retfilter; + + var safeKeys = keys(safeObject); + if (safeKeys.length) { + errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); + return errorObj; + } + return retfilter; +} + +CatchFilter.prototype.doFilter = function (e) { + var cb = this._callback; + var promise = this._promise; + var boundTo = promise._boundTo; + for (var i = 0, len = this._instances.length; i < len; ++i) { + var item = this._instances[i]; + var itemIsErrorType = item === Error || + (item != null && item.prototype instanceof Error); + + if (itemIsErrorType && e instanceof item) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } else if (typeof item === "function" && !itemIsErrorType) { + var shouldHandle = safePredicate(item, e); + if (shouldHandle === errorObj) { + e = errorObj.e; + break; + } else if (shouldHandle) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } + } + } + NEXT_FILTER.e = e; + return NEXT_FILTER; +}; + +return CatchFilter; +}; + +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace, isDebugging) { +var contextStack = []; +function Context() { + this._trace = new CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.pop(); + } +}; + +function createContext() { + if (isDebugging()) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} + +Promise.prototype._peekContext = peekContext; +Promise.prototype._pushContext = Context.prototype._pushContext; +Promise.prototype._popContext = Context.prototype._popContext; + +return createContext; +}; + +},{}],10:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var async = _dereq_("./async.js"); +var Warning = _dereq_("./errors.js").Warning; +var util = _dereq_("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +if (debugging) { + async.disableTrampolineIfNecessary(); +} + +Promise.prototype._ensurePossibleRejectionHandled = function () { + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + CapturedTrace.fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._getCarriedStackTrace() || this._settledValue; + this._setUnhandledRejectionIsNotified(); + CapturedTrace.fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 524288; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~524288); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 524288) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 2097152; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~2097152); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 2097152) > 0; +}; + +Promise.prototype._setCarriedStackTrace = function (capturedTrace) { + this._bitField = this._bitField | 1048576; + this._fulfillmentHandler0 = capturedTrace; +}; + +Promise.prototype._isCarryingStackTrace = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._getCarriedStackTrace = function () { + return this._isCarryingStackTrace() + ? this._fulfillmentHandler0 + : undefined; +}; + +Promise.prototype._captureStackTrace = function () { + if (debugging) { + this._trace = new CapturedTrace(this._peekContext()); + } + return this; +}; + +Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { + if (debugging && canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = CapturedTrace.parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +}; + +Promise.prototype._warn = function(message) { + var warning = new Warning(message); + var ctx = this._peekContext(); + if (ctx) { + ctx.attachExtraTrace(warning); + } else { + var parsed = CapturedTrace.parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + CapturedTrace.formatAndLogError(warning, ""); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + unhandledRejectionHandled = typeof fn === "function" ? fn : undefined; +}; + +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && + debugging === false + ) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); + } + debugging = CapturedTrace.isSupported(); + if (debugging) { + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; + +},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util.js"); +var isPrimitive = util.isPrimitive; +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; + +module.exports = function(Promise) { +var returner = function () { + return this; +}; +var thrower = function () { + throw this; +}; +var returnUndefined = function() {}; +var throwUndefined = function() { + throw undefined; +}; + +var wrapper = function (value, action) { + if (action === 1) { + return function () { + throw value; + }; + } else if (action === 2) { + return function () { + return value; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value === undefined) return this.then(returnUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; + +},{"./util.js":38}],12:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, null, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, null, INTERNAL); +}; +}; + +},{}],13:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util.js"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} + +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; + + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + +} +inherits(OperationalError, Error); + +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; + +},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} + +},{}],15:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseMap = Promise.map; + +Promise.prototype.filter = function (fn, options) { + return PromiseMap(this, fn, options, INTERNAL); +}; + +Promise.filter = function (promises, fn, options) { + return PromiseMap(promises, fn, options, INTERNAL); +}; +}; + +},{}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = _dereq_("./util.js"); +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, reasonOrValue, + promise.isFulfilled()); + } + } + + if (promise.isRejected()) { + NEXT_FILTER.e = reasonOrValue; + return NEXT_FILTER; + } else { + return reasonOrValue; + } +} + +function tapHandler(value) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo, value) + : handler(value); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, value, true); + } + } + return value; +} + +Promise.prototype._passThroughHandler = function (handler, isFinally) { + if (typeof handler !== "function") return this.then(); + + var promiseAndHandler = { + promise: this, + handler: handler + }; + + return this._then( + isFinally ? finallyHandler : tapHandler, + isFinally ? finallyHandler : undefined, undefined, + promiseAndHandler, undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThroughHandler(handler, true); +}; + +Promise.prototype.tap = function (handler) { + return this._passThroughHandler(handler, false); +}; +}; + +},{"./util.js":38}],17:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = _dereq_("./errors.js"); +var TypeError = errors.TypeError; +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; +} + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._next(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + if (result === errorObj) { + return this._promise._rejectCallback(result.e, false, true); + } + + var value = result.value; + if (result.done === true) { + this._promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._throw( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise._then( + this._next, + this._throw, + undefined, + this, + null + ); + } +}; + +PromiseSpawn.prototype._throw = function (reason) { + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._next = function (value) { + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + spawn._generator = generator; + spawn._next(undefined); + return spawn.promise(); + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; + +},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!true) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var caller = function(count) { + var values = []; + for (var i = 1; i <= count; ++i) values.push("holder.p" + i); + return new Function("holder", " \n\ + 'use strict'; \n\ + var callback = holder.fn; \n\ + return callback(values); \n\ + ".replace(/values/g, values.join(", "))); + }; + var thenCallbacks = []; + var callers = [undefined]; + for (var i = 1; i <= 5; ++i) { + thenCallbacks.push(thenCallback(i)); + callers.push(caller(i)); + } + + var Holder = function(total, fn) { + this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; + this.fn = fn; + this.total = total; + this.now = 0; + }; + + Holder.prototype.callers = callers; + Holder.prototype.checkFulfillment = function(promise) { + var now = this.now; + now++; + var total = this.total; + if (now >= total) { + var handler = this.callers[total]; + promise._pushContext(); + var ret = tryCatch(handler)(this); + promise._popContext(); + if (ret === errorObj) { + promise._rejectCallback(ret.e, false, true); + } else { + promise._resolveCallback(ret); + } + } else { + this.now = now; + } + }; + + var reject = function (reason) { + this._reject(reason); + }; +} +} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!true) { + if (last < 6 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var holder = new Holder(last, fn); + var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + } else if (maybePromise._isFulfilled()) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else { + ret._reject(maybePromise._reason()); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + return ret; + } + } + } + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; + +},{"./util.js":38}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var PENDING = {}; +var EMPTY_ARRAY = []; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._callback = fn; + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + async.invoke(init, this, undefined); +} +util.inherits(MappingPromiseArray, PromiseArray); +function init() {this._init$(undefined, -2);} + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + if (values[index] === PENDING) { + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return; + } + if (preservedValues !== null) preservedValues[index] = value; + + var callback = this._callback; + var receiver = this._promise._boundTo; + this._promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + this._promise._popContext(); + if (ret === errorObj) return this._reject(ret.e); + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + if (limit >= 1) this._inFlight++; + values[index] = PENDING; + return maybePromise._proxyPromiseArray(this, index); + } else if (maybePromise._isFulfilled()) { + ret = maybePromise._value(); + } else { + return this._reject(maybePromise._reason()); + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + + } +}; + +MappingPromiseArray.prototype._drainQueue = function () { + var queue = this._queue; + var limit = this._limit; + var values = this._values; + while (queue.length > 0 && this._inFlight < limit) { + if (this._isResolved()) return; + var index = queue.pop(); + this._promiseFulfilled(values[index], index); + } +}; + +MappingPromiseArray.prototype._filter = function (booleans, values) { + var len = values.length; + var ret = new Array(len); + var j = 0; + for (var i = 0; i < len; ++i) { + if (booleans[i]) ret[j++] = values[i]; + } + ret.length = j; + this._resolve(ret); +}; + +MappingPromiseArray.prototype.preservedValues = function () { + return this._preservedValues; +}; + +function map(promises, fn, options, _filter) { + var limit = typeof options === "object" && options !== null + ? options.concurrency + : 0; + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter); +} + +Promise.prototype.map = function (fn, options) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + + return map(this, fn, options, null).promise(); +}; + +Promise.map = function (promises, fn, options, _filter) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + return map(promises, fn, options, _filter).promise(); +}; + + +}; + +},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn, args, ctx) { + if (typeof fn !== "function") { + return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = util.isArray(args) + ? tryCatch(fn).apply(ctx, args) + : tryCatch(fn).call(ctx, args); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false, true); + } else { + this._resolveCallback(value, true); + } +}; +}; + +},{"./util.js":38}],21:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundTo; + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var target = promise._target(); + var newReason = target._getCarriedStackTrace(); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundTo, reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = +Promise.prototype.nodeify = function (nodeback, options) { + if (typeof nodeback == "function") { + var adapter = successAdapter; + if (options !== undefined && Object(options).spread) { + adapter = spreadAdapter; + } + this._then( + adapter, + errorAdapter, + undefined, + this, + nodeback + ); + } + return this; +}; +}; + +},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +Promise.prototype.progressed = function (handler) { + return this._then(undefined, undefined, handler, undefined, undefined); +}; + +Promise.prototype._progress = function (progressValue) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._target()._progressUnchecked(progressValue); + +}; + +Promise.prototype._progressHandlerAt = function (index) { + return index === 0 + ? this._progressHandler0 + : this[(index << 2) + index - 5 + 2]; +}; + +Promise.prototype._doProgressWith = function (progression) { + var progressValue = progression.value; + var handler = progression.handler; + var promise = progression.promise; + var receiver = progression.receiver; + + var ret = tryCatch(handler).call(receiver, progressValue); + if (ret === errorObj) { + if (ret.e != null && + ret.e.name !== "StopProgressPropagation") { + var trace = util.canAttachTrace(ret.e) + ? ret.e : new Error(util.toString(ret.e)); + promise._attachExtraTrace(trace); + promise._progress(ret.e); + } + } else if (ret instanceof Promise) { + ret._then(promise._progress, null, null, promise, undefined); + } else { + promise._progress(ret); + } +}; + + +Promise.prototype._progressUnchecked = function (progressValue) { + var len = this._length(); + var progress = this._progress; + for (var i = 0; i < len; i++) { + var handler = this._progressHandlerAt(i); + var promise = this._promiseAt(i); + if (!(promise instanceof Promise)) { + var receiver = this._receiverAt(i); + if (typeof handler === "function") { + handler.call(receiver, progressValue, promise); + } else if (receiver instanceof PromiseArray && + !receiver._isResolved()) { + receiver._promiseProgressed(progressValue, promise); + } + continue; + } + + if (typeof handler === "function") { + async.invoke(this._doProgressWith, this, { + handler: handler, + promise: promise, + receiver: this._receiverAt(i), + value: progressValue + }); + } else { + async.invoke(progress, promise, progressValue); + } + } +}; +}; + +},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); +}; +var reflect = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var errors = _dereq_("./errors.js"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {e: null}; +var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = _dereq_("./captured_trace.js")(); +var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + _dereq_("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = _dereq_("./promise_resolver.js"); +var nodebackForPromise = PromiseResolver._nodebackForPromise; +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function Promise(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); + } + if (this.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._progressHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._settledValue = undefined; + if (resolver !== INTERNAL) this._resolveFromResolver(resolver); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (typeof item === "function") { + catchInstances[j++] = item; + } else { + return Promise.reject( + new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); + } + } + catchInstances.length = j; + fn = arguments[i]; + var catchFilter = new CatchFilter(catchInstances, fn, this); + return this._then(undefined, catchFilter.doFilter, undefined, + catchFilter, undefined); + } + return this._then(undefined, fn, undefined, undefined, undefined); +}; + +Promise.prototype.reflect = function () { + return this._then(reflect, reflect, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject, didProgress) { + if (isDebugging() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, didProgress, + undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject, didProgress) { + var promise = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (didFulfill, didReject) { + return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); +}; + +Promise.prototype.isCancellable = function () { + return !this.isResolved() && + this._cancellable(); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = function(fn) { + var ret = new Promise(INTERNAL); + var result = tryCatch(fn)(nodebackForPromise(ret)); + if (result === errorObj) { + ret._rejectCallback(result.e, true, true); + } + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.defer = Promise.pending = function () { + var promise = new Promise(INTERNAL); + return new PromiseResolver(promise); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + var val = ret; + ret = new Promise(INTERNAL); + ret._fulfillUnchecked(val); + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + didProgress, + receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var ret = haveInternalData ? internalData : new Promise(INTERNAL); + + if (!haveInternalData) { + ret._propagateFrom(this, 4 | 1); + ret._captureStackTrace(); + } + + var target = this._target(); + if (target !== this) { + if (receiver === undefined) receiver = this._boundTo; + if (!haveInternalData) ret._setIsMigrated(); + } + + var callbackIndex = + target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); + + if (target._isResolved() && !target._isSettlePromisesQueued()) { + async.invoke( + target._settlePromiseAtPostResolution, target, callbackIndex); + } + + return ret; +}; + +Promise.prototype._settlePromiseAtPostResolution = function (index) { + if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); + this._settlePromiseAt(index); +}; + +Promise.prototype._length = function () { + return this._bitField & 131071; +}; + +Promise.prototype._isFollowingOrFulfilledOrRejected = function () { + return (this._bitField & 939524096) > 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 536870912) === 536870912; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -131072) | + (len & 131071); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 536870912; +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 33554432; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 33554432) > 0; +}; + +Promise.prototype._cancellable = function () { + return (this._bitField & 67108864) > 0; +}; + +Promise.prototype._setCancellable = function () { + this._bitField = this._bitField | 67108864; +}; + +Promise.prototype._unsetCancellable = function () { + this._bitField = this._bitField & (~67108864); +}; + +Promise.prototype._setIsMigrated = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._unsetIsMigrated = function () { + this._bitField = this._bitField & (~4194304); +}; + +Promise.prototype._isMigrated = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 + ? this._receiver0 + : this[ + index * 5 - 5 + 4]; + if (ret === undefined && this._isBound()) { + return this._boundTo; + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return index === 0 + ? this._promise0 + : this[index * 5 - 5 + 3]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return index === 0 + ? this._fulfillmentHandler0 + : this[index * 5 - 5 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return index === 0 + ? this._rejectionHandler0 + : this[index * 5 - 5 + 1]; +}; + +Promise.prototype._migrateCallbacks = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var progress = follower._progressHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (promise instanceof Promise) promise._setIsMigrated(); + this._addCallbacks(fulfill, reject, progress, promise, receiver); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + progress, + promise, + receiver +) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + if (receiver !== undefined) this._receiver0 = receiver; + if (typeof fulfill === "function" && !this._isCarryingStackTrace()) + this._fulfillmentHandler0 = fulfill; + if (typeof reject === "function") this._rejectionHandler0 = reject; + if (typeof progress === "function") this._progressHandler0 = progress; + } else { + var base = index * 5 - 5; + this[base + 3] = promise; + this[base + 4] = receiver; + if (typeof fulfill === "function") + this[base + 0] = fulfill; + if (typeof reject === "function") + this[base + 1] = reject; + if (typeof progress === "function") + this[base + 2] = progress; + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + if (index === 0) { + this._promise0 = promiseSlotValue; + this._receiver0 = receiver; + } else { + var base = index * 5 - 5; + this[base + 3] = promiseSlotValue; + this[base + 4] = receiver; + } + this._setLength(index + 1); +}; + +Promise.prototype._proxyPromiseArray = function (promiseArray, index) { + this._setProxyHandlers(promiseArray, index); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (this._isFollowingOrFulfilledOrRejected()) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false, true); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + var propagationFlags = 1 | (shouldBind ? 4 : 0); + this._propagateFrom(maybePromise, propagationFlags); + var promise = maybePromise._target(); + if (promise._isPending()) { + var len = this._length(); + for (var i = 0; i < len; ++i) { + promise._migrateCallbacks(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (promise._isFulfilled()) { + this._fulfillUnchecked(promise._value()); + } else { + this._rejectUnchecked(promise._reason(), + promise._getCarriedStackTrace()); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { + if (!shouldNotMarkOriginatingFromRejection) { + util.markAsOriginatingFromRejection(reason); + } + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, hasStack ? undefined : trace); +}; + +Promise.prototype._resolveFromResolver = function (resolver) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = tryCatch(resolver)(function(value) { + if (promise === null) return; + promise._resolveCallback(value); + promise = null; + }, function (reason) { + if (promise === null) return; + promise._rejectCallback(reason, synchronous); + promise = null; + }); + synchronous = false; + this._popContext(); + + if (r !== undefined && r === errorObj && promise !== null) { + promise._rejectCallback(r.e, true, true); + promise = null; + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + if (promise._isRejected()) return; + promise._pushContext(); + var x; + if (receiver === APPLY && !this._isRejected()) { + x = tryCatch(handler).apply(this._boundTo, value); + } else { + x = tryCatch(handler).call(receiver, value); + } + promise._popContext(); + + if (x === errorObj || x === promise || x === NEXT_FILTER) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false, true); + } else { + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._cleanValues = function () { + if (this._cancellable()) { + this._cancellationParent = undefined; + } +}; + +Promise.prototype._propagateFrom = function (parent, flags) { + if ((flags & 1) > 0 && parent._cancellable()) { + this._setCancellable(); + this._cancellationParent = parent; + } + if ((flags & 4) > 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +}; + +Promise.prototype._fulfill = function (value) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._fulfillUnchecked(value); +}; + +Promise.prototype._reject = function (reason, carriedStackTrace) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._rejectUnchecked(reason, carriedStackTrace); +}; + +Promise.prototype._settlePromiseAt = function (index) { + var promise = this._promiseAt(index); + var isPromise = promise instanceof Promise; + + if (isPromise && promise._isMigrated()) { + promise._unsetIsMigrated(); + return async.invoke(this._settlePromiseAt, this, index); + } + var handler = this._isFulfilled() + ? this._fulfillmentHandlerAt(index) + : this._rejectionHandlerAt(index); + + var carriedStackTrace = + this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; + var value = this._settledValue; + var receiver = this._receiverAt(index); + + + this._clearCallbackDataAtIndex(index); + + if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof PromiseArray) { + if (!receiver._isResolved()) { + if (this._isFulfilled()) { + receiver._promiseFulfilled(value, promise); + } + else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (this._isFulfilled()) { + promise._fulfill(value); + } else { + promise._reject(value, carriedStackTrace); + } + } + + if (index >= 4 && (index & 31) === 4) + async.invokeLater(this._setLength, this, 0); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + if (index === 0) { + if (!this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = undefined; + } + this._rejectionHandler0 = + this._progressHandler0 = + this._receiver0 = + this._promise0 = undefined; + } else { + var base = index * 5 - 5; + this[base + 3] = + this[base + 4] = + this[base + 0] = + this[base + 1] = + this[base + 2] = undefined; + } +}; + +Promise.prototype._isSettlePromisesQueued = function () { + return (this._bitField & + -1073741824) === -1073741824; +}; + +Promise.prototype._setSettlePromisesQueued = function () { + this._bitField = this._bitField | -1073741824; +}; + +Promise.prototype._unsetSettlePromisesQueued = function () { + this._bitField = this._bitField & (~-1073741824); +}; + +Promise.prototype._queueSettlePromises = function() { + async.settlePromises(this); + this._setSettlePromisesQueued(); +}; + +Promise.prototype._fulfillUnchecked = function (value) { + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err, undefined); + } + this._setFulfilled(); + this._settledValue = value; + this._cleanValues(); + + if (this._length() > 0) { + this._queueSettlePromises(); + } +}; + +Promise.prototype._rejectUncheckedCheckError = function (reason) { + var trace = util.ensureErrorObject(reason); + this._rejectUnchecked(reason, trace === reason ? undefined : trace); +}; + +Promise.prototype._rejectUnchecked = function (reason, trace) { + if (reason === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err); + } + this._setRejected(); + this._settledValue = reason; + this._cleanValues(); + + if (this._isFinal()) { + async.throwLater(function(e) { + if ("stack" in e) { + async.invokeFirst( + CapturedTrace.unhandledRejection, undefined, e); + } + throw e; + }, trace === undefined ? reason : trace); + return; + } + + if (trace !== undefined && trace !== reason) { + this._setCarriedStackTrace(trace); + } + + if (this._length() > 0) { + this._queueSettlePromises(); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._settlePromises = function () { + this._unsetSettlePromisesQueued(); + var len = this._length(); + for (var i = 0; i < len; i++) { + this._settlePromiseAt(i); + } +}; + +Promise._makeSelfResolutionError = makeSelfResolutionError; +_dereq_("./progress.js")(Promise, PromiseArray); +_dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +_dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +_dereq_("./direct_resolve.js")(Promise); +_dereq_("./synchronous_inspection.js")(Promise); +_dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./cancel.js')(Promise); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +_dereq_('./nodeify.js')(Promise); +_dereq_('./call_get.js')(Promise); +_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./settle.js')(Promise, PromiseArray); +_dereq_('./some.js')(Promise, PromiseArray, apiRejection); +_dereq_('./promisify.js')(Promise, INTERNAL); +_dereq_('./any.js')(Promise); +_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./timers.js')(Promise, INTERNAL); +_dereq_('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._progressHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + p._settledValue = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + CapturedTrace.setBounds(async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = _dereq_("./util.js"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + var parent; + if (values instanceof Promise) { + parent = values; + promise._propagateFrom(parent, 1 | 4); + } + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + this._values = values; + if (values._isFulfilled()) { + values = values._value(); + if (!isArray(values)) { + var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + this.__hardReject__(err); + return; + } + } else if (values._isPending()) { + values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + return; + } else { + this._reject(values._reason()); + return; + } + } else if (!isArray(values)) { + this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var promise = this._promise; + for (var i = 0; i < len; ++i) { + var isResolved = this._isResolved(); + var maybePromise = tryConvertToPromise(values[i], promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (isResolved) { + maybePromise._unsetRejectionIsUnhandled(); + } else if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, i); + } else if (maybePromise._isFulfilled()) { + this._promiseFulfilled(maybePromise._value(), i); + } else { + this._promiseRejected(maybePromise._reason(), i); + } + } else if (!isResolved) { + this._promiseFulfilled(maybePromise, i); + } + } +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype.__hardReject__ = +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false, true); +}; + +PromiseArray.prototype._promiseProgressed = function (progressValue, index) { + this._promise._progress({ + index: index, + value: progressValue + }); +}; + + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +PromiseArray.prototype._promiseRejected = function (reason, index) { + this._totalResolved++; + this._reject(reason); +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util.js":38}],25:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = _dereq_("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = _dereq_("./es5.js"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise) { + return function(err, value) { + if (promise === null) return; + + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (arguments.length > 2) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + promise._fulfill(args); + } else { + promise._fulfill(value); + } + + promise = null; + }; +} + + +var PromiseResolver; +if (!haveGetters) { + PromiseResolver = function (promise) { + this.promise = promise; + this.asCallback = nodebackForPromise(promise); + this.callback = this.asCallback; + }; +} +else { + PromiseResolver = function (promise) { + this.promise = promise; + }; +} +if (haveGetters) { + var prop = { + get: function() { + return nodebackForPromise(this.promise); + } + }; + es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); + es5.defineProperty(PromiseResolver.prototype, "callback", prop); +} + +PromiseResolver._nodebackForPromise = nodebackForPromise; + +PromiseResolver.prototype.toString = function () { + return "[object PromiseResolver]"; +}; + +PromiseResolver.prototype.resolve = +PromiseResolver.prototype.fulfill = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._resolveCallback(value); +}; + +PromiseResolver.prototype.reject = function (reason) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._rejectCallback(reason); +}; + +PromiseResolver.prototype.progress = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._progress(value); +}; + +PromiseResolver.prototype.cancel = function (err) { + this.promise.cancel(err); +}; + +PromiseResolver.prototype.timeout = function () { + this.reject(new TimeoutError("timeout")); +}; + +PromiseResolver.prototype.isResolved = function () { + return this.promise.isResolved(); +}; + +PromiseResolver.prototype.toJSON = function () { + return this.promise.toJSON(); +}; + +module.exports = PromiseResolver; + +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = _dereq_("./util.js"); +var nodebackForPromise = _dereq_("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = _dereq_("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyPropsPattern = + /^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/; +var defaultFilter = function(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} + +function isPromisified(fn) { + try { + return fn.__isPromisified__ === true; + } + catch (e) { + return false; + } +} + +function hasPromisified(obj, key, suffix) { + var val = util.getDataPropertyOrDefault(obj, key + suffix, + defaultPromisified); + return val ? isPromisified(val) : false; +} +function checkValid(ret, suffix, suffixRegexp) { + for (var i = 0; i < ret.length; i += 2) { + var key = ret[i]; + if (suffixRegexp.test(key)) { + var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); + for (var j = 0; j < ret.length; j += 2) { + if (ret[j] === keyWithoutAsyncSuffix) { + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a" + .replace("%s", suffix)); + } + } + } + } +} + +function promisifiableMethods(obj, suffix, suffixRegexp, filter) { + var keys = util.inheritedDataKeys(obj); + var ret = []; + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var value = obj[key]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} + +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!true) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { + var ret = [likelyArgumentCount]; + var min = Math.max(0, likelyArgumentCount - 1 - 3); + for(var i = likelyArgumentCount - 1; i >= min; --i) { + ret.push(i); + } + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { + ret.push(i); + } + return ret; +}; + +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; + +var parameterCount = function(fn) { + if (typeof fn.length === "number") { + return Math.max(Math.min(fn.length, 1023 + 1), 0); + } + return 0; +}; + +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn) { + var newParameterCount = Math.max(0, parameterCount(fn) - 1); + var argumentOrder = switchCaseArgumentOrder(newParameterCount); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; + + function generateCallForArgumentCount(count) { + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; + } + return ret.replace("{{args}}", args).replace(", ", comma); + } + + function generateArgumentSwitchCase() { + var ret = ""; + for (var i = 0; i < argumentOrder.length; ++i) { + ret += "case " + argumentOrder[i] +":" + + generateCallForArgumentCount(argumentOrder[i]); + } + + ret += " \n\ + default: \n\ + var args = new Array(len + 1); \n\ + var i = 0; \n\ + for (var i = 0; i < len; ++i) { \n\ + args[i] = arguments[i]; \n\ + } \n\ + args[i] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); + return ret; + } + + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "INTERNAL","'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + return promise; \n\ + }; \n\ + ret.__isPromisified__ = true; \n\ + return ret; \n\ + " + .replace("Parameters", parameterDeclaration(newParameterCount)) + .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode))( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + INTERNAL + ); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } + function promisified() { + var _receiver = receiver; + if (receiver === THIS) _receiver = this; + var promise = new Promise(INTERNAL); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; + var fn = nodebackForPromise(promise); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + return promise; + } + promisified.__isPromisified__ = true; + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier) { + var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); + var methods = + promisifiableMethods(obj, suffix, suffixRegexp, filter); + + for (var i = 0, len = methods.length; i < len; i+= 2) { + var key = methods[i]; + var fn = methods[i+1]; + var promisifiedKey = key + suffix; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver) { + return makeNodePromisified(callback, receiver, undefined, callback); +} + +Promise.promisify = function (fn, receiver) { + if (typeof fn !== "function") { + throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + if (isPromisified(fn)) { + return fn; + } + var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + util.copyDescriptors(fn, ret, propsFilter); + return ret; +}; + +Promise.promisifyAll = function (target, options) { + if (typeof target !== "function" && typeof target !== "object") { + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a"); + } + options = Object(options); + var suffix = options.suffix; + if (typeof suffix !== "string") suffix = defaultSuffix; + var filter = options.filter; + if (typeof filter !== "function") filter = defaultFilter; + var promisifier = options.promisifier; + if (typeof promisifier !== "function") promisifier = makeNodePromisified; + + if (!util.isIdentifier(suffix)) { + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); + } + + var keys = util.inheritedDataKeys(target); + for (var i = 0; i < keys.length; ++i) { + var value = target[keys[i]]; + if (keys[i] !== "constructor" && + util.isClass(value)) { + promisifyAll(value.prototype, suffix, filter, promisifier); + promisifyAll(value, suffix, filter, promisifier); + } + } + + return promisifyAll(target, suffix, filter, promisifier); +}; +}; + + +},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var isObject = util.isObject; +var es5 = _dereq_("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; +}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val = {}; + var keyOffset = this.length(); + for (var i = 0, len = this.length(); i < len; ++i) { + val[this._values[i + keyOffset]] = this._values[i]; + } + this._resolve(val); + } +}; + +PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { + this._promise._progress({ + key: this._values[index + this.length()], + value: value + }); +}; + +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; + +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); + + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } + + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 4); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; + +},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; + +},{}],29:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = _dereq_("./util.js").isArray; + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else if (!isArray(promises)) { + return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 4 | 1); + } + var fulfill = ret._fulfill; + var reject = ret._reject; + for (var i = 0, len = promises.length; i < len; ++i) { + var val = promises[i]; + + if (val === undefined && !(i in promises)) { + continue; + } + + Promise.cast(val)._then(fulfill, reject, undefined, ret, null); + } + return ret; +} + +Promise.race = function (promises) { + return race(promises, undefined); +}; + +Promise.prototype.race = function () { + return race(this, undefined); +}; + +}; + +},{"./util.js":38}],30:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +function ReductionPromiseArray(promises, fn, accum, _each) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._preservedValues = _each === INTERNAL ? [] : null; + this._zerothIsAccum = (accum === undefined); + this._gotAccum = false; + this._reducingIndex = (this._zerothIsAccum ? 1 : 0); + this._valuesPhase = undefined; + var maybePromise = tryConvertToPromise(accum, this._promise); + var rejected = false; + var isPromise = maybePromise instanceof Promise; + if (isPromise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, -1); + } else if (maybePromise._isFulfilled()) { + accum = maybePromise._value(); + this._gotAccum = true; + } else { + this._reject(maybePromise._reason()); + rejected = true; + } + } + if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; + this._callback = fn; + this._accum = accum; + if (!rejected) async.invoke(init, this, undefined); +} +function init() { + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._init = function () {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); + } +}; + +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + values[index] = value; + var length = this.length(); + var preservedValues = this._preservedValues; + var isEach = preservedValues !== null; + var gotAccum = this._gotAccum; + var valuesPhase = this._valuesPhase; + var valuesPhaseIndex; + if (!valuesPhase) { + valuesPhase = this._valuesPhase = new Array(length); + for (valuesPhaseIndex=0; valuesPhaseIndex 10) || (version[0] > 0) + ? function(fn) { global.setImmediate(fn); } : process.nextTick; + + if (!schedule) { + if (typeof setImmediate !== "undefined") { + schedule = setImmediate; + } else if (typeof setTimeout !== "undefined") { + schedule = setTimeout; + } else { + schedule = noAsyncScheduler; + } + } +} else if (typeof MutationObserver !== "undefined") { + schedule = function(fn) { + var div = document.createElement("div"); + var observer = new MutationObserver(fn); + observer.observe(div, {attributes: true}); + return function() { div.classList.toggle("foo"); }; + }; + schedule.isStatic = true; +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; + +},{"./util.js":38}],32:[function(_dereq_,module,exports){ +"use strict"; +module.exports = + function(Promise, PromiseArray) { +var PromiseInspection = Promise.PromiseInspection; +var util = _dereq_("./util.js"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 268435456; + ret._settledValue = value; + this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 134217728; + ret._settledValue = reason; + this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return new SettledPromiseArray(this).promise(); +}; +}; + +},{"./util.js":38}],33:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = _dereq_("./util.js"); +var RangeError = _dereq_("./errors.js").RangeError; +var AggregateError = _dereq_("./errors.js").AggregateError; +var isArray = util.isArray; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + this._addFulfilled(value); + if (this._fulfilled() === this.howMany()) { + this._values.length = this.howMany(); + if (this.howMany() === 1 && this._unwrap) { + this._resolve(this._values[0]); + } else { + this._resolve(this._values); + } + } + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + e.push(this._values[i]); + } + this._reject(e); + } +}; + +SomePromiseArray.prototype._fulfilled = function () { + return this._totalResolved; +}; + +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); +}; + +SomePromiseArray.prototype._addRejected = function (reason) { + this._values.push(reason); +}; + +SomePromiseArray.prototype._addFulfilled = function (value) { + this._values[this._totalResolved++] = value; +}; + +SomePromiseArray.prototype._canPossiblyFulfill = function () { + return this.length() - this._rejected(); +}; + +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); +}; + +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; + +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} + +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; + +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; + +Promise._SomePromiseArray = SomePromiseArray; +}; + +},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValue = promise._settledValue; + } + else { + this._bitField = 0; + this._settledValue = undefined; + } +} + +PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.isFulfilled = +Promise.prototype._isFulfilled = function () { + return (this._bitField & 268435456) > 0; +}; + +PromiseInspection.prototype.isRejected = +Promise.prototype._isRejected = function () { + return (this._bitField & 134217728) > 0; +}; + +PromiseInspection.prototype.isPending = +Promise.prototype._isPending = function () { + return (this._bitField & 402653184) === 0; +}; + +PromiseInspection.prototype.isResolved = +Promise.prototype._isResolved = function () { + return (this._bitField & 402653184) > 0; +}; + +Promise.prototype.isPending = function() { + return this._target()._isPending(); +}; + +Promise.prototype.isRejected = function() { + return this._target()._isRejected(); +}; + +Promise.prototype.isFulfilled = function() { + return this._target()._isFulfilled(); +}; + +Promise.prototype.isResolved = function() { + return this._target()._isResolved(); +}; + +Promise.prototype._value = function() { + return this._settledValue; +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue; +}; + +Promise.prototype.value = function() { + var target = this._target(); + if (!target.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return target._settledValue; +}; + +Promise.prototype.reason = function() { + var target = this._target(); + if (!target.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + target._unsetRejectionIsUnhandled(); + return target._settledValue; +}; + + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],35:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) { + return obj; + } + else if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfillUnchecked, + ret._rejectUncheckedCheckError, + ret._progressUnchecked, + ret, + null + ); + return ret; + } + var then = util.tryCatch(getThen)(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + return doThenable(obj, then, context); + } + } + return obj; +} + +function getThen(obj) { + return obj.then; +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, + resolveFromThenable, + rejectFromThenable, + progressFromThenable); + synchronous = false; + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolveFromThenable(value) { + if (!promise) return; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + promise._resolveCallback(value); + } + promise = null; + } + + function rejectFromThenable(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + + function progressFromThenable(value) { + if (!promise) return; + if (typeof promise._progress === "function") { + promise._progress(value); + } + } + return ret; +} + +return tryConvertToPromise; +}; + +},{"./util.js":38}],36:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + if (typeof message !== "string") { + message = "operation timed out"; + } + var err = new TimeoutError(message); + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._cancel(err); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (value, ms) { + if (ms === undefined) { + ms = value; + value = undefined; + var ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, ms); + return ret; + } + ms = +ms; + return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); +}; + +Promise.prototype.delay = function (ms) { + return delay(this, ms); +}; + +function successClear(value) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + return value; +} + +function failureClear(reason) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret = this.then().cancellable(); + ret._cancellationParent = this; + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; + +},{"./util.js":38}],37:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = _dereq_("./errors.js").TypeError; + var inherits = _dereq_("./util.js").inherits; + var PromiseInspection = Promise.PromiseInspection; + + function inspectionMapper(inspections) { + var len = inspections.length; + for (var i = 0; i < len; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + return Promise.reject(inspection.error()); + } + inspections[i] = inspection._settledValue; + } + return inspections; + } + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + if (maybePromise !== thenable && + typeof thenable._isDisposable === "function" && + typeof thenable._getDisposer === "function" && + thenable._isDisposable()) { + maybePromise._setDisposable(thenable._getDisposer()); + } + return maybePromise; + } + function dispose(resources, inspection) { + var i = 0; + var len = resources.length; + var ret = Promise.defer(); + function iterator() { + if (i >= len) return ret.resolve(); + var maybePromise = castPreservingDisposable(resources[i++]); + if (maybePromise instanceof Promise && + maybePromise._isDisposable()) { + try { + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); + } catch (e) { + return thrower(e); + } + if (maybePromise instanceof Promise) { + return maybePromise._then(iterator, thrower, + null, null, null); + } + } + iterator(); + } + iterator(); + return ret.promise; + } + + function disposerSuccess(value) { + var inspection = new PromiseInspection(); + inspection._settledValue = value; + inspection._bitField = 268435456; + return dispose(this, inspection).thenReturn(value); + } + + function disposerFail(reason) { + var inspection = new PromiseInspection(); + inspection._settledValue = reason; + inspection._bitField = 134217728; + return dispose(this, inspection).thenThrow(reason); + } + + function Disposer(data, promise, context) { + this._data = data; + this._promise = promise; + this._context = context; + } + + Disposer.prototype.data = function () { + return this._data; + }; + + Disposer.prototype.promise = function () { + return this._promise; + }; + + Disposer.prototype.resource = function () { + if (this.promise().isFulfilled()) { + return this.promise().value(); + } + return null; + }; + + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== null + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; + + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); + }; + + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); + + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); + }; + + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); + } + return value; + } + + Promise.using = function () { + var len = arguments.length; + if (len < 2) return apiRejection( + "you must pass at least 2 arguments to Promise.using"); + var fn = arguments[len - 1]; + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } + } + resources[i] = resource; + } + + var promise = Promise.settle(resources) + .then(inspectionMapper) + .then(function(vals) { + promise._pushContext(); + var ret; + try { + ret = fn.apply(undefined, vals); + } finally { + promise._popContext(); + } + return ret; + }) + ._then( + disposerSuccess, disposerFail, undefined, resources, undefined); + resources.promise = promise; + return promise; + }; + + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 262144; + this._disposer = disposer; + }; + + Promise.prototype._isDisposable = function () { + return (this._bitField & 262144) > 0; + }; + + Promise.prototype._getDisposer = function () { + return this._disposer; + }; + + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~262144); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); + }; + +}; + +},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var canEvaluate = typeof navigator == "undefined"; +var haveGetters = (function(){ + try { + var o = {}; + es5.defineProperty(o, "f", { + get: function () { + return 3; + } + }); + return o.f === 3; + } + catch (e) { + return false; + } + +})(); + +var errorObj = {e: {}}; +var tryCatchTarget; +function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } + } + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return !isPrimitive(value); +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); +} + +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; +} + +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} + +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; +} + + +var wrapsPrimitiveReceiver = (function() { + return this !== "string"; +}).call("string"); + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + if (es5.isES5) { + var oProto = Object.prototype; + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && obj !== oProto) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function f() {} + f.prototype = obj; + var l = 8; + while (l--) new f(); + return obj; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + haveGetters: haveGetters, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" +}; +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5.js":14}],39:[function(_dereq_,module,exports){ +// 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. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } + throw TypeError('Uncaught, unspecified "error" event.'); + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + handler.apply(this, args); + } + } else if (isObject(handler)) { + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + var m; + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + var ret; + if (!emitter._events || !emitter._events[type]) + ret = 0; + else if (isFunction(emitter._events[type])) + ret = 1; + else + ret = emitter._events[type].length; + return ret; +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}]},{},[4])(4) +}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } \ No newline at end of file diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js new file mode 100644 index 0000000..679f778 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/browser/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2014 Petka Antonov + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions:

+ * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +/** + * bluebird build version 2.9.26 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers +*/ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,r;return function n(t,e,r){function i(s,a){if(!e[s]){if(!t[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=e[s]={exports:{}};t[s][0].call(l.exports,function(e){var r=t[s][1][e];return i(r?r:e)},l,l.exports,n,t,e,r)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0},r.prototype.throwLater=function(t,e){1===arguments.length&&(e=t,t=function(){throw e});var r=this._getDomain();if(void 0!==r&&(t=r.bind(t)),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(n){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")}},r.prototype._getDomain=function(){};l.hasDevTools?(r.prototype.invokeLater=function(t,e,r){this._trampolineEnabled?n.call(this,t,e,r):setTimeout(function(){t.call(e,r)},100)},r.prototype.invoke=function(t,e,r){this._trampolineEnabled?i.call(this,t,e,r):setTimeout(function(){t.call(e,r)},0)},r.prototype.settlePromises=function(t){this._trampolineEnabled?o.call(this,t):setTimeout(function(){t._settlePromises()},0)}):(r.prototype.invokeLater=n,r.prototype.invoke=i,r.prototype.settlePromises=o),r.prototype.invokeFirst=function(t,e,r){var n=this._getDomain();void 0!==n&&(t=n.bind(t)),this._normalQueue.unshift(t,e,r),this._queueTick()},r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var r=t.shift(),n=t.shift();e.call(r,n)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=new r,e.exports.firstLineError=s},{"./queue.js":28,"./schedule.js":31,"./util.js":38,events:39}],3:[function(t,e){"use strict";e.exports=function(t,e,r){var n=function(t,e){this._reject(e)},i=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(n,n,null,this,t)},o=function(t,e){this._setBoundTo(t),this._isPending()&&this._resolveCallback(e.target)},s=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(n){var a=r(n),u=new t(e);u._propagateFrom(this,1);var c=this._target();if(a instanceof t){var l={promiseRejectionQueued:!1,promise:u,target:c,bindingPromise:a};c._then(e,i,u._progress,u,l),a._then(o,s,u._progress,u,l)}else u._setBoundTo(n),u._resolveCallback(c);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=131072|this._bitField,this._boundTo=t):this._bitField=-131073&this._bitField},t.prototype._isBound=function(){return 131072===(131072&this._bitField)},t.bind=function(n,i){var o=r(n),s=new t(e);return o instanceof t?o._then(function(t){s._setBoundTo(t),s._resolveCallback(i)},s._reject,s._progress,s,null):(s._setBoundTo(n),s._resolveCallback(i)),s}}},{}],4:[function(t,e){"use strict";function r(){try{Promise===i&&(Promise=n)}catch(t){}return i}var n;"undefined"!=typeof Promise&&(n=Promise);var i=t("./promise.js")();i.noConflict=r,e.exports=i},{"./promise.js":23}],5:[function(t,e){"use strict";var r=Object.create;if(r){var n=r(null),i=r(null);n[" size"]=i[" size"]=0}e.exports=function(e){function r(t,r){var n;if(null!=t&&(n=t[r]),"function"!=typeof n){var i="Object "+a.classString(t)+" has no method '"+a.toString(r)+"'";throw new e.TypeError(i)}return n}function n(t){var e=this.pop(),n=r(t,e);return n.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}{var s,a=t("./util.js"),u=a.canEvaluate;a.isIdentifier}e.prototype.call=function(t){for(var e=arguments.length,r=new Array(e-1),i=1;e>i;++i)r[i-1]=arguments[i];return r.push(t),this._then(n,void 0,void 0,r,void 0)},e.prototype.get=function(t){var e,r="number"==typeof t;if(r)e=o;else if(u){var n=s(t);e=null!==n?n:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util.js":38}],6:[function(t,e){"use strict";e.exports=function(e){var r=t("./errors.js"),n=t("./async.js"),i=r.CancellationError;e.prototype._cancel=function(t){if(!this.isCancellable())return this;for(var e,r=this;void 0!==(e=r._cancellationParent)&&e.isCancellable();)r=e;this._unsetCancellable(),r._target()._rejectCallback(t,!1,!0)},e.prototype.cancel=function(t){return this.isCancellable()?(void 0===t&&(t=new i),n.invokeLater(this._cancel,this,t),this):this},e.prototype.cancellable=function(){return this._cancellable()?this:(n.enableTrampoline(),this._setCancellable(),this._cancellationParent=void 0,this)},e.prototype.uncancellable=function(){var t=this.then();return t._unsetCancellable(),t},e.prototype.fork=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);return n._setCancellable(),n._cancellationParent=void 0,n}}},{"./async.js":2,"./errors.js":13}],7:[function(t,e){"use strict";e.exports=function(){function e(t){this._parent=t;var r=this._length=1+(void 0===t?0:t._length);j(this,e),r>32&&this.uncycle()}function r(t,e){for(var r=0;r=0;--a)if(n[a]===o){s=a;break}for(var a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}function o(t){for(var e=[],r=0;r0&&(e=e.slice(r)),e}function a(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t.toString();var r=/\[object [a-zA-Z0-9$_]+\]/;if(r.test(e))try{var n=JSON.stringify(t);e=n}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+u(e)+">, no stack trace)"}function u(t){var e=41;return t.lengtht)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;t=this._length=n;for(var n=t-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(var n=0;t>n;++n){var s=e[n].stack,a=r[s];if(void 0!==a&&a!==n){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var u=n>0?e[n-1]:this;t-1>a?(u._parent=e[a+1],u._parent.uncycle(),u._length=u._parent._length+1):(u._parent=void 0,u._length=1);for(var c=u._length+1,l=n-2;l>=0;--l)e[l]._length=c,c++;return}}}},e.prototype.parent=function(){return this._parent},e.prototype.hasParent=function(){return void 0!==this._parent},e.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var s=e.parseStackAndMessage(t),a=s.message,u=[s.stack],c=this;void 0!==c;)u.push(o(c.stack.split("\n"))),c=c._parent;i(u),n(u),p.notEnumerableProp(t,"stack",r(a,u)),p.notEnumerableProp(t,"__stackCleaned__",!0)}},e.parseStackAndMessage=function(t){var e=t.stack,r=t.toString();return e="string"==typeof e&&e.length>0?s(t):[" (No stack trace)"],{message:r,stack:o(e)}},e.formatAndLogError=function(t,e){if("undefined"!=typeof console){var r;if("object"==typeof t||"function"==typeof t){var n=t.stack;r=e+d(n,t)}else r=e+String(t);"function"==typeof l?l(r):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}},e.unhandledRejection=function(t){e.formatAndLogError(t,"^--- With additional stack trace: ")},e.isSupported=function(){return"function"==typeof j},e.fireRejectionEvent=function(t,r,n,i){var o=!1;try{"function"==typeof r&&(o=!0,"rejectionHandled"===t?r(i):r(n,i))}catch(s){h.throwLater(s)}var a=!1;try{a=b(t,n,i)}catch(s){a=!0,h.throwLater(s)}var u=!1;if(m)try{u=m(t.toLowerCase(),{reason:n,promise:i})}catch(s){u=!0,h.throwLater(s)}a||o||u||"unhandledRejection"!==t||e.formatAndLogError(n,"Unhandled rejection ")};var y=function(){return!1},g=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;e.setBounds=function(t,r){if(e.isSupported()){for(var n,i,o=t.stack.split("\n"),s=r.stack.split("\n"),a=-1,u=-1,l=0;la||0>u||!n||!i||n!==i||a>=u||(y=function(t){if(f.test(t))return!0;var e=c(t);return e&&e.fileName===n&&a<=e.line&&e.line<=u?!0:!1})}};var m,j=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():a(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit=Error.stackTraceLimit+6,_=t,d=e;var r=Error.captureStackTrace;return y=function(t){return f.test(t)},function(t,e){Error.stackTraceLimit=Error.stackTraceLimit+6,r(t,e),Error.stackTraceLimit=Error.stackTraceLimit-6}}var n=new Error;if("string"==typeof n.stack&&n.stack.split("\n")[0].indexOf("stackDetection@")>=0)return _=/@/,d=e,v=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in n||!i?(d=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?a(e):e.toString()},null):(_=t,d=e,function(t){Error.stackTraceLimit=Error.stackTraceLimit+6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit=Error.stackTraceLimit-6})}([]),b=function(){if(p.isNode)return function(t,e,r){return"rejectionHandled"===t?process.emit(t,r):process.emit(t,e,r)};var t=!1,e=!0;try{var r=new self.CustomEvent("test");t=r instanceof CustomEvent}catch(n){}if(!t)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(n){e=!1}e&&(m=function(e,r){var n;return t?n=new self.CustomEvent(e,{detail:r,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(n=document.createEvent("CustomEvent"),n.initCustomEvent(e,!1,!0,r)),n?!self.dispatchEvent(n):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,r){var n=o[t],i=self[n];return i?("rejectionHandled"===t?i.call(self,r):i.call(self,e,r),!0):!1}}();return"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(l=function(t){console.warn(t)},p.isNode&&process.stderr.isTTY?l=function(t){process.stderr.write(""+t+"\n")}:p.isNode||"string"!=typeof(new Error).stack||(l=function(t){console.warn("%c"+t,"color: red")})),e}},{"./async.js":2,"./util.js":38}],8:[function(t,e){"use strict";e.exports=function(e){function r(t,e,r){this._instances=t,this._callback=e,this._promise=r}function n(t,e){var r={},n=s(t).call(r,e);if(n===a)return n;var i=u(r);return i.length?(a.e=new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"),a):n}var i=t("./util.js"),o=t("./errors.js"),s=i.tryCatch,a=i.errorObj,u=t("./es5.js").keys,c=o.TypeError;return r.prototype.doFilter=function(t){for(var r=this._callback,i=this._promise,o=i._boundTo,u=0,c=this._instances.length;c>u;++u){var l=this._instances[u],h=l===Error||null!=l&&l.prototype instanceof Error;if(h&&t instanceof l){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}if("function"==typeof l&&!h){var f=n(l,t);if(f===a){t=a.e;break}if(f){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}}}return e.e=t,e},r}},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(t,e){"use strict";e.exports=function(t,e,r){function n(){this._trace=new e(o())}function i(){return r()?new n:void 0}function o(){var t=s.length-1;return t>=0?s[t]:void 0}var s=[];return n.prototype._pushContext=function(){r()&&void 0!==this._trace&&s.push(this._trace)},n.prototype._popContext=function(){r()&&void 0!==this._trace&&s.pop()},t.prototype._peekContext=o,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,i}},{}],10:[function(t,e){"use strict";e.exports=function(e,r){var n,i,o=t("./async.js"),s=t("./errors.js").Warning,a=t("./util.js"),u=a.canAttachTrace,c=!1||a.isNode&&(!!process.env.BLUEBIRD_DEBUG||"development"===process.env.NODE_ENV);return c&&o.disableTrampolineIfNecessary(),e.prototype._ensurePossibleRejectionHandled=function(){this._setRejectionIsUnhandled(),o.invokeLater(this._notifyUnhandledRejection,this,void 0)},e.prototype._notifyUnhandledRejectionIsHandled=function(){r.fireRejectionEvent("rejectionHandled",n,void 0,this)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._getCarriedStackTrace()||this._settledValue;this._setUnhandledRejectionIsNotified(),r.fireRejectionEvent("unhandledRejection",i,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=524288|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-524289&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(524288&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=2097152|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-2097153&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(2097152&this._bitField)>0},e.prototype._setCarriedStackTrace=function(t){this._bitField=1048576|this._bitField,this._fulfillmentHandler0=t},e.prototype._isCarryingStackTrace=function(){return(1048576&this._bitField)>0},e.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0},e.prototype._captureStackTrace=function(){return c&&(this._trace=new r(this._peekContext())),this},e.prototype._attachExtraTrace=function(t,e){if(c&&u(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var i=r.parseStackAndMessage(t);a.notEnumerableProp(t,"stack",i.message+"\n"+i.stack.join("\n")),a.notEnumerableProp(t,"__stackCleaned__",!0)}}},e.prototype._warn=function(t){var e=new s(t),n=this._peekContext();if(n)n.attachExtraTrace(e);else{var i=r.parseStackAndMessage(e);e.stack=i.message+"\n"+i.stack.join("\n")}r.formatAndLogError(e,"")},e.onPossiblyUnhandledRejection=function(t){i="function"==typeof t?t:void 0},e.onUnhandledRejectionHandled=function(t){n="function"==typeof t?t:void 0},e.longStackTraces=function(){if(o.haveItemsQueued()&&c===!1)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/DT1qyG\n");c=r.isSupported(),c&&o.disableTrampolineIfNecessary()},e.hasLongStackTraces=function(){return c&&r.isSupported()},r.isSupported()||(e.longStackTraces=function(){},c=!1),function(){return c}}},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(t,e){"use strict";var r=t("./util.js"),n=r.isPrimitive,i=r.wrapsPrimitiveReceiver;e.exports=function(t){var e=function(){return this},r=function(){throw this},o=function(){},s=function(){throw void 0},a=function(t,e){return 1===e?function(){throw t}:2===e?function(){return t}:void 0};t.prototype["return"]=t.prototype.thenReturn=function(t){return void 0===t?this.then(o):i&&n(t)?this._then(a(t,2),void 0,void 0,void 0,void 0):this._then(e,void 0,void 0,t,void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return void 0===t?this.then(s):i&&n(t)?this._then(a(t,1),void 0,void 0,void 0,void 0):this._then(r,void 0,void 0,t,void 0)}}},{"./util.js":38}],12:[function(t,e){"use strict";e.exports=function(t,e){var r=t.reduce;t.prototype.each=function(t){return r(this,t,null,e)},t.each=function(t,n){return r(t,n,null,e)}}},{}],13:[function(t,e){"use strict";function r(t,e){function r(n){return this instanceof r?(l(this,"message","string"==typeof n?n:e),l(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new r(n)}return c(r,Error),r}function n(t){return this instanceof n?(l(this,"name","OperationalError"),l(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(l(this,"message",t.message),l(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new n(t)}var i,o,s=t("./es5.js"),a=s.freeze,u=t("./util.js"),c=u.inherits,l=u.notEnumerableProp,h=r("Warning","warning"),p=r("CancellationError","cancellation error"),f=r("TimeoutError","timeout error"),_=r("AggregateError","aggregate error");try{i=TypeError,o=RangeError}catch(d){i=r("TypeError","type error"),o=r("RangeError","range error")}for(var v="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y0&&"function"==typeof arguments[e]){t=arguments[e];var n}for(var i=arguments.length,o=new Array(i),s=0;i>s;++s)o[s]=arguments[s];t&&o.pop();var n=new r(o).promise();return void 0!==t?n.spread(t):n}}},{"./util.js":38}],19:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,e,r,n){this.constructor$(t),this._promise._captureStackTrace(),this._callback=e,this._preservedValues=n===o?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=r>=1?[]:_,c.invoke(a,this,void 0)}function a(){this._init$(void 0,-2)}function u(t,e,r,n){var i="object"==typeof r&&null!==r?r.concurrency:0;return i="number"==typeof i&&isFinite(i)&&i>=1?i:0,new s(t,e,i,n)}var c=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj,f={},_=[];l.inherits(s,r),s.prototype._init=function(){},s.prototype._promiseFulfilled=function(t,r){var n=this._values,o=this.length(),s=this._preservedValues,a=this._limit;if(n[r]===f){if(n[r]=t,a>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return}else{if(a>=1&&this._inFlight>=a)return n[r]=t,void this._queue.push(r);null!==s&&(s[r]=t);var u=this._callback,c=this._promise._boundTo;this._promise._pushContext();var l=h(u).call(c,t,r,o);if(this._promise._popContext(),l===p)return this._reject(l.e);var _=i(l,this._promise);if(_ instanceof e){if(_=_._target(),_._isPending())return a>=1&&this._inFlight++,n[r]=f,_._proxyPromiseArray(this,r);if(!_._isFulfilled())return this._reject(_._reason());l=_._value()}n[r]=l}var d=++this._totalResolved;d>=o&&(null!==s?this._filter(n,s):this._resolve(n))},s.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(n[i++]=e[o]);n.length=i,this._resolve(n)},s.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return"function"!=typeof t?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(this,t,e,null).promise()},e.map=function(t,e,r,i){return"function"!=typeof e?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(t,e,r,i).promise()}}},{"./async.js":2,"./util.js":38}],20:[function(t,e){"use strict";e.exports=function(e,r,n,i){var o=t("./util.js"),s=o.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");return function(){var n=new e(r);n._captureStackTrace(),n._pushContext();var i=s(t).apply(this,arguments);return n._popContext(),n._resolveFromSyncValue(i),n}},e.attempt=e["try"]=function(t,n,a){if("function"!=typeof t)return i("fn must be a function\n\n See http://goo.gl/916lJJ\n");var u=new e(r);u._captureStackTrace(),u._pushContext();var c=o.isArray(n)?s(t).apply(a,n):s(t).call(a,n);return u._popContext(),u._resolveFromSyncValue(c),u},e.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1,!0):this._resolveCallback(t,!0)}}},{"./util.js":38}],21:[function(t,e){"use strict";e.exports=function(e){function r(t,e){var r=this;if(!o.isArray(t))return n.call(r,t,e);var i=a(e).apply(r._boundTo,[null].concat(t));i===u&&s.throwLater(i.e)}function n(t,e){var r=this,n=r._boundTo,i=void 0===t?a(e).call(n,null):a(e).call(n,null,t);i===u&&s.throwLater(i.e)}function i(t,e){var r=this;if(!t){var n=r._target(),i=n._getCarriedStackTrace();i.cause=t,t=i}var o=a(e).call(r._boundTo,t);o===u&&s.throwLater(o.e)}var o=t("./util.js"),s=t("./async.js"),a=o.tryCatch,u=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=n;void 0!==e&&Object(e).spread&&(o=r),this._then(o,i,void 0,this,t)}return this}}},{"./async.js":2,"./util.js":38}],22:[function(t,e){"use strict";e.exports=function(e,r){var n=t("./util.js"),i=t("./async.js"),o=n.tryCatch,s=n.errorObj;e.prototype.progressed=function(t){return this._then(void 0,void 0,t,void 0,void 0)},e.prototype._progress=function(t){this._isFollowingOrFulfilledOrRejected()||this._target()._progressUnchecked(t)},e.prototype._progressHandlerAt=function(t){return 0===t?this._progressHandler0:this[(t<<2)+t-5+2]},e.prototype._doProgressWith=function(t){var r=t.value,i=t.handler,a=t.promise,u=t.receiver,c=o(i).call(u,r);if(c===s){if(null!=c.e&&"StopProgressPropagation"!==c.e.name){var l=n.canAttachTrace(c.e)?c.e:new Error(n.toString(c.e));a._attachExtraTrace(l),a._progress(c.e)}}else c instanceof e?c._then(a._progress,null,null,a,void 0):a._progress(c)},e.prototype._progressUnchecked=function(t){for(var n=this._length(),o=this._progress,s=0;n>s;s++){var a=this._progressHandlerAt(s),u=this._promiseAt(s);if(u instanceof e)"function"==typeof a?i.invoke(this._doProgressWith,this,{handler:a,promise:u,receiver:this._receiverAt(s),value:t}):i.invoke(o,u,t);else{var c=this._receiverAt(s);"function"==typeof a?a.call(c,t,u):c instanceof r&&!c._isResolved()&&c._promiseProgressed(t,u)}}}}},{"./async.js":2,"./util.js":38}],23:[function(t,e){"use strict";e.exports=function(){function e(t){if("function"!=typeof t)throw new c("the promise constructor requires a resolver function\n\n See http://goo.gl/EC22Yn\n");if(this.constructor!==e)throw new c("the promise constructor cannot be invoked directly\n\n See http://goo.gl/KsIlge\n");this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._progressHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._settledValue=void 0,t!==l&&this._resolveFromResolver(t)}function r(t){var r=new e(l);r._fulfillmentHandler0=t,r._rejectionHandler0=t,r._progressHandler0=t,r._promise0=t,r._receiver0=t,r._settledValue=t}var n=function(){return new c("circular promise resolution chain\n\n See http://goo.gl/LhFpo0\n")},i=function(){return new e.PromiseInspection(this._target())},o=function(t){return e.reject(new c(t))},s=t("./util.js"),a=t("./async.js"),u=t("./errors.js"),c=e.TypeError=u.TypeError;e.RangeError=u.RangeError,e.CancellationError=u.CancellationError,e.TimeoutError=u.TimeoutError,e.OperationalError=u.OperationalError,e.RejectionError=u.OperationalError,e.AggregateError=u.AggregateError;var l=function(){},h={},p={e:null},f=t("./thenables.js")(e,l),_=t("./promise_array.js")(e,l,f,o),d=t("./captured_trace.js")(),v=t("./debuggability.js")(e,d),y=t("./context.js")(e,d,v),g=t("./catch_filter.js")(p),m=t("./promise_resolver.js"),j=m._nodebackForPromise,b=s.errorObj,w=s.tryCatch;return e.prototype.toString=function(){return"[object Promise]"},e.prototype.caught=e.prototype["catch"]=function(t){var r=arguments.length;if(r>1){var n,i=new Array(r-1),o=0;for(n=0;r-1>n;++n){var s=arguments[n];if("function"!=typeof s)return e.reject(new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"));i[o++]=s}i.length=o,t=arguments[n];var a=new g(i,t,this);return this._then(void 0,a.doFilter,void 0,a,void 0)}return this._then(void 0,t,void 0,void 0,void 0)},e.prototype.reflect=function(){return this._then(i,i,void 0,this,void 0)},e.prototype.then=function(t,e,r){if(v()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+s.classString(t);arguments.length>1&&(n+=", "+s.classString(e)),this._warn(n)}return this._then(t,e,r,void 0,void 0)},e.prototype.done=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);n._setIsFinal()},e.prototype.spread=function(t,e){return this.all()._then(t,e,void 0,h,void 0)},e.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable() +},e.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},e.prototype.all=function(){return new _(this).promise()},e.prototype.error=function(t){return this.caught(s.originatesFromRejection,t)},e.is=function(t){return t instanceof e},e.fromNode=function(t){var r=new e(l),n=w(t)(j(r));return n===b&&r._rejectCallback(n.e,!0,!0),r},e.all=function(t){return new _(t).promise()},e.defer=e.pending=function(){var t=new e(l);return new m(t)},e.cast=function(t){var r=f(t);if(!(r instanceof e)){var n=r;r=new e(l),r._fulfillUnchecked(n)}return r},e.resolve=e.fulfilled=e.cast,e.reject=e.rejected=function(t){var r=new e(l);return r._captureStackTrace(),r._rejectCallback(t,!0),r},e.setScheduler=function(t){if("function"!=typeof t)throw new c("fn must be a function\n\n See http://goo.gl/916lJJ\n");var e=a._schedule;return a._schedule=t,e},e.prototype._then=function(t,r,n,i,o){var s=void 0!==o,u=s?o:new e(l);s||(u._propagateFrom(this,5),u._captureStackTrace());var c=this._target();c!==this&&(void 0===i&&(i=this._boundTo),s||u._setIsMigrated());var h=c._addCallbacks(t,r,n,u,i);return c._isResolved()&&!c._isSettlePromisesQueued()&&a.invoke(c._settlePromiseAtPostResolution,c,h),u},e.prototype._settlePromiseAtPostResolution=function(t){this._isRejectionUnhandled()&&this._unsetRejectionIsUnhandled(),this._settlePromiseAt(t)},e.prototype._length=function(){return 131071&this._bitField},e.prototype._isFollowingOrFulfilledOrRejected=function(){return(939524096&this._bitField)>0},e.prototype._isFollowing=function(){return 536870912===(536870912&this._bitField)},e.prototype._setLength=function(t){this._bitField=-131072&this._bitField|131071&t},e.prototype._setFulfilled=function(){this._bitField=268435456|this._bitField},e.prototype._setRejected=function(){this._bitField=134217728|this._bitField},e.prototype._setFollowing=function(){this._bitField=536870912|this._bitField},e.prototype._setIsFinal=function(){this._bitField=33554432|this._bitField},e.prototype._isFinal=function(){return(33554432&this._bitField)>0},e.prototype._cancellable=function(){return(67108864&this._bitField)>0},e.prototype._setCancellable=function(){this._bitField=67108864|this._bitField},e.prototype._unsetCancellable=function(){this._bitField=-67108865&this._bitField},e.prototype._setIsMigrated=function(){this._bitField=4194304|this._bitField},e.prototype._unsetIsMigrated=function(){this._bitField=-4194305&this._bitField},e.prototype._isMigrated=function(){return(4194304&this._bitField)>0},e.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[5*t-5+4];return void 0===e&&this._isBound()?this._boundTo:e},e.prototype._promiseAt=function(t){return 0===t?this._promise0:this[5*t-5+3]},e.prototype._fulfillmentHandlerAt=function(t){return 0===t?this._fulfillmentHandler0:this[5*t-5+0]},e.prototype._rejectionHandlerAt=function(t){return 0===t?this._rejectionHandler0:this[5*t-5+1]},e.prototype._migrateCallbacks=function(t,r){var n=t._fulfillmentHandlerAt(r),i=t._rejectionHandlerAt(r),o=t._progressHandlerAt(r),s=t._promiseAt(r),a=t._receiverAt(r);s instanceof e&&s._setIsMigrated(),this._addCallbacks(n,i,o,s,a)},e.prototype._addCallbacks=function(t,e,r,n,i){var o=this._length();if(o>=131066&&(o=0,this._setLength(0)),0===o)this._promise0=n,void 0!==i&&(this._receiver0=i),"function"!=typeof t||this._isCarryingStackTrace()||(this._fulfillmentHandler0=t),"function"==typeof e&&(this._rejectionHandler0=e),"function"==typeof r&&(this._progressHandler0=r);else{var s=5*o-5;this[s+3]=n,this[s+4]=i,"function"==typeof t&&(this[s+0]=t),"function"==typeof e&&(this[s+1]=e),"function"==typeof r&&(this[s+2]=r)}return this._setLength(o+1),o},e.prototype._setProxyHandlers=function(t,e){var r=this._length();if(r>=131066&&(r=0,this._setLength(0)),0===r)this._promise0=e,this._receiver0=t;else{var n=5*r-5;this[n+3]=e,this[n+4]=t}this._setLength(r+1)},e.prototype._proxyPromiseArray=function(t,e){this._setProxyHandlers(t,e)},e.prototype._resolveCallback=function(t,r){if(!this._isFollowingOrFulfilledOrRejected()){if(t===this)return this._rejectCallback(n(),!1,!0);var i=f(t,this);if(!(i instanceof e))return this._fulfill(t);var o=1|(r?4:0);this._propagateFrom(i,o);var s=i._target();if(s._isPending()){for(var a=this._length(),u=0;a>u;++u)s._migrateCallbacks(this,u);this._setFollowing(),this._setLength(0),this._setFollowee(s)}else s._isFulfilled()?this._fulfillUnchecked(s._value()):this._rejectUnchecked(s._reason(),s._getCarriedStackTrace())}},e.prototype._rejectCallback=function(t,e,r){r||s.markAsOriginatingFromRejection(t);var n=s.ensureErrorObject(t),i=n===t;this._attachExtraTrace(n,e?i:!1),this._reject(t,i?void 0:n)},e.prototype._resolveFromResolver=function(t){var e=this;this._captureStackTrace(),this._pushContext();var r=!0,n=w(t)(function(t){null!==e&&(e._resolveCallback(t),e=null)},function(t){null!==e&&(e._rejectCallback(t,r),e=null)});r=!1,this._popContext(),void 0!==n&&n===b&&null!==e&&(e._rejectCallback(n.e,!0,!0),e=null)},e.prototype._settlePromiseFromHandler=function(t,e,r,i){if(!i._isRejected()){i._pushContext();var o;if(o=e!==h||this._isRejected()?w(t).call(e,r):w(t).apply(this._boundTo,r),i._popContext(),o===b||o===i||o===p){var s=o===i?n():o.e;i._rejectCallback(s,!1,!0)}else i._resolveCallback(o)}},e.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},e.prototype._followee=function(){return this._rejectionHandler0},e.prototype._setFollowee=function(t){this._rejectionHandler0=t},e.prototype._cleanValues=function(){this._cancellable()&&(this._cancellationParent=void 0)},e.prototype._propagateFrom=function(t,e){(1&e)>0&&t._cancellable()&&(this._setCancellable(),this._cancellationParent=t),(4&e)>0&&t._isBound()&&this._setBoundTo(t._boundTo)},e.prototype._fulfill=function(t){this._isFollowingOrFulfilledOrRejected()||this._fulfillUnchecked(t)},e.prototype._reject=function(t,e){this._isFollowingOrFulfilledOrRejected()||this._rejectUnchecked(t,e)},e.prototype._settlePromiseAt=function(t){var r=this._promiseAt(t),n=r instanceof e;if(n&&r._isMigrated())return r._unsetIsMigrated(),a.invoke(this._settlePromiseAt,this,t);var i=this._isFulfilled()?this._fulfillmentHandlerAt(t):this._rejectionHandlerAt(t),o=this._isCarryingStackTrace()?this._getCarriedStackTrace():void 0,s=this._settledValue,u=this._receiverAt(t);this._clearCallbackDataAtIndex(t),"function"==typeof i?n?this._settlePromiseFromHandler(i,u,s,r):i.call(u,s,r):u instanceof _?u._isResolved()||(this._isFulfilled()?u._promiseFulfilled(s,r):u._promiseRejected(s,r)):n&&(this._isFulfilled()?r._fulfill(s):r._reject(s,o)),t>=4&&4===(31&t)&&a.invokeLater(this._setLength,this,0)},e.prototype._clearCallbackDataAtIndex=function(t){if(0===t)this._isCarryingStackTrace()||(this._fulfillmentHandler0=void 0),this._rejectionHandler0=this._progressHandler0=this._receiver0=this._promise0=void 0;else{var e=5*t-5;this[e+3]=this[e+4]=this[e+0]=this[e+1]=this[e+2]=void 0}},e.prototype._isSettlePromisesQueued=function(){return-1073741824===(-1073741824&this._bitField)},e.prototype._setSettlePromisesQueued=function(){this._bitField=-1073741824|this._bitField},e.prototype._unsetSettlePromisesQueued=function(){this._bitField=1073741823&this._bitField},e.prototype._queueSettlePromises=function(){a.settlePromises(this),this._setSettlePromisesQueued()},e.prototype._fulfillUnchecked=function(t){if(t===this){var e=n();return this._attachExtraTrace(e),this._rejectUnchecked(e,void 0)}this._setFulfilled(),this._settledValue=t,this._cleanValues(),this._length()>0&&this._queueSettlePromises()},e.prototype._rejectUncheckedCheckError=function(t){var e=s.ensureErrorObject(t);this._rejectUnchecked(t,e===t?void 0:e)},e.prototype._rejectUnchecked=function(t,e){if(t===this){var r=n();return this._attachExtraTrace(r),this._rejectUnchecked(r)}return this._setRejected(),this._settledValue=t,this._cleanValues(),this._isFinal()?void a.throwLater(function(t){throw"stack"in t&&a.invokeFirst(d.unhandledRejection,void 0,t),t},void 0===e?t:e):(void 0!==e&&e!==t&&this._setCarriedStackTrace(e),void(this._length()>0?this._queueSettlePromises():this._ensurePossibleRejectionHandled()))},e.prototype._settlePromises=function(){this._unsetSettlePromisesQueued();for(var t=this._length(),e=0;t>e;e++)this._settlePromiseAt(e)},e._makeSelfResolutionError=n,t("./progress.js")(e,_),t("./method.js")(e,l,f,o),t("./bind.js")(e,l,f),t("./finally.js")(e,p,f),t("./direct_resolve.js")(e),t("./synchronous_inspection.js")(e),t("./join.js")(e,_,f,l),e.Promise=e,t("./map.js")(e,_,o,f,l),t("./cancel.js")(e),t("./using.js")(e,o,f,y),t("./generators.js")(e,o,l,f),t("./nodeify.js")(e),t("./call_get.js")(e),t("./props.js")(e,_,f,o),t("./race.js")(e,l,f,o),t("./reduce.js")(e,_,o,f,l),t("./settle.js")(e,_),t("./some.js")(e,_,o),t("./promisify.js")(e,l),t("./any.js")(e),t("./each.js")(e,l),t("./timers.js")(e,l),t("./filter.js")(e,l),s.toFastProperties(e),s.toFastProperties(e.prototype),r({a:1}),r({b:2}),r({c:3}),r(1),r(function(){}),r(void 0),r(!1),r(new e(l)),d.setBounds(a.firstLineError,s.lastLineError),e}},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){switch(t){case-2:return[];case-3:return{}}}function s(t){var n,i=this._promise=new e(r);t instanceof e&&(n=t,i._propagateFrom(n,5)),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var a=t("./util.js"),u=a.isArray;return s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function c(t,r){var s=n(this._values,this._promise);if(s instanceof e){if(s=s._target(),this._values=s,!s._isFulfilled())return s._isPending()?void s._then(c,this._reject,void 0,this,r):void this._reject(s._reason());if(s=s._value(),!u(s)){var a=new e.TypeError("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");return void this.__hardReject__(a)}}else if(!u(s))return void this._promise._reject(i("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")._reason());if(0===s.length)return void(-5===r?this._resolveEmptyArray():this._resolve(o(r)));var l=this.getActualLength(s.length);this._length=l,this._values=this.shouldCopyValues()?new Array(l):this._values;for(var h=this._promise,p=0;l>p;++p){var f=this._isResolved(),_=n(s[p],h);_ instanceof e?(_=_._target(),f?_._unsetRejectionIsUnhandled():_._isPending()?_._proxyPromiseArray(this,p):_._isFulfilled()?this._promiseFulfilled(_._value(),p):this._promiseRejected(_._reason(),p)):f||this._promiseFulfilled(_,p)}},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype.__hardReject__=s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1,!0)},s.prototype._promiseProgressed=function(t,e){this._promise._progress({index:e,value:t})},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},s.prototype._promiseRejected=function(t){this._totalResolved++,this._reject(t)},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}},{"./util.js":38}],25:[function(t,e){"use strict";function r(t){return t instanceof Error&&p.getPrototypeOf(t)===Error.prototype}function n(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=p.keys(t),i=0;i2){for(var o=arguments.length,s=new Array(o-1),u=1;o>u;++u)s[u-1]=arguments[u];t._fulfill(s)}else t._fulfill(r);t=null}}}var o,s=t("./util.js"),a=s.maybeWrapAsError,u=t("./errors.js"),c=u.TimeoutError,l=u.OperationalError,h=s.haveGetters,p=t("./es5.js"),f=/^(?:name|message|stack|cause)$/;if(o=h?function(t){this.promise=t}:function(t){this.promise=t,this.asCallback=i(t),this.callback=this.asCallback},h){var _={get:function(){return i(this.promise)}};p.defineProperty(o.prototype,"asCallback",_),p.defineProperty(o.prototype,"callback",_)}o._nodebackForPromise=i,o.prototype.toString=function(){return"[object PromiseResolver]"},o.prototype.resolve=o.prototype.fulfill=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._resolveCallback(t)},o.prototype.reject=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._rejectCallback(t)},o.prototype.progress=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._progress(t)},o.prototype.cancel=function(t){this.promise.cancel(t)},o.prototype.timeout=function(){this.reject(new c("timeout"))},o.prototype.isResolved=function(){return this.promise.isResolved()},o.prototype.toJSON=function(){return this.promise.toJSON()},e.exports=o},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(t,e){"use strict";e.exports=function(e,r){function n(t){return!b.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(e){return!1}}function o(t,e,r){var n=f.getDataPropertyOrDefault(t,e+r,j);return n?i(n):!1}function s(t,e,r){for(var n=0;ns;s+=2){var c=o[s],l=o[s+1],h=c+e;t[h]=n===E?E(c,p,c,l,e):n(l,function(){return E(c,p,c,l,e)})}return f.toFastProperties(t),t}function l(t,e){return E(t,e,void 0,t)}var h,p={},f=t("./util.js"),_=t("./promise_resolver.js")._nodebackForPromise,d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,g=t("./errors").TypeError,m="Async",j={__isPromisified__:!0},b=/^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/,w=function(t,e){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&!f.isClass(e)},k=function(t){return t.replace(/([$])/,"\\$")},E=y?h:u;e.promisify=function(t,e){if("function"!=typeof t)throw new g("fn must be a function\n\n See http://goo.gl/916lJJ\n");if(i(t))return t;var r=l(t,arguments.length<2?p:e);return f.copyDescriptors(t,r,n),r},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new g("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/9ITlV0\n");e=Object(e);var r=e.suffix;"string"!=typeof r&&(r=m);var n=e.filter;"function"!=typeof n&&(n=w);var i=e.promisifier;if("function"!=typeof i&&(i=E),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/8FZo5V\n");for(var o=f.inheritedDataKeys(t),s=0;si;++i){var o=e[i];n[i]=t[o],n[i+r]=o}this.constructor$(n)}function s(t){var r,s=n(t);return u(s)?(r=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&r._propagateFrom(s,4),r):i("cannot await properties of a non-object\n\n See http://goo.gl/OsFKC8\n")}var a=t("./util.js"),u=a.isObject,c=t("./es5.js");a.inherits(o,r),o.prototype._init=function(){this._init$(void 0,-3)},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;if(r>=this._length){for(var n={},i=this.length(),o=0,s=this.length();s>o;++o)n[this._values[o+i]]=this._values[o];this._resolve(n)}},o.prototype._promiseProgressed=function(t,e){this._promise._progress({key:this._values[e+this.length()],value:t})},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5.js":14,"./util.js":38}],28:[function(t,e){"use strict";function r(t,e,r,n,i){for(var o=0;i>o;++o)r[o+n]=t[o+e],t[o+e]=void 0}function n(t){this._capacity=t,this._length=0,this._front=0}n.prototype._willBeOverCapacity=function(t){return this._capacityp;++p){var _=t[p];(void 0!==_||p in t)&&e.cast(_)._then(l,h,void 0,c,null)}return c}var s=t("./util.js").isArray,a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util.js":38}],30:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,r,n,s){this.constructor$(t),this._promise._captureStackTrace(),this._preservedValues=s===o?[]:null,this._zerothIsAccum=void 0===n,this._gotAccum=!1,this._reducingIndex=this._zerothIsAccum?1:0,this._valuesPhase=void 0;var u=i(n,this._promise),l=!1,h=u instanceof e;h&&(u=u._target(),u._isPending()?u._proxyPromiseArray(this,-1):u._isFulfilled()?(n=u._value(),this._gotAccum=!0):(this._reject(u._reason()),l=!0)),h||this._zerothIsAccum||(this._gotAccum=!0),this._callback=r,this._accum=n,l||c.invoke(a,this,void 0)}function a(){this._init$(void 0,-5)}function u(t,e,r,i){if("function"!=typeof e)return n("fn must be a function\n\n See http://goo.gl/916lJJ\n");var o=new s(t,e,r,i);return o.promise()}var c=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj;l.inherits(s,r),s.prototype._init=function(){},s.prototype._resolveEmptyArray=function(){(this._gotAccum||this._zerothIsAccum)&&this._resolve(null!==this._preservedValues?[]:this._accum)},s.prototype._promiseFulfilled=function(t,r){var n=this._values;n[r]=t;var o,s=this.length(),a=this._preservedValues,u=null!==a,c=this._gotAccum,l=this._valuesPhase;if(!l)for(l=this._valuesPhase=new Array(s),o=0;s>o;++o)l[o]=0;if(o=l[r],0===r&&this._zerothIsAccum?(this._accum=t,this._gotAccum=c=!0,l[r]=0===o?1:2):-1===r?(this._accum=t,this._gotAccum=c=!0):0===o?l[r]=1:(l[r]=2,this._accum=t),c){for(var f,_=this._callback,d=this._promise._boundTo,v=this._reducingIndex;s>v;++v)if(o=l[v],2!==o){if(1!==o)return;if(t=n[v],this._promise._pushContext(),u?(a.push(t),f=h(_).call(d,t,v,s)):f=h(_).call(d,this._accum,t,v,s),this._promise._popContext(),f===p)return this._reject(f.e);var y=i(f,this._promise);if(y instanceof e){if(y=y._target(),y._isPending())return l[v]=4,y._proxyPromiseArray(this,v);if(!y._isFulfilled())return this._reject(y._reason());f=y._value()}this._reducingIndex=v+1,this._accum=f}else this._reducingIndex=v+1;this._resolve(u?a:this._accum)}},e.prototype.reduce=function(t,e){return u(this,t,e,null)},e.reduce=function(t,e,r,n){return u(t,e,r,n)}}},{"./async.js":2,"./util.js":38}],31:[function(t,e){"use strict";var r,n=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")};if(t("./util.js").isNode){var i=process.versions.node.split(".").map(Number);r=0===i[0]&&i[1]>10||i[0]>0?function(t){global.setImmediate(t)}:process.nextTick,r||(r="undefined"!=typeof setImmediate?setImmediate:"undefined"!=typeof setTimeout?setTimeout:n)}else"undefined"!=typeof MutationObserver?(r=function(t){var e=document.createElement("div"),r=new MutationObserver(t);return r.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},r.isStatic=!0):r="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:n;e.exports=r},{"./util.js":38}],32:[function(t,e){"use strict";e.exports=function(e,r){function n(t){this.constructor$(t)}var i=e.PromiseInspection,o=t("./util.js");o.inherits(n,r),n.prototype._promiseResolved=function(t,e){this._values[t]=e;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},n.prototype._promiseFulfilled=function(t,e){var r=new i;r._bitField=268435456,r._settledValue=t,this._promiseResolved(e,r)},n.prototype._promiseRejected=function(t,e){var r=new i;r._bitField=134217728,r._settledValue=t,this._promiseResolved(e,r)},e.settle=function(t){return new n(t).promise()},e.prototype.settle=function(){return new n(this).promise()}}},{"./util.js":38}],33:[function(t,e){"use strict";e.exports=function(e,r,n){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return n("expecting a positive integer\n\n See http://goo.gl/1wAmHx\n");var r=new i(t),o=r.promise();return r.setHowMany(e),r.init(),o}var s=t("./util.js"),a=t("./errors.js").RangeError,u=t("./errors.js").AggregateError,c=s.isArray;s.inherits(i,r),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=c(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),this._resolve(1===this.howMany()&&this._unwrap?this._values[0]:this._values))},i.prototype._promiseRejected=function(t){if(this._addRejected(t),this.howMany()>this._canPossiblyFulfill()){for(var e=new u,r=this.length();r0},e.prototype.isRejected=t.prototype._isRejected=function(){return(134217728&this._bitField)>0},e.prototype.isPending=t.prototype._isPending=function(){return 0===(402653184&this._bitField)},e.prototype.isResolved=t.prototype._isResolved=function(){return(402653184&this._bitField)>0},t.prototype.isPending=function(){return this._target()._isPending()},t.prototype.isRejected=function(){return this._target()._isRejected()},t.prototype.isFulfilled=function(){return this._target()._isFulfilled()},t.prototype.isResolved=function(){return this._target()._isResolved()},t.prototype._value=function(){return this._settledValue},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue},t.prototype.value=function(){var t=this._target();if(!t.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n");return t._settledValue},t.prototype.reason=function(){var t=this._target();if(!t.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n");return t._unsetRejectionIsUnhandled(),t._settledValue},t.PromiseInspection=e}},{}],35:[function(t,e){"use strict";e.exports=function(e,r){function n(t,n){if(c(t)){if(t instanceof e)return t;if(o(t)){var l=new e(r);return t._then(l._fulfillUnchecked,l._rejectUncheckedCheckError,l._progressUnchecked,l,null),l}var h=a.tryCatch(i)(t);if(h===u){n&&n._pushContext();var l=e.reject(h.e);return n&&n._popContext(),l}if("function"==typeof h)return s(t,h,n)}return t}function i(t){return t.then}function o(t){return l.call(t,"_promise0")}function s(t,n,i){function o(r){l&&(t===r?l._rejectCallback(e._makeSelfResolutionError(),!1,!0):l._resolveCallback(r),l=null)}function s(t){l&&(l._rejectCallback(t,p,!0),l=null)}function c(t){l&&"function"==typeof l._progress&&l._progress(t)}var l=new e(r),h=l;i&&i._pushContext(),l._captureStackTrace(),i&&i._popContext();var p=!0,f=a.tryCatch(n).call(t,o,s,c);return p=!1,l&&f===u&&(l._rejectCallback(f.e,!0,!0),l=null),h}var a=t("./util.js"),u=a.errorObj,c=a.isObject,l={}.hasOwnProperty;return n}},{"./util.js":38}],36:[function(t,e){"use strict";e.exports=function(e,r){function n(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util.js"),s=e.TimeoutError,a=function(t,e){if(t.isPending()){"string"!=typeof e&&(e="operation timed out");var r=new s(e);o.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._cancel(r)}},u=function(t){return c(+this).thenReturn(t)},c=e.delay=function(t,n){if(void 0===n){n=t,t=void 0;var i=new e(r);return setTimeout(function(){i._fulfill()},n),i}return n=+n,e.resolve(t)._then(u,null,null,n,void 0)};e.prototype.delay=function(t){return c(this,t)},e.prototype.timeout=function(t,e){t=+t;var r=this.then().cancellable();r._cancellationParent=this;var o=setTimeout(function(){a(r,e)},t);return r._then(n,i,void 0,o,void 0)}}},{"./util.js":38}],37:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){for(var r=t.length,n=0;r>n;++n){var i=t[n];if(i.isRejected())return e.reject(i.error());t[n]=i._settledValue}return t}function s(t){setTimeout(function(){throw t},0)}function a(t){var e=n(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function u(t,r){function i(){if(o>=u)return c.resolve();var l=a(t[o++]);if(l instanceof e&&l._isDisposable()){try{l=n(l._getDisposer().tryDispose(r),t.promise)}catch(h){return s(h)}if(l instanceof e)return l._then(i,s,null,null,null)}i()}var o=0,u=t.length,c=e.defer();return i(),c.promise}function c(t){var e=new v;return e._settledValue=t,e._bitField=268435456,u(this,e).thenReturn(t)}function l(t){var e=new v;return e._settledValue=t,e._bitField=134217728,u(this,e).thenThrow(t)}function h(t,e,r){this._data=t,this._promise=e,this._context=r}function p(t,e,r){this.constructor$(t,e,r)}function f(t){return h.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}var _=t("./errors.js").TypeError,d=t("./util.js").inherits,v=e.PromiseInspection;h.prototype.data=function(){return this._data},h.prototype.promise=function(){return this._promise},h.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},h.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=null!==e?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},h.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},d(p,h),p.prototype.doDispose=function(t,e){var r=this.data();return r.call(t,t,e)},e.using=function(){var t=arguments.length;if(2>t)return r("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return r("fn must be a function\n\n See http://goo.gl/916lJJ\n");t--;for(var s=new Array(t),a=0;t>a;++a){var u=arguments[a];if(h.isDisposer(u)){var p=u;u=u.promise(),u._setDisposable(p)}else{var _=n(u);_ instanceof e&&(u=_._then(f,null,null,{resources:s,index:a},void 0))}s[a]=u}var d=e.settle(s).then(o).then(function(t){d._pushContext();var e;try{e=i.apply(void 0,t)}finally{d._popContext()}return e})._then(c,l,void 0,s,void 0);return s.promise=d,d},e.prototype._setDisposable=function(t){this._bitField=262144|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(262144&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-262145&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new _}}},{"./errors.js":13,"./util.js":38}],38:[function(t,e,r){"use strict"; +function n(){try{return T.apply(this,arguments)}catch(t){return F.e=t,F}}function i(t){return T=t,n}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return!o(t)}function a(t){return o(t)?new Error(v(t)):t}function u(t,e){var r,n=t.length,i=new Array(n+1);for(r=0;n>r;++r)i[r]=t[r];return i[r]=e,i}function c(t,e,r){if(!w.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var n=Object.getOwnPropertyDescriptor(t,e);return null!=n?null==n.get&&null==n.set?n.value:r:void 0}function l(t,e,r){if(o(t))return t;var n={value:r,configurable:!0,enumerable:!1,writable:!0};return w.defineProperty(t,e,n),t}function h(t){throw t}function p(t){try{if("function"==typeof t){var e=w.names(t.prototype);return w.isES5?e.length>1:e.length>0&&!(1===e.length&&"constructor"===e[0])}return!1}catch(r){return!1}}function f(t){function e(){}e.prototype=t;for(var r=8;r--;)new e;return t}function _(t){return R.test(t)}function d(t,e,r){for(var n=new Array(t),i=0;t>i;++i)n[i]=e+i+r;return n}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){try{l(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function m(t){return t instanceof Error&&w.propertyIsWritable(t,"stack")}function j(t){return{}.toString.call(t)}function b(t,e,r){for(var n=w.names(t),i=0;it||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,r,i,a,u,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],s(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];r.apply(this,a)}else if(o(r)){for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];for(c=r.slice(),i=c.length,u=0;i>u;u++)c[u].apply(this,a)}return!0},r.prototype.addListener=function(t,e){var i;if(!n(e))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,n(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned){var i;i=s(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,i&&i>0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())}return this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),i||(i=!0,e.apply(this,arguments))}if(!n(e))throw TypeError("listener must be a function");var i=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,i,s,a;if(!n(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],s=r.length,i=-1,r===e||n(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(a=s;a-->0;)if(r[a]===e||r[a].listener&&r[a].listener===e){i=a;break}if(0>i)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],n(r))this.removeListener(t,r);else for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?n(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.listenerCount=function(t,e){var r;return r=t._events&&t._events[e]?n(t._events[e])?1:t._events[e].length:0}},{}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js new file mode 100644 index 0000000..05a6228 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js @@ -0,0 +1,21 @@ +"use strict"; +module.exports = function(Promise) { +var SomePromiseArray = Promise._SomePromiseArray; +function any(promises) { + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(1); + ret.setUnwrap(); + ret.init(); + return promise; +} + +Promise.any = function (promises) { + return any(promises); +}; + +Promise.prototype.any = function () { + return any(this); +}; + +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js new file mode 100644 index 0000000..a98955c --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js @@ -0,0 +1,55 @@ +"use strict"; +module.exports = (function(){ +var AssertionError = (function() { + function AssertionError(a) { + this.constructor$(a); + this.message = a; + this.name = "AssertionError"; + } + AssertionError.prototype = new Error(); + AssertionError.prototype.constructor = AssertionError; + AssertionError.prototype.constructor$ = Error; + return AssertionError; +})(); + +function getParams(args) { + var params = []; + for (var i = 0; i < args.length; ++i) params.push("arg" + i); + return params; +} + +function nativeAssert(callName, args, expect) { + try { + var params = getParams(args); + var constructorArgs = params; + constructorArgs.push("return " + + callName + "("+ params.join(",") + ");"); + var fn = Function.apply(null, constructorArgs); + return fn.apply(null, args); + } catch (e) { + if (!(e instanceof SyntaxError)) { + throw e; + } else { + return expect; + } + } +} + +return function assert(boolExpr, message) { + if (boolExpr === true) return; + + if (typeof boolExpr === "string" && + boolExpr.charAt(0) === "%") { + var nativeCallName = boolExpr; + var $_len = arguments.length;var args = new Array($_len - 2); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];} + if (nativeAssert(nativeCallName, args, message) === message) return; + message = (nativeCallName + " !== " + message); + } + + var ret = new AssertionError(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(ret, assert); + } + throw ret; +}; +})(); diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js new file mode 100644 index 0000000..3b5f828 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js @@ -0,0 +1,204 @@ +"use strict"; +var firstLineError; +try {throw new Error(); } catch (e) {firstLineError = e;} +var schedule = require("./schedule.js"); +var Queue = require("./queue.js"); +var util = require("./util.js"); + +function Async() { + this._isTickUsed = false; + this._lateQueue = new Queue(16); + this._normalQueue = new Queue(16); + this._trampolineEnabled = true; + var self = this; + this.drainQueues = function () { + self._drainQueues(); + }; + this._schedule = + schedule.isStatic ? schedule(this.drainQueues) : schedule; +} + +Async.prototype.disableTrampolineIfNecessary = function() { + if (util.hasDevTools) { + this._trampolineEnabled = false; + } +}; + +Async.prototype.enableTrampoline = function() { + if (!this._trampolineEnabled) { + this._trampolineEnabled = true; + this._schedule = function(fn) { + setTimeout(fn, 0); + }; + } +}; + +Async.prototype.haveItemsQueued = function () { + return this._normalQueue.length() > 0; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + } +}; + +Async.prototype._getDomain = function() {}; + +if (!false) { +if (util.isNode) { + var EventsModule = require("events"); + + var domainGetter = function() { + var domain = process.domain; + if (domain === null) return undefined; + return domain; + }; + + if (EventsModule.usingDomains) { + Async.prototype._getDomain = domainGetter; + } else { + var descriptor = + Object.getOwnPropertyDescriptor(EventsModule, "usingDomains"); + + if (descriptor) { + if (!descriptor.configurable) { + process.on("domainsActivated", function() { + Async.prototype._getDomain = domainGetter; + }); + } else { + var usingDomains = false; + Object.defineProperty(EventsModule, "usingDomains", { + configurable: false, + enumerable: true, + get: function() { + return usingDomains; + }, + set: function(value) { + if (usingDomains || !value) return; + usingDomains = true; + Async.prototype._getDomain = domainGetter; + util.toFastProperties(process); + process.emit("domainsActivated"); + } + }); + } + } + } +} +} + +function AsyncInvokeLater(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + var domain = this._getDomain(); + if (domain !== undefined) { + var fn = domain.bind(promise._settlePromises); + this._normalQueue.push(fn, promise, undefined); + } else { + this._normalQueue._pushOne(promise); + } + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + setTimeout(function() { + fn.call(receiver, arg); + }, 0); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + setTimeout(function() { + promise._settlePromises(); + }, 0); + } + }; +} + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + var domain = this._getDomain(); + if (domain !== undefined) fn = domain.bind(fn); + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = new Async(); +module.exports.firstLineError = firstLineError; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js new file mode 100644 index 0000000..d6f6da2 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bind.js @@ -0,0 +1,73 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + this._setBoundTo(thisArg); + if (this._isPending()) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, ret._progress, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, ret._progress, ret, context); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 131072; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~131072); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.bind = function (thisArg, value) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + + if (maybePromise instanceof Promise) { + maybePromise._then(function(thisArg) { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + }, ret._reject, ret._progress, ret, null); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + } + return ret; +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js new file mode 100644 index 0000000..ed6226e --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js @@ -0,0 +1,11 @@ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = require("./promise.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js new file mode 100644 index 0000000..62c166d --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js @@ -0,0 +1,123 @@ +"use strict"; +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} + +module.exports = function(Promise) { +var util = require("./util.js"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!false) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; + } + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; + } + } + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + if (!false) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } + } + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; + +function namedGetter(obj) { + return obj[this]; +} +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js new file mode 100644 index 0000000..9eb40b6 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js @@ -0,0 +1,48 @@ +"use strict"; +module.exports = function(Promise) { +var errors = require("./errors.js"); +var async = require("./async.js"); +var CancellationError = errors.CancellationError; + +Promise.prototype._cancel = function (reason) { + if (!this.isCancellable()) return this; + var parent; + var promiseToReject = this; + while ((parent = promiseToReject._cancellationParent) !== undefined && + parent.isCancellable()) { + promiseToReject = parent; + } + this._unsetCancellable(); + promiseToReject._target()._rejectCallback(reason, false, true); +}; + +Promise.prototype.cancel = function (reason) { + if (!this.isCancellable()) return this; + if (reason === undefined) reason = new CancellationError(); + async.invokeLater(this._cancel, this, reason); + return this; +}; + +Promise.prototype.cancellable = function () { + if (this._cancellable()) return this; + async.enableTrampoline(); + this._setCancellable(); + this._cancellationParent = undefined; + return this; +}; + +Promise.prototype.uncancellable = function () { + var ret = this.then(); + ret._unsetCancellable(); + return ret; +}; + +Promise.prototype.fork = function (didFulfill, didReject, didProgress) { + var ret = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + + ret._setCancellable(); + ret._cancellationParent = undefined; + return ret; +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js new file mode 100644 index 0000000..6fda9e8 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js @@ -0,0 +1,492 @@ +"use strict"; +module.exports = function() { +var async = require("./async.js"); +var util = require("./util.js"); +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var warn; + +function CapturedTrace(parent) { + this._parent = parent; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.parent = function() { + return this._parent; +}; + +CapturedTrace.prototype.hasParent = function() { + return this._parent !== undefined; +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = CapturedTrace.parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = stackFramePattern.test(line) || + " (No stack trace)" === line; + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +CapturedTrace.parseStackAndMessage = function(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +}; + +CapturedTrace.formatAndLogError = function(error, title) { + if (typeof console !== "undefined") { + var message; + if (typeof error === "object" || typeof error === "function") { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof warn === "function") { + warn(message); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +}; + +CapturedTrace.unhandledRejection = function (reason) { + CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: "); +}; + +CapturedTrace.isSupported = function () { + return typeof captureStackTrace === "function"; +}; + +CapturedTrace.fireRejectionEvent = +function(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); + } + } + + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + } +}; + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj.toString(); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} +CapturedTrace.setBounds = function(firstLineError, lastLineError) { + if (!CapturedTrace.isSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow) { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); + } + }; + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; + } + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); + } + return true; + }; + } +})(); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + warn = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + warn = function(message) { + process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + warn = function(message) { + console.warn("%c" + message, "color: red"); + }; + } +} + +return CapturedTrace; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js new file mode 100644 index 0000000..040f057 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js @@ -0,0 +1,66 @@ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = require("./util.js"); +var errors = require("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = require("./es5.js").keys; +var TypeError = errors.TypeError; + +function CatchFilter(instances, callback, promise) { + this._instances = instances; + this._callback = callback; + this._promise = promise; +} + +function safePredicate(predicate, e) { + var safeObject = {}; + var retfilter = tryCatch(predicate).call(safeObject, e); + + if (retfilter === errorObj) return retfilter; + + var safeKeys = keys(safeObject); + if (safeKeys.length) { + errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); + return errorObj; + } + return retfilter; +} + +CatchFilter.prototype.doFilter = function (e) { + var cb = this._callback; + var promise = this._promise; + var boundTo = promise._boundTo; + for (var i = 0, len = this._instances.length; i < len; ++i) { + var item = this._instances[i]; + var itemIsErrorType = item === Error || + (item != null && item.prototype instanceof Error); + + if (itemIsErrorType && e instanceof item) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } else if (typeof item === "function" && !itemIsErrorType) { + var shouldHandle = safePredicate(item, e); + if (shouldHandle === errorObj) { + e = errorObj.e; + break; + } else if (shouldHandle) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } + } + } + NEXT_FILTER.e = e; + return NEXT_FILTER; +}; + +return CatchFilter; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js new file mode 100644 index 0000000..ccd7702 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/context.js @@ -0,0 +1,38 @@ +"use strict"; +module.exports = function(Promise, CapturedTrace, isDebugging) { +var contextStack = []; +function Context() { + this._trace = new CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.pop(); + } +}; + +function createContext() { + if (isDebugging()) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} + +Promise.prototype._peekContext = peekContext; +Promise.prototype._pushContext = Context.prototype._pushContext; +Promise.prototype._popContext = Context.prototype._popContext; + +return createContext; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js new file mode 100644 index 0000000..5ac1767 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/debuggability.js @@ -0,0 +1,147 @@ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var async = require("./async.js"); +var Warning = require("./errors.js").Warning; +var util = require("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +if (debugging) { + async.disableTrampolineIfNecessary(); +} + +Promise.prototype._ensurePossibleRejectionHandled = function () { + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + CapturedTrace.fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._getCarriedStackTrace() || this._settledValue; + this._setUnhandledRejectionIsNotified(); + CapturedTrace.fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 524288; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~524288); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 524288) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 2097152; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~2097152); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 2097152) > 0; +}; + +Promise.prototype._setCarriedStackTrace = function (capturedTrace) { + this._bitField = this._bitField | 1048576; + this._fulfillmentHandler0 = capturedTrace; +}; + +Promise.prototype._isCarryingStackTrace = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._getCarriedStackTrace = function () { + return this._isCarryingStackTrace() + ? this._fulfillmentHandler0 + : undefined; +}; + +Promise.prototype._captureStackTrace = function () { + if (debugging) { + this._trace = new CapturedTrace(this._peekContext()); + } + return this; +}; + +Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { + if (debugging && canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = CapturedTrace.parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +}; + +Promise.prototype._warn = function(message) { + var warning = new Warning(message); + var ctx = this._peekContext(); + if (ctx) { + ctx.attachExtraTrace(warning); + } else { + var parsed = CapturedTrace.parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + CapturedTrace.formatAndLogError(warning, ""); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + unhandledRejectionHandled = typeof fn === "function" ? fn : undefined; +}; + +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && + debugging === false + ) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); + } + debugging = CapturedTrace.isSupported(); + if (debugging) { + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js new file mode 100644 index 0000000..47a9ce9 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js @@ -0,0 +1,62 @@ +"use strict"; +var util = require("./util.js"); +var isPrimitive = util.isPrimitive; +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; + +module.exports = function(Promise) { +var returner = function () { + return this; +}; +var thrower = function () { + throw this; +}; +var returnUndefined = function() {}; +var throwUndefined = function() { + throw undefined; +}; + +var wrapper = function (value, action) { + if (action === 1) { + return function () { + throw value; + }; + } else if (action === 2) { + return function () { + return value; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value === undefined) return this.then(returnUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js new file mode 100644 index 0000000..a37e22c --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js @@ -0,0 +1,12 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, null, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, null, INTERNAL); +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js new file mode 100644 index 0000000..c334bb1 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js @@ -0,0 +1,111 @@ +"use strict"; +var es5 = require("./es5.js"); +var Objectfreeze = es5.freeze; +var util = require("./util.js"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} + +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; + + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + +} +inherits(OperationalError, Error); + +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js new file mode 100644 index 0000000..ea41d5a --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js @@ -0,0 +1,80 @@ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js new file mode 100644 index 0000000..ed57bf0 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js @@ -0,0 +1,12 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseMap = Promise.map; + +Promise.prototype.filter = function (fn, options) { + return PromiseMap(this, fn, options, INTERNAL); +}; + +Promise.filter = function (promises, fn, options) { + return PromiseMap(promises, fn, options, INTERNAL); +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js new file mode 100644 index 0000000..ed84a2a --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js @@ -0,0 +1,99 @@ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = require("./util.js"); +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, reasonOrValue, + promise.isFulfilled()); + } + } + + if (promise.isRejected()) { + NEXT_FILTER.e = reasonOrValue; + return NEXT_FILTER; + } else { + return reasonOrValue; + } +} + +function tapHandler(value) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo, value) + : handler(value); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, value, true); + } + } + return value; +} + +Promise.prototype._passThroughHandler = function (handler, isFinally) { + if (typeof handler !== "function") return this.then(); + + var promiseAndHandler = { + promise: this, + handler: handler + }; + + return this._then( + isFinally ? finallyHandler : tapHandler, + isFinally ? finallyHandler : undefined, undefined, + promiseAndHandler, undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThroughHandler(handler, true); +}; + +Promise.prototype.tap = function (handler) { + return this._passThroughHandler(handler, false); +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js new file mode 100644 index 0000000..4c0568d --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js @@ -0,0 +1,136 @@ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = require("./errors.js"); +var TypeError = errors.TypeError; +var util = require("./util.js"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; +} + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._next(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + if (result === errorObj) { + return this._promise._rejectCallback(result.e, false, true); + } + + var value = result.value; + if (result.done === true) { + this._promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._throw( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise._then( + this._next, + this._throw, + undefined, + this, + null + ); + } +}; + +PromiseSpawn.prototype._throw = function (reason) { + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._next = function (value) { + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + spawn._generator = generator; + spawn._next(undefined); + return spawn.promise(); + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js new file mode 100644 index 0000000..cf33eb1 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js @@ -0,0 +1,107 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = require("./util.js"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!false) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var caller = function(count) { + var values = []; + for (var i = 1; i <= count; ++i) values.push("holder.p" + i); + return new Function("holder", " \n\ + 'use strict'; \n\ + var callback = holder.fn; \n\ + return callback(values); \n\ + ".replace(/values/g, values.join(", "))); + }; + var thenCallbacks = []; + var callers = [undefined]; + for (var i = 1; i <= 5; ++i) { + thenCallbacks.push(thenCallback(i)); + callers.push(caller(i)); + } + + var Holder = function(total, fn) { + this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; + this.fn = fn; + this.total = total; + this.now = 0; + }; + + Holder.prototype.callers = callers; + Holder.prototype.checkFulfillment = function(promise) { + var now = this.now; + now++; + var total = this.total; + if (now >= total) { + var handler = this.callers[total]; + promise._pushContext(); + var ret = tryCatch(handler)(this); + promise._popContext(); + if (ret === errorObj) { + promise._rejectCallback(ret.e, false, true); + } else { + promise._resolveCallback(ret); + } + } else { + this.now = now; + } + }; + + var reject = function (reason) { + this._reject(reason); + }; +} +} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!false) { + if (last < 6 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var holder = new Holder(last, fn); + var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + } else if (maybePromise._isFulfilled()) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else { + ret._reject(maybePromise._reason()); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + return ret; + } + } + } + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js new file mode 100644 index 0000000..66a5b17 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js @@ -0,0 +1,131 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = require("./async.js"); +var util = require("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var PENDING = {}; +var EMPTY_ARRAY = []; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._callback = fn; + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + async.invoke(init, this, undefined); +} +util.inherits(MappingPromiseArray, PromiseArray); +function init() {this._init$(undefined, -2);} + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + if (values[index] === PENDING) { + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return; + } + if (preservedValues !== null) preservedValues[index] = value; + + var callback = this._callback; + var receiver = this._promise._boundTo; + this._promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + this._promise._popContext(); + if (ret === errorObj) return this._reject(ret.e); + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + if (limit >= 1) this._inFlight++; + values[index] = PENDING; + return maybePromise._proxyPromiseArray(this, index); + } else if (maybePromise._isFulfilled()) { + ret = maybePromise._value(); + } else { + return this._reject(maybePromise._reason()); + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + + } +}; + +MappingPromiseArray.prototype._drainQueue = function () { + var queue = this._queue; + var limit = this._limit; + var values = this._values; + while (queue.length > 0 && this._inFlight < limit) { + if (this._isResolved()) return; + var index = queue.pop(); + this._promiseFulfilled(values[index], index); + } +}; + +MappingPromiseArray.prototype._filter = function (booleans, values) { + var len = values.length; + var ret = new Array(len); + var j = 0; + for (var i = 0; i < len; ++i) { + if (booleans[i]) ret[j++] = values[i]; + } + ret.length = j; + this._resolve(ret); +}; + +MappingPromiseArray.prototype.preservedValues = function () { + return this._preservedValues; +}; + +function map(promises, fn, options, _filter) { + var limit = typeof options === "object" && options !== null + ? options.concurrency + : 0; + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter); +} + +Promise.prototype.map = function (fn, options) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + + return map(this, fn, options, null).promise(); +}; + +Promise.map = function (promises, fn, options, _filter) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + return map(promises, fn, options, _filter).promise(); +}; + + +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js new file mode 100644 index 0000000..3d3eeb1 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/method.js @@ -0,0 +1,44 @@ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = require("./util.js"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn, args, ctx) { + if (typeof fn !== "function") { + return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = util.isArray(args) + ? tryCatch(fn).apply(ctx, args) + : tryCatch(fn).call(ctx, args); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false, true); + } else { + this._resolveCallback(value, true); + } +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js new file mode 100644 index 0000000..f305b93 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise) { +var util = require("./util.js"); +var async = require("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundTo; + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var target = promise._target(); + var newReason = target._getCarriedStackTrace(); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundTo, reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = +Promise.prototype.nodeify = function (nodeback, options) { + if (typeof nodeback == "function") { + var adapter = successAdapter; + if (options !== undefined && Object(options).spread) { + adapter = spreadAdapter; + } + this._then( + adapter, + errorAdapter, + undefined, + this, + nodeback + ); + } + return this; +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js new file mode 100644 index 0000000..2e3e95e --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js @@ -0,0 +1,76 @@ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = require("./util.js"); +var async = require("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +Promise.prototype.progressed = function (handler) { + return this._then(undefined, undefined, handler, undefined, undefined); +}; + +Promise.prototype._progress = function (progressValue) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._target()._progressUnchecked(progressValue); + +}; + +Promise.prototype._progressHandlerAt = function (index) { + return index === 0 + ? this._progressHandler0 + : this[(index << 2) + index - 5 + 2]; +}; + +Promise.prototype._doProgressWith = function (progression) { + var progressValue = progression.value; + var handler = progression.handler; + var promise = progression.promise; + var receiver = progression.receiver; + + var ret = tryCatch(handler).call(receiver, progressValue); + if (ret === errorObj) { + if (ret.e != null && + ret.e.name !== "StopProgressPropagation") { + var trace = util.canAttachTrace(ret.e) + ? ret.e : new Error(util.toString(ret.e)); + promise._attachExtraTrace(trace); + promise._progress(ret.e); + } + } else if (ret instanceof Promise) { + ret._then(promise._progress, null, null, promise, undefined); + } else { + promise._progress(ret); + } +}; + + +Promise.prototype._progressUnchecked = function (progressValue) { + var len = this._length(); + var progress = this._progress; + for (var i = 0; i < len; i++) { + var handler = this._progressHandlerAt(i); + var promise = this._promiseAt(i); + if (!(promise instanceof Promise)) { + var receiver = this._receiverAt(i); + if (typeof handler === "function") { + handler.call(receiver, progressValue, promise); + } else if (receiver instanceof PromiseArray && + !receiver._isResolved()) { + receiver._promiseProgressed(progressValue, promise); + } + continue; + } + + if (typeof handler === "function") { + async.invoke(this._doProgressWith, this, { + handler: handler, + promise: promise, + receiver: this._receiverAt(i), + value: progressValue + }); + } else { + async.invoke(progress, promise, progressValue); + } + } +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js new file mode 100644 index 0000000..f80d247 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js @@ -0,0 +1,700 @@ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); +}; +var reflect = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +var util = require("./util.js"); +var async = require("./async.js"); +var errors = require("./errors.js"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {e: null}; +var tryConvertToPromise = require("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + require("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = require("./captured_trace.js")(); +var isDebugging = require("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + require("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = require("./promise_resolver.js"); +var nodebackForPromise = PromiseResolver._nodebackForPromise; +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function Promise(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); + } + if (this.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._progressHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._settledValue = undefined; + if (resolver !== INTERNAL) this._resolveFromResolver(resolver); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (typeof item === "function") { + catchInstances[j++] = item; + } else { + return Promise.reject( + new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); + } + } + catchInstances.length = j; + fn = arguments[i]; + var catchFilter = new CatchFilter(catchInstances, fn, this); + return this._then(undefined, catchFilter.doFilter, undefined, + catchFilter, undefined); + } + return this._then(undefined, fn, undefined, undefined, undefined); +}; + +Promise.prototype.reflect = function () { + return this._then(reflect, reflect, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject, didProgress) { + if (isDebugging() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, didProgress, + undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject, didProgress) { + var promise = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (didFulfill, didReject) { + return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); +}; + +Promise.prototype.isCancellable = function () { + return !this.isResolved() && + this._cancellable(); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = function(fn) { + var ret = new Promise(INTERNAL); + var result = tryCatch(fn)(nodebackForPromise(ret)); + if (result === errorObj) { + ret._rejectCallback(result.e, true, true); + } + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.defer = Promise.pending = function () { + var promise = new Promise(INTERNAL); + return new PromiseResolver(promise); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + var val = ret; + ret = new Promise(INTERNAL); + ret._fulfillUnchecked(val); + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + didProgress, + receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var ret = haveInternalData ? internalData : new Promise(INTERNAL); + + if (!haveInternalData) { + ret._propagateFrom(this, 4 | 1); + ret._captureStackTrace(); + } + + var target = this._target(); + if (target !== this) { + if (receiver === undefined) receiver = this._boundTo; + if (!haveInternalData) ret._setIsMigrated(); + } + + var callbackIndex = + target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); + + if (target._isResolved() && !target._isSettlePromisesQueued()) { + async.invoke( + target._settlePromiseAtPostResolution, target, callbackIndex); + } + + return ret; +}; + +Promise.prototype._settlePromiseAtPostResolution = function (index) { + if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); + this._settlePromiseAt(index); +}; + +Promise.prototype._length = function () { + return this._bitField & 131071; +}; + +Promise.prototype._isFollowingOrFulfilledOrRejected = function () { + return (this._bitField & 939524096) > 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 536870912) === 536870912; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -131072) | + (len & 131071); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 536870912; +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 33554432; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 33554432) > 0; +}; + +Promise.prototype._cancellable = function () { + return (this._bitField & 67108864) > 0; +}; + +Promise.prototype._setCancellable = function () { + this._bitField = this._bitField | 67108864; +}; + +Promise.prototype._unsetCancellable = function () { + this._bitField = this._bitField & (~67108864); +}; + +Promise.prototype._setIsMigrated = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._unsetIsMigrated = function () { + this._bitField = this._bitField & (~4194304); +}; + +Promise.prototype._isMigrated = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 + ? this._receiver0 + : this[ + index * 5 - 5 + 4]; + if (ret === undefined && this._isBound()) { + return this._boundTo; + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return index === 0 + ? this._promise0 + : this[index * 5 - 5 + 3]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return index === 0 + ? this._fulfillmentHandler0 + : this[index * 5 - 5 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return index === 0 + ? this._rejectionHandler0 + : this[index * 5 - 5 + 1]; +}; + +Promise.prototype._migrateCallbacks = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var progress = follower._progressHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (promise instanceof Promise) promise._setIsMigrated(); + this._addCallbacks(fulfill, reject, progress, promise, receiver); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + progress, + promise, + receiver +) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + if (receiver !== undefined) this._receiver0 = receiver; + if (typeof fulfill === "function" && !this._isCarryingStackTrace()) + this._fulfillmentHandler0 = fulfill; + if (typeof reject === "function") this._rejectionHandler0 = reject; + if (typeof progress === "function") this._progressHandler0 = progress; + } else { + var base = index * 5 - 5; + this[base + 3] = promise; + this[base + 4] = receiver; + if (typeof fulfill === "function") + this[base + 0] = fulfill; + if (typeof reject === "function") + this[base + 1] = reject; + if (typeof progress === "function") + this[base + 2] = progress; + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + if (index === 0) { + this._promise0 = promiseSlotValue; + this._receiver0 = receiver; + } else { + var base = index * 5 - 5; + this[base + 3] = promiseSlotValue; + this[base + 4] = receiver; + } + this._setLength(index + 1); +}; + +Promise.prototype._proxyPromiseArray = function (promiseArray, index) { + this._setProxyHandlers(promiseArray, index); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (this._isFollowingOrFulfilledOrRejected()) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false, true); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + var propagationFlags = 1 | (shouldBind ? 4 : 0); + this._propagateFrom(maybePromise, propagationFlags); + var promise = maybePromise._target(); + if (promise._isPending()) { + var len = this._length(); + for (var i = 0; i < len; ++i) { + promise._migrateCallbacks(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (promise._isFulfilled()) { + this._fulfillUnchecked(promise._value()); + } else { + this._rejectUnchecked(promise._reason(), + promise._getCarriedStackTrace()); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { + if (!shouldNotMarkOriginatingFromRejection) { + util.markAsOriginatingFromRejection(reason); + } + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, hasStack ? undefined : trace); +}; + +Promise.prototype._resolveFromResolver = function (resolver) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = tryCatch(resolver)(function(value) { + if (promise === null) return; + promise._resolveCallback(value); + promise = null; + }, function (reason) { + if (promise === null) return; + promise._rejectCallback(reason, synchronous); + promise = null; + }); + synchronous = false; + this._popContext(); + + if (r !== undefined && r === errorObj && promise !== null) { + promise._rejectCallback(r.e, true, true); + promise = null; + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + if (promise._isRejected()) return; + promise._pushContext(); + var x; + if (receiver === APPLY && !this._isRejected()) { + x = tryCatch(handler).apply(this._boundTo, value); + } else { + x = tryCatch(handler).call(receiver, value); + } + promise._popContext(); + + if (x === errorObj || x === promise || x === NEXT_FILTER) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false, true); + } else { + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._cleanValues = function () { + if (this._cancellable()) { + this._cancellationParent = undefined; + } +}; + +Promise.prototype._propagateFrom = function (parent, flags) { + if ((flags & 1) > 0 && parent._cancellable()) { + this._setCancellable(); + this._cancellationParent = parent; + } + if ((flags & 4) > 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +}; + +Promise.prototype._fulfill = function (value) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._fulfillUnchecked(value); +}; + +Promise.prototype._reject = function (reason, carriedStackTrace) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._rejectUnchecked(reason, carriedStackTrace); +}; + +Promise.prototype._settlePromiseAt = function (index) { + var promise = this._promiseAt(index); + var isPromise = promise instanceof Promise; + + if (isPromise && promise._isMigrated()) { + promise._unsetIsMigrated(); + return async.invoke(this._settlePromiseAt, this, index); + } + var handler = this._isFulfilled() + ? this._fulfillmentHandlerAt(index) + : this._rejectionHandlerAt(index); + + var carriedStackTrace = + this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; + var value = this._settledValue; + var receiver = this._receiverAt(index); + + + this._clearCallbackDataAtIndex(index); + + if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof PromiseArray) { + if (!receiver._isResolved()) { + if (this._isFulfilled()) { + receiver._promiseFulfilled(value, promise); + } + else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (this._isFulfilled()) { + promise._fulfill(value); + } else { + promise._reject(value, carriedStackTrace); + } + } + + if (index >= 4 && (index & 31) === 4) + async.invokeLater(this._setLength, this, 0); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + if (index === 0) { + if (!this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = undefined; + } + this._rejectionHandler0 = + this._progressHandler0 = + this._receiver0 = + this._promise0 = undefined; + } else { + var base = index * 5 - 5; + this[base + 3] = + this[base + 4] = + this[base + 0] = + this[base + 1] = + this[base + 2] = undefined; + } +}; + +Promise.prototype._isSettlePromisesQueued = function () { + return (this._bitField & + -1073741824) === -1073741824; +}; + +Promise.prototype._setSettlePromisesQueued = function () { + this._bitField = this._bitField | -1073741824; +}; + +Promise.prototype._unsetSettlePromisesQueued = function () { + this._bitField = this._bitField & (~-1073741824); +}; + +Promise.prototype._queueSettlePromises = function() { + async.settlePromises(this); + this._setSettlePromisesQueued(); +}; + +Promise.prototype._fulfillUnchecked = function (value) { + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err, undefined); + } + this._setFulfilled(); + this._settledValue = value; + this._cleanValues(); + + if (this._length() > 0) { + this._queueSettlePromises(); + } +}; + +Promise.prototype._rejectUncheckedCheckError = function (reason) { + var trace = util.ensureErrorObject(reason); + this._rejectUnchecked(reason, trace === reason ? undefined : trace); +}; + +Promise.prototype._rejectUnchecked = function (reason, trace) { + if (reason === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err); + } + this._setRejected(); + this._settledValue = reason; + this._cleanValues(); + + if (this._isFinal()) { + async.throwLater(function(e) { + if ("stack" in e) { + async.invokeFirst( + CapturedTrace.unhandledRejection, undefined, e); + } + throw e; + }, trace === undefined ? reason : trace); + return; + } + + if (trace !== undefined && trace !== reason) { + this._setCarriedStackTrace(trace); + } + + if (this._length() > 0) { + this._queueSettlePromises(); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._settlePromises = function () { + this._unsetSettlePromisesQueued(); + var len = this._length(); + for (var i = 0; i < len; i++) { + this._settlePromiseAt(i); + } +}; + +Promise._makeSelfResolutionError = makeSelfResolutionError; +require("./progress.js")(Promise, PromiseArray); +require("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +require("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +require("./direct_resolve.js")(Promise); +require("./synchronous_inspection.js")(Promise); +require("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./cancel.js')(Promise); +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +require('./nodeify.js')(Promise); +require('./call_get.js')(Promise); +require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./settle.js')(Promise, PromiseArray); +require('./some.js')(Promise, PromiseArray, apiRejection); +require('./promisify.js')(Promise, INTERNAL); +require('./any.js')(Promise); +require('./each.js')(Promise, INTERNAL); +require('./timers.js')(Promise, INTERNAL); +require('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._progressHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + p._settledValue = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + CapturedTrace.setBounds(async.firstLineError, util.lastLineError); + return Promise; + +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js new file mode 100644 index 0000000..6dac866 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js @@ -0,0 +1,142 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = require("./util.js"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + var parent; + if (values instanceof Promise) { + parent = values; + promise._propagateFrom(parent, 1 | 4); + } + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + this._values = values; + if (values._isFulfilled()) { + values = values._value(); + if (!isArray(values)) { + var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + this.__hardReject__(err); + return; + } + } else if (values._isPending()) { + values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + return; + } else { + this._reject(values._reason()); + return; + } + } else if (!isArray(values)) { + this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var promise = this._promise; + for (var i = 0; i < len; ++i) { + var isResolved = this._isResolved(); + var maybePromise = tryConvertToPromise(values[i], promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (isResolved) { + maybePromise._unsetRejectionIsUnhandled(); + } else if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, i); + } else if (maybePromise._isFulfilled()) { + this._promiseFulfilled(maybePromise._value(), i); + } else { + this._promiseRejected(maybePromise._reason(), i); + } + } else if (!isResolved) { + this._promiseFulfilled(maybePromise, i); + } + } +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype.__hardReject__ = +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false, true); +}; + +PromiseArray.prototype._promiseProgressed = function (progressValue, index) { + this._promise._progress({ + index: index, + value: progressValue + }); +}; + + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +PromiseArray.prototype._promiseRejected = function (reason, index) { + this._totalResolved++; + this._reject(reason); +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js new file mode 100644 index 0000000..b180a32 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js @@ -0,0 +1,123 @@ +"use strict"; +var util = require("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = require("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = require("./es5.js"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise) { + return function(err, value) { + if (promise === null) return; + + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (arguments.length > 2) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + promise._fulfill(args); + } else { + promise._fulfill(value); + } + + promise = null; + }; +} + + +var PromiseResolver; +if (!haveGetters) { + PromiseResolver = function (promise) { + this.promise = promise; + this.asCallback = nodebackForPromise(promise); + this.callback = this.asCallback; + }; +} +else { + PromiseResolver = function (promise) { + this.promise = promise; + }; +} +if (haveGetters) { + var prop = { + get: function() { + return nodebackForPromise(this.promise); + } + }; + es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); + es5.defineProperty(PromiseResolver.prototype, "callback", prop); +} + +PromiseResolver._nodebackForPromise = nodebackForPromise; + +PromiseResolver.prototype.toString = function () { + return "[object PromiseResolver]"; +}; + +PromiseResolver.prototype.resolve = +PromiseResolver.prototype.fulfill = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._resolveCallback(value); +}; + +PromiseResolver.prototype.reject = function (reason) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._rejectCallback(reason); +}; + +PromiseResolver.prototype.progress = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._progress(value); +}; + +PromiseResolver.prototype.cancel = function (err) { + this.promise.cancel(err); +}; + +PromiseResolver.prototype.timeout = function () { + this.reject(new TimeoutError("timeout")); +}; + +PromiseResolver.prototype.isResolved = function () { + return this.promise.isResolved(); +}; + +PromiseResolver.prototype.toJSON = function () { + return this.promise.toJSON(); +}; + +module.exports = PromiseResolver; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js new file mode 100644 index 0000000..0355344 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js @@ -0,0 +1,291 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = require("./util.js"); +var nodebackForPromise = require("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = require("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyPropsPattern = + /^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/; +var defaultFilter = function(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} + +function isPromisified(fn) { + try { + return fn.__isPromisified__ === true; + } + catch (e) { + return false; + } +} + +function hasPromisified(obj, key, suffix) { + var val = util.getDataPropertyOrDefault(obj, key + suffix, + defaultPromisified); + return val ? isPromisified(val) : false; +} +function checkValid(ret, suffix, suffixRegexp) { + for (var i = 0; i < ret.length; i += 2) { + var key = ret[i]; + if (suffixRegexp.test(key)) { + var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); + for (var j = 0; j < ret.length; j += 2) { + if (ret[j] === keyWithoutAsyncSuffix) { + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a" + .replace("%s", suffix)); + } + } + } + } +} + +function promisifiableMethods(obj, suffix, suffixRegexp, filter) { + var keys = util.inheritedDataKeys(obj); + var ret = []; + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var value = obj[key]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} + +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!false) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { + var ret = [likelyArgumentCount]; + var min = Math.max(0, likelyArgumentCount - 1 - 3); + for(var i = likelyArgumentCount - 1; i >= min; --i) { + ret.push(i); + } + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { + ret.push(i); + } + return ret; +}; + +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; + +var parameterCount = function(fn) { + if (typeof fn.length === "number") { + return Math.max(Math.min(fn.length, 1023 + 1), 0); + } + return 0; +}; + +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn) { + var newParameterCount = Math.max(0, parameterCount(fn) - 1); + var argumentOrder = switchCaseArgumentOrder(newParameterCount); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; + + function generateCallForArgumentCount(count) { + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; + } + return ret.replace("{{args}}", args).replace(", ", comma); + } + + function generateArgumentSwitchCase() { + var ret = ""; + for (var i = 0; i < argumentOrder.length; ++i) { + ret += "case " + argumentOrder[i] +":" + + generateCallForArgumentCount(argumentOrder[i]); + } + + ret += " \n\ + default: \n\ + var args = new Array(len + 1); \n\ + var i = 0; \n\ + for (var i = 0; i < len; ++i) { \n\ + args[i] = arguments[i]; \n\ + } \n\ + args[i] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); + return ret; + } + + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "INTERNAL","'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + return promise; \n\ + }; \n\ + ret.__isPromisified__ = true; \n\ + return ret; \n\ + " + .replace("Parameters", parameterDeclaration(newParameterCount)) + .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode))( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + INTERNAL + ); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } + function promisified() { + var _receiver = receiver; + if (receiver === THIS) _receiver = this; + var promise = new Promise(INTERNAL); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; + var fn = nodebackForPromise(promise); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + return promise; + } + promisified.__isPromisified__ = true; + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier) { + var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); + var methods = + promisifiableMethods(obj, suffix, suffixRegexp, filter); + + for (var i = 0, len = methods.length; i < len; i+= 2) { + var key = methods[i]; + var fn = methods[i+1]; + var promisifiedKey = key + suffix; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver) { + return makeNodePromisified(callback, receiver, undefined, callback); +} + +Promise.promisify = function (fn, receiver) { + if (typeof fn !== "function") { + throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + if (isPromisified(fn)) { + return fn; + } + var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + util.copyDescriptors(fn, ret, propsFilter); + return ret; +}; + +Promise.promisifyAll = function (target, options) { + if (typeof target !== "function" && typeof target !== "object") { + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a"); + } + options = Object(options); + var suffix = options.suffix; + if (typeof suffix !== "string") suffix = defaultSuffix; + var filter = options.filter; + if (typeof filter !== "function") filter = defaultFilter; + var promisifier = options.promisifier; + if (typeof promisifier !== "function") promisifier = makeNodePromisified; + + if (!util.isIdentifier(suffix)) { + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); + } + + var keys = util.inheritedDataKeys(target); + for (var i = 0; i < keys.length; ++i) { + var value = target[keys[i]]; + if (keys[i] !== "constructor" && + util.isClass(value)) { + promisifyAll(value.prototype, suffix, filter, promisifier); + promisifyAll(value, suffix, filter, promisifier); + } + } + + return promisifyAll(target, suffix, filter, promisifier); +}; +}; + diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js new file mode 100644 index 0000000..d6f9e64 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js @@ -0,0 +1,79 @@ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = require("./util.js"); +var isObject = util.isObject; +var es5 = require("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; +}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val = {}; + var keyOffset = this.length(); + for (var i = 0, len = this.length(); i < len; ++i) { + val[this._values[i + keyOffset]] = this._values[i]; + } + this._resolve(val); + } +}; + +PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { + this._promise._progress({ + key: this._values[index + this.length()], + value: value + }); +}; + +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; + +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); + + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } + + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 4); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js new file mode 100644 index 0000000..84d57d5 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js @@ -0,0 +1,90 @@ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js new file mode 100644 index 0000000..30e7bb0 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js @@ -0,0 +1,47 @@ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = require("./util.js").isArray; + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else if (!isArray(promises)) { + return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 4 | 1); + } + var fulfill = ret._fulfill; + var reject = ret._reject; + for (var i = 0, len = promises.length; i < len; ++i) { + var val = promises[i]; + + if (val === undefined && !(i in promises)) { + continue; + } + + Promise.cast(val)._then(fulfill, reject, undefined, ret, null); + } + return ret; +} + +Promise.race = function (promises) { + return race(promises, undefined); +}; + +Promise.prototype.race = function () { + return race(this, undefined); +}; + +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js new file mode 100644 index 0000000..3192220 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js @@ -0,0 +1,146 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var async = require("./async.js"); +var util = require("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +function ReductionPromiseArray(promises, fn, accum, _each) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._preservedValues = _each === INTERNAL ? [] : null; + this._zerothIsAccum = (accum === undefined); + this._gotAccum = false; + this._reducingIndex = (this._zerothIsAccum ? 1 : 0); + this._valuesPhase = undefined; + var maybePromise = tryConvertToPromise(accum, this._promise); + var rejected = false; + var isPromise = maybePromise instanceof Promise; + if (isPromise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, -1); + } else if (maybePromise._isFulfilled()) { + accum = maybePromise._value(); + this._gotAccum = true; + } else { + this._reject(maybePromise._reason()); + rejected = true; + } + } + if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; + this._callback = fn; + this._accum = accum; + if (!rejected) async.invoke(init, this, undefined); +} +function init() { + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._init = function () {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); + } +}; + +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + values[index] = value; + var length = this.length(); + var preservedValues = this._preservedValues; + var isEach = preservedValues !== null; + var gotAccum = this._gotAccum; + var valuesPhase = this._valuesPhase; + var valuesPhaseIndex; + if (!valuesPhase) { + valuesPhase = this._valuesPhase = new Array(length); + for (valuesPhaseIndex=0; valuesPhaseIndex 10) || (version[0] > 0) + ? function(fn) { global.setImmediate(fn); } : process.nextTick; + + if (!schedule) { + if (typeof setImmediate !== "undefined") { + schedule = setImmediate; + } else if (typeof setTimeout !== "undefined") { + schedule = setTimeout; + } else { + schedule = noAsyncScheduler; + } + } +} else if (typeof MutationObserver !== "undefined") { + schedule = function(fn) { + var div = document.createElement("div"); + var observer = new MutationObserver(fn); + observer.observe(div, {attributes: true}); + return function() { div.classList.toggle("foo"); }; + }; + schedule.isStatic = true; +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js new file mode 100644 index 0000000..f9299c2 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js @@ -0,0 +1,40 @@ +"use strict"; +module.exports = + function(Promise, PromiseArray) { +var PromiseInspection = Promise.PromiseInspection; +var util = require("./util.js"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 268435456; + ret._settledValue = value; + this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 134217728; + ret._settledValue = reason; + this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return new SettledPromiseArray(this).promise(); +}; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js new file mode 100644 index 0000000..f3968cf --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js @@ -0,0 +1,125 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = require("./util.js"); +var RangeError = require("./errors.js").RangeError; +var AggregateError = require("./errors.js").AggregateError; +var isArray = util.isArray; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + this._addFulfilled(value); + if (this._fulfilled() === this.howMany()) { + this._values.length = this.howMany(); + if (this.howMany() === 1 && this._unwrap) { + this._resolve(this._values[0]); + } else { + this._resolve(this._values); + } + } + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + e.push(this._values[i]); + } + this._reject(e); + } +}; + +SomePromiseArray.prototype._fulfilled = function () { + return this._totalResolved; +}; + +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); +}; + +SomePromiseArray.prototype._addRejected = function (reason) { + this._values.push(reason); +}; + +SomePromiseArray.prototype._addFulfilled = function (value) { + this._values[this._totalResolved++] = value; +}; + +SomePromiseArray.prototype._canPossiblyFulfill = function () { + return this.length() - this._rejected(); +}; + +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); +}; + +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; + +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} + +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; + +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; + +Promise._SomePromiseArray = SomePromiseArray; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js new file mode 100644 index 0000000..7aac149 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js @@ -0,0 +1,94 @@ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValue = promise._settledValue; + } + else { + this._bitField = 0; + this._settledValue = undefined; + } +} + +PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.isFulfilled = +Promise.prototype._isFulfilled = function () { + return (this._bitField & 268435456) > 0; +}; + +PromiseInspection.prototype.isRejected = +Promise.prototype._isRejected = function () { + return (this._bitField & 134217728) > 0; +}; + +PromiseInspection.prototype.isPending = +Promise.prototype._isPending = function () { + return (this._bitField & 402653184) === 0; +}; + +PromiseInspection.prototype.isResolved = +Promise.prototype._isResolved = function () { + return (this._bitField & 402653184) > 0; +}; + +Promise.prototype.isPending = function() { + return this._target()._isPending(); +}; + +Promise.prototype.isRejected = function() { + return this._target()._isRejected(); +}; + +Promise.prototype.isFulfilled = function() { + return this._target()._isFulfilled(); +}; + +Promise.prototype.isResolved = function() { + return this._target()._isResolved(); +}; + +Promise.prototype._value = function() { + return this._settledValue; +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue; +}; + +Promise.prototype.value = function() { + var target = this._target(); + if (!target.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return target._settledValue; +}; + +Promise.prototype.reason = function() { + var target = this._target(); + if (!target.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + target._unsetRejectionIsUnhandled(); + return target._settledValue; +}; + + +Promise.PromiseInspection = PromiseInspection; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js new file mode 100644 index 0000000..c858f86 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js @@ -0,0 +1,89 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util.js"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) { + return obj; + } + else if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfillUnchecked, + ret._rejectUncheckedCheckError, + ret._progressUnchecked, + ret, + null + ); + return ret; + } + var then = util.tryCatch(getThen)(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + return doThenable(obj, then, context); + } + } + return obj; +} + +function getThen(obj) { + return obj.then; +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, + resolveFromThenable, + rejectFromThenable, + progressFromThenable); + synchronous = false; + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolveFromThenable(value) { + if (!promise) return; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + promise._resolveCallback(value); + } + promise = null; + } + + function rejectFromThenable(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + + function progressFromThenable(value) { + if (!promise) return; + if (typeof promise._progress === "function") { + promise._progress(value); + } + } + return ret; +} + +return tryConvertToPromise; +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js new file mode 100644 index 0000000..ecf1b57 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + if (typeof message !== "string") { + message = "operation timed out"; + } + var err = new TimeoutError(message); + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._cancel(err); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (value, ms) { + if (ms === undefined) { + ms = value; + value = undefined; + var ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, ms); + return ret; + } + ms = +ms; + return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); +}; + +Promise.prototype.delay = function (ms) { + return delay(this, ms); +}; + +function successClear(value) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + return value; +} + +function failureClear(reason) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret = this.then().cancellable(); + ret._cancellationParent = this; + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js new file mode 100644 index 0000000..4038711 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js @@ -0,0 +1,202 @@ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = require("./errors.js").TypeError; + var inherits = require("./util.js").inherits; + var PromiseInspection = Promise.PromiseInspection; + + function inspectionMapper(inspections) { + var len = inspections.length; + for (var i = 0; i < len; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + return Promise.reject(inspection.error()); + } + inspections[i] = inspection._settledValue; + } + return inspections; + } + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + if (maybePromise !== thenable && + typeof thenable._isDisposable === "function" && + typeof thenable._getDisposer === "function" && + thenable._isDisposable()) { + maybePromise._setDisposable(thenable._getDisposer()); + } + return maybePromise; + } + function dispose(resources, inspection) { + var i = 0; + var len = resources.length; + var ret = Promise.defer(); + function iterator() { + if (i >= len) return ret.resolve(); + var maybePromise = castPreservingDisposable(resources[i++]); + if (maybePromise instanceof Promise && + maybePromise._isDisposable()) { + try { + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); + } catch (e) { + return thrower(e); + } + if (maybePromise instanceof Promise) { + return maybePromise._then(iterator, thrower, + null, null, null); + } + } + iterator(); + } + iterator(); + return ret.promise; + } + + function disposerSuccess(value) { + var inspection = new PromiseInspection(); + inspection._settledValue = value; + inspection._bitField = 268435456; + return dispose(this, inspection).thenReturn(value); + } + + function disposerFail(reason) { + var inspection = new PromiseInspection(); + inspection._settledValue = reason; + inspection._bitField = 134217728; + return dispose(this, inspection).thenThrow(reason); + } + + function Disposer(data, promise, context) { + this._data = data; + this._promise = promise; + this._context = context; + } + + Disposer.prototype.data = function () { + return this._data; + }; + + Disposer.prototype.promise = function () { + return this._promise; + }; + + Disposer.prototype.resource = function () { + if (this.promise().isFulfilled()) { + return this.promise().value(); + } + return null; + }; + + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== null + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; + + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); + }; + + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); + + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); + }; + + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); + } + return value; + } + + Promise.using = function () { + var len = arguments.length; + if (len < 2) return apiRejection( + "you must pass at least 2 arguments to Promise.using"); + var fn = arguments[len - 1]; + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } + } + resources[i] = resource; + } + + var promise = Promise.settle(resources) + .then(inspectionMapper) + .then(function(vals) { + promise._pushContext(); + var ret; + try { + ret = fn.apply(undefined, vals); + } finally { + promise._popContext(); + } + return ret; + }) + ._then( + disposerSuccess, disposerFail, undefined, resources, undefined); + resources.promise = promise; + return promise; + }; + + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 262144; + this._disposer = disposer; + }; + + Promise.prototype._isDisposable = function () { + return (this._bitField & 262144) > 0; + }; + + Promise.prototype._getDisposer = function () { + return this._disposer; + }; + + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~262144); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); + }; + +}; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js new file mode 100644 index 0000000..fbee5de --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js @@ -0,0 +1,280 @@ +"use strict"; +var es5 = require("./es5.js"); +var canEvaluate = typeof navigator == "undefined"; +var haveGetters = (function(){ + try { + var o = {}; + es5.defineProperty(o, "f", { + get: function () { + return 3; + } + }); + return o.f === 3; + } + catch (e) { + return false; + } + +})(); + +var errorObj = {e: {}}; +var tryCatchTarget; +function tryCatcher() { + try { + return tryCatchTarget.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } + } + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return !isPrimitive(value); +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); +} + +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; +} + +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} + +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; +} + + +var wrapsPrimitiveReceiver = (function() { + return this !== "string"; +}).call("string"); + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + if (es5.isES5) { + var oProto = Object.prototype; + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && obj !== oProto) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function f() {} + f.prototype = obj; + var l = 8; + while (l--) new f(); + return obj; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + haveGetters: haveGetters, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" +}; +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json new file mode 100644 index 0000000..4371fc3 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json @@ -0,0 +1,97 @@ +{ + "name": "bluebird", + "description": "Full featured Promises/A+ implementation with exceptionally good performance", + "version": "2.9.26", + "keywords": [ + "promise", + "performance", + "promises", + "promises-a", + "promises-aplus", + "async", + "await", + "deferred", + "deferreds", + "future", + "flow control", + "dsl", + "fluent interface" + ], + "scripts": { + "lint": "node scripts/jshint.js", + "test": "node tools/test.js", + "istanbul": "istanbul", + "prepublish": "node tools/build.js --no-debug --main --zalgo --browser --minify" + }, + "homepage": "https://github.com/petkaantonov/bluebird", + "repository": { + "type": "git", + "url": "git://github.com/petkaantonov/bluebird.git" + }, + "bugs": { + "url": "http://github.com/petkaantonov/bluebird/issues" + }, + "license": "MIT", + "author": { + "name": "Petka Antonov", + "email": "petka_antonov@hotmail.com", + "url": "http://github.com/petkaantonov/" + }, + "devDependencies": { + "acorn": "~0.6.0", + "baconjs": "^0.7.43", + "bluebird": "^2.9.2", + "body-parser": "^1.10.2", + "browserify": "^8.1.1", + "cli-table": "~0.3.1", + "co": "^4.2.0", + "cross-spawn": "^0.2.3", + "glob": "^4.3.2", + "grunt-saucelabs": "~8.4.1", + "highland": "^2.3.0", + "istanbul": "^0.3.5", + "jshint": "^2.6.0", + "jshint-stylish": "~0.2.0", + "mkdirp": "~0.5.0", + "mocha": "~2.1", + "open": "~0.0.5", + "optimist": "~0.6.1", + "rimraf": "~2.2.6", + "rx": "^2.3.25", + "serve-static": "^1.7.1", + "sinon": "~1.7.3", + "uglify-js": "~2.4.16" + }, + "main": "./js/main/bluebird.js", + "browser": "./js/browser/bluebird.js", + "files": [ + "js/browser", + "js/main", + "js/zalgo", + "LICENSE", + "zalgo.js" + ], + "gitHead": "c6604d44f219af9da683f6e28d818008fa374af2", + "_id": "bluebird@2.9.26", + "_shasum": "362772ea4d09f556a4b9f3b64c2fd136e87e3a55", + "_from": "bluebird@2.9.26", + "_npmVersion": "2.7.1", + "_nodeVersion": "1.6.2", + "_npmUser": { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + }, + "maintainers": [ + { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + } + ], + "dist": { + "shasum": "362772ea4d09f556a4b9f3b64c2fd136e87e3a55", + "tarball": "http://registry.npmjs.org/bluebird/-/bluebird-2.9.26.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.9.26.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/.jshintrc b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md new file mode 100644 index 0000000..854c971 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md @@ -0,0 +1,195 @@ + +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 +================== + + * 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/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile new file mode 100644 index 0000000..5cf4a59 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile @@ -0,0 +1,36 @@ + +# 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 dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +distclean: clean + @rm -rf node_modules + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean distclean diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md new file mode 100644 index 0000000..b4f45e3 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md @@ -0,0 +1,188 @@ +# 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'); +``` + +### 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 + - 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/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/bower.json b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/bower.json new file mode 100644 index 0000000..6af573f --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/bower.json @@ -0,0 +1,28 @@ +{ + "name": "visionmedia-debug", + "main": "dist/debug.js", + "version": "2.2.0", + "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/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/browser.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/browser.js new file mode 100644 index 0000000..7c76452 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/browser.js @@ -0,0 +1,168 @@ + +/** + * 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; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : 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) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.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/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/component.json b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/component.json new file mode 100644 index 0000000..ca10637 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.2.0", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js new file mode 100644 index 0000000..7571a86 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * 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/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/node.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/node.js new file mode 100644 index 0000000..1d392a8 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/node.js @@ -0,0 +1,209 @@ + +/** + * 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/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json new file mode 100644 index 0000000..6ecc8c9 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json @@ -0,0 +1,73 @@ +{ + "name": "debug", + "version": "2.2.0", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "license": "MIT", + "dependencies": { + "ms": "0.7.1" + }, + "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": "b38458422b5aa8aa6d286b10dfe427e8a67e2b35", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@2.2.0", + "scripts": {}, + "_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "_from": "debug@2.2.0", + "_npmVersion": "2.7.4", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + } + ], + "dist": { + "shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "tarball": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.npmignore b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.travis.yml b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.travis.yml new file mode 100644 index 0000000..895dbd3 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/History.md b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/History.md new file mode 100644 index 0000000..33abe6d --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/History.md @@ -0,0 +1,30 @@ + +0.0.5 / 2013-02-05 +================== + + * optimization: remove use of arguments [jkroso](https://github.com/jkroso) + * add scripts to component.json [jkroso](https://github.com/jkroso) + * tests; remove time for travis + +0.0.4 / 2013-01-07 +================== + + * added component.json #1 [jkroso](https://github.com/jkroso) + * reversed array loop #1 [jkroso](https://github.com/jkroso) + * remove fn params + +0.0.3 / 2012-09-29 +================== + + * faster with negative start args + +0.0.2 / 2012-09-29 +================== + + * support full [].slice semantics + +0.0.1 / 2012-09-29 +=================== + + * initial release + diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/LICENSE b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/LICENSE @@ -0,0 +1,22 @@ +(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/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/Makefile b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/Makefile new file mode 100644 index 0000000..2ad4e47 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/Makefile @@ -0,0 +1,5 @@ + +test: + @./node_modules/.bin/mocha $(T) $(TESTS) + +.PHONY: test diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/README.md b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/README.md new file mode 100644 index 0000000..6605c39 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/README.md @@ -0,0 +1,62 @@ +#sliced +========== + +A faster alternative to `[].slice.call(arguments)`. + +[![Build Status](https://secure.travis-ci.org/aheckmann/sliced.png)](http://travis-ci.org/aheckmann/sliced) + +Example output from [benchmark.js](https://github.com/bestiejs/benchmark.js) + + Array.prototype.slice.call x 1,320,205 ops/sec ±2.35% (92 runs sampled) + [].slice.call x 1,314,605 ops/sec ±1.60% (95 runs sampled) + cached slice.call x 10,468,380 ops/sec ±1.45% (95 runs sampled) + sliced x 16,608,237 ops/sec ±1.40% (92 runs sampled) + fastest is sliced + + Array.prototype.slice.call(arguments, 1) x 1,383,584 ops/sec ±1.73% (97 runs sampled) + [].slice.call(arguments, 1) x 1,494,735 ops/sec ±1.33% (95 runs sampled) + cached slice.call(arguments, 1) x 10,085,270 ops/sec ±1.51% (97 runs sampled) + sliced(arguments, 1) x 16,620,480 ops/sec ±1.29% (95 runs sampled) + fastest is sliced(arguments, 1) + + Array.prototype.slice.call(arguments, -1) x 1,303,262 ops/sec ±1.62% (94 runs sampled) + [].slice.call(arguments, -1) x 1,325,615 ops/sec ±1.36% (97 runs sampled) + cached slice.call(arguments, -1) x 9,673,603 ops/sec ±1.70% (96 runs sampled) + sliced(arguments, -1) x 16,384,575 ops/sec ±1.06% (91 runs sampled) + fastest is sliced(arguments, -1) + + Array.prototype.slice.call(arguments, -2, -10) x 1,404,390 ops/sec ±1.61% (95 runs sampled) + [].slice.call(arguments, -2, -10) x 1,514,367 ops/sec ±1.21% (96 runs sampled) + cached slice.call(arguments, -2, -10) x 9,836,017 ops/sec ±1.21% (95 runs sampled) + sliced(arguments, -2, -10) x 18,544,882 ops/sec ±1.30% (91 runs sampled) + fastest is sliced(arguments, -2, -10) + + Array.prototype.slice.call(arguments, -2, -1) x 1,458,604 ops/sec ±1.41% (97 runs sampled) + [].slice.call(arguments, -2, -1) x 1,536,547 ops/sec ±1.63% (99 runs sampled) + cached slice.call(arguments, -2, -1) x 10,060,633 ops/sec ±1.37% (96 runs sampled) + sliced(arguments, -2, -1) x 18,608,712 ops/sec ±1.08% (93 runs sampled) + fastest is sliced(arguments, -2, -1) + +_Benchmark [source](https://github.com/aheckmann/sliced/blob/master/bench.js)._ + +##Usage + +`sliced` accepts the same arguments as `Array#slice` so you can easily swap it out. + +```js +function zing () { + var slow = [].slice.call(arguments, 1, 8); + var args = slice(arguments, 1, 8); + + var slow = Array.prototype.slice.call(arguments); + var args = slice(arguments); + // etc +} +``` + +## install + + npm install sliced + + +[LICENSE](https://github.com/aheckmann/sliced/blob/master/LICENSE) diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/bench.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/bench.js new file mode 100644 index 0000000..f201d16 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/bench.js @@ -0,0 +1,95 @@ + +var sliced = require('./') +var Bench = require('benchmark'); +var s = new Bench.Suite; +var slice = [].slice; + +s.add('Array.prototype.slice.call', function () { + Array.prototype.slice.call(arguments); +}).add('[].slice.call', function () { + [].slice.call(arguments); +}).add('cached slice.call', function () { + slice.call(arguments) +}).add('sliced', function () { + sliced(arguments) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, 1)', function () { + Array.prototype.slice.call(arguments, 1); +}).add('[].slice.call(arguments, 1)', function () { + [].slice.call(arguments, 1); +}).add('cached slice.call(arguments, 1)', function () { + slice.call(arguments, 1) +}).add('sliced(arguments, 1)', function () { + sliced(arguments, 1) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, -1)', function () { + Array.prototype.slice.call(arguments, -1); +}).add('[].slice.call(arguments, -1)', function () { + [].slice.call(arguments, -1); +}).add('cached slice.call(arguments, -1)', function () { + slice.call(arguments, -1) +}).add('sliced(arguments, -1)', function () { + sliced(arguments, -1) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, -2, -10)', function () { + Array.prototype.slice.call(arguments, -2, -10); +}).add('[].slice.call(arguments, -2, -10)', function () { + [].slice.call(arguments, -2, -10); +}).add('cached slice.call(arguments, -2, -10)', function () { + slice.call(arguments, -2, -10) +}).add('sliced(arguments, -2, -10)', function () { + sliced(arguments, -2, -10) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +var s = new Bench.Suite; +s.add('Array.prototype.slice.call(arguments, -2, -1)', function () { + Array.prototype.slice.call(arguments, -2, -1); +}).add('[].slice.call(arguments, -2, -1)', function () { + [].slice.call(arguments, -2, -1); +}).add('cached slice.call(arguments, -2, -1)', function () { + slice.call(arguments, -2, -1) +}).add('sliced(arguments, -2, -1)', function () { + sliced(arguments, -2, -1) +}).on('cycle', function (evt) { + console.log(String(evt.target)); +}).on('complete', function () { + console.log('fastest is %s', this.filter('fastest').pluck('name')); +}) +.run(); + +/** + * Output: + * + * Array.prototype.slice.call x 1,289,592 ops/sec ±2.88% (87 runs sampled) + * [].slice.call x 1,345,451 ops/sec ±1.68% (97 runs sampled) + * cached slice.call x 10,719,886 ops/sec ±1.04% (99 runs sampled) + * sliced x 15,809,545 ops/sec ±1.46% (93 runs sampled) + * fastest is sliced + * + */ diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/component.json b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/component.json new file mode 100644 index 0000000..57e9e0c --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/component.json @@ -0,0 +1,14 @@ +{ + "name": "sliced", + "version": "0.0.5", + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "repo" : "aheckmann/sliced", + "keywords": [ + "arguments", + "slice", + "array" + ], + "scripts": ["lib/sliced.js", "index.js"], + "author": "Aaron Heckmann ", + "license": "MIT" +} diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/index.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/index.js new file mode 100644 index 0000000..3b90ae7 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/index.js @@ -0,0 +1 @@ +module.exports = exports = require('./lib/sliced'); diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/lib/sliced.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/lib/sliced.js new file mode 100644 index 0000000..d88c85b --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/lib/sliced.js @@ -0,0 +1,33 @@ + +/** + * An Array.prototype.slice.call(arguments) alternative + * + * @param {Object} args something with a length + * @param {Number} slice + * @param {Number} sliceEnd + * @api public + */ + +module.exports = function (args, slice, sliceEnd) { + var ret = []; + var len = args.length; + + if (0 === len) return ret; + + var start = slice < 0 + ? Math.max(0, slice + len) + : slice || 0; + + if (sliceEnd !== undefined) { + len = sliceEnd < 0 + ? sliceEnd + len + : sliceEnd + } + + while (len-- > start) { + ret[len - start] = args[len]; + } + + return ret; +} + diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/package.json b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/package.json new file mode 100644 index 0000000..4db2cd4 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/package.json @@ -0,0 +1,52 @@ +{ + "name": "sliced", + "version": "0.0.5", + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/sliced.git" + }, + "keywords": [ + "arguments", + "slice", + "array" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.5.0", + "benchmark": "~1.0.0" + }, + "_id": "sliced@0.0.5", + "dist": { + "shasum": "5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", + "tarball": "http://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz" + }, + "_npmVersion": "1.1.59", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "directories": {}, + "_shasum": "5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", + "_resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", + "_from": "sliced@0.0.5", + "bugs": { + "url": "https://github.com/aheckmann/sliced/issues" + }, + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/aheckmann/sliced#readme" +} diff --git a/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/test/index.js b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/test/index.js new file mode 100644 index 0000000..33d36a1 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/node_modules/sliced/test/index.js @@ -0,0 +1,80 @@ + +var sliced = require('../') +var assert = require('assert') + +describe('sliced', function(){ + it('exports a function', function(){ + assert.equal('function', typeof sliced); + }) + describe('with 1 arg', function(){ + it('returns an array of the arg', function(){ + var o = [3, "4", {}]; + var r = sliced(o); + assert.equal(3, r.length); + assert.equal(o[0], r[0]); + assert.equal(o[1], r[1]); + assert.equal(o[1], r[1]); + }) + }) + describe('with 2 args', function(){ + it('returns an array of the arg starting at the 2nd arg', function(){ + var o = [3, "4", 5, null]; + var r = sliced(o, 2); + assert.equal(2, r.length); + assert.equal(o[2], r[0]); + assert.equal(o[3], r[1]); + }) + }) + describe('with 3 args', function(){ + it('returns an array of the arg from the 2nd to the 3rd arg', function(){ + var o = [3, "4", 5, null]; + var r = sliced(o, 1, 2); + assert.equal(1, r.length); + assert.equal(o[1], r[0]); + }) + }) + describe('with negative start and no end', function(){ + it('begins at an offset from the end and includes all following elements', function(){ + var o = [3, "4", 5, null]; + var r = sliced(o, -2); + assert.equal(2, r.length); + assert.equal(o[2], r[0]); + assert.equal(o[3], r[1]); + + var r = sliced(o, -12); + assert.equal(4, r.length); + assert.equal(o[0], r[0]); + assert.equal(o[1], r[1]); + }) + }) + describe('with negative start and positive end', function(){ + it('begins at an offset from the end and includes `end` elements', function(){ + var o = [3, "4", {x:1}, null]; + + var r = sliced(o, -2, 1); + assert.equal(0, r.length); + + var r = sliced(o, -2, 2); + assert.equal(0, r.length); + + var r = sliced(o, -2, 3); + assert.equal(1, r.length); + assert.equal(o[2], r[0]); + }) + }) + describe('with negative start and negative end', function(){ + it('begins at `start` offset from the end and includes all elements up to `end` offset from the end', function(){ + var o = [3, "4", {x:1}, null]; + var r = sliced(o, -3, -1); + assert.equal(2, r.length); + assert.equal(o[1], r[0]); + assert.equal(o[2], r[1]); + + var r = sliced(o, -3, -3); + assert.equal(0, r.length); + + var r = sliced(o, -3, -4); + assert.equal(0, r.length); + }) + }) +}) diff --git a/6-2/node_modules/mongoose/node_modules/mquery/package.json b/6-2/node_modules/mongoose/node_modules/mquery/package.json new file mode 100644 index 0000000..e1ce167 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/package.json @@ -0,0 +1,69 @@ +{ + "name": "mquery", + "version": "1.6.3", + "description": "Expressive query building for MongoDB", + "main": "lib/mquery.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mquery.git" + }, + "dependencies": { + "bluebird": "2.9.26", + "debug": "2.2.0", + "regexp-clone": "0.0.1", + "sliced": "0.0.5" + }, + "devDependencies": { + "mongodb": "1.4.38", + "mocha": "1.9.x", + "istanbul": "0.3.2" + }, + "bugs": { + "url": "https://github.com/aheckmann/mquery/issues/new" + }, + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "keywords": [ + "mongodb", + "query", + "builder" + ], + "homepage": "https://github.com/aheckmann/mquery/", + "gitHead": "cd0c3284df2089eed5f0a331802e15c6ff0e7fab", + "_id": "mquery@1.6.3", + "_shasum": "7c02bfb7e49c8012cece1556c5e65fef61f3c8e5", + "_from": "mquery@1.6.3", + "_npmVersion": "2.9.1", + "_nodeVersion": "0.12.3", + "_npmUser": { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + "dist": { + "shasum": "7c02bfb7e49c8012cece1556c5e65fef61f3c8e5", + "tarball": "http://registry.npmjs.org/mquery/-/mquery-1.6.3.tgz" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "ebensing", + "email": "ebensing38@gmail.com" + }, + { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + } + ], + "directories": {}, + "_resolved": "https://registry.npmjs.org/mquery/-/mquery-1.6.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/6-2/node_modules/mongoose/node_modules/mquery/test/collection/browser.js b/6-2/node_modules/mongoose/node_modules/mquery/test/collection/browser.js new file mode 100644 index 0000000..e69de29 diff --git a/6-2/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js b/6-2/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js new file mode 100644 index 0000000..e69de29 diff --git a/6-2/node_modules/mongoose/node_modules/mquery/test/collection/node.js b/6-2/node_modules/mongoose/node_modules/mquery/test/collection/node.js new file mode 100644 index 0000000..43f446e --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/test/collection/node.js @@ -0,0 +1,29 @@ + +var assert = require('assert') +var slice = require('sliced') +var mongo = require('mongodb') +var utils = require('../../').utils; + +var uri = process.env.MQUERY_URI || 'mongodb://localhost/mquery'; +var db; + +exports.getCollection = function (cb) { + mongo.Db.connect(uri, function (err, db_) { + assert.ifError(err); + db = db_; + + var collection = db.collection('stuff'); + collection.opts.safe = true; + + // clean test db before starting + db.dropDatabase(function () { + cb(null, collection); + }); + }) +} + +exports.dropCollection = function (cb) { + db.dropDatabase(function () { + db.close(cb); + }) +} diff --git a/6-2/node_modules/mongoose/node_modules/mquery/test/env.js b/6-2/node_modules/mongoose/node_modules/mquery/test/env.js new file mode 100644 index 0000000..9b9b80b --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/test/env.js @@ -0,0 +1,20 @@ + +var assert = require('assert') +var env = require('../').env; + +console.log('environment: %s', env.type); + +var col; +switch (env.type) { + case 'node': + col = require('./collection/node'); + break; + case 'mongo': + col = require('./collection/mongo'); + case 'browser': + col = require('./collection/browser'); + default: + throw new Error('missing collection implementation for environment: ' + env.type); +} + +module.exports = exports = col; diff --git a/6-2/node_modules/mongoose/node_modules/mquery/test/index.js b/6-2/node_modules/mongoose/node_modules/mquery/test/index.js new file mode 100644 index 0000000..747c947 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/test/index.js @@ -0,0 +1,2875 @@ +var mquery = require('../'); +var assert = require('assert'); + +describe('mquery', function(){ + var col; + + before(function(done){ + // get the env specific collection interface + require('./env').getCollection(function (err, collection) { + assert.ifError(err); + col = collection; + done(); + }); + }) + + after(function(done){ + require('./env').dropCollection(done); + }) + + describe('mquery', function(){ + it('is a function', function(){ + assert.equal('function', typeof mquery); + }) + it('creates instances with the `new` keyword', function(){ + assert.ok(mquery() instanceof mquery); + }) + describe('defaults', function(){ + it('are set', function(){ + var m = mquery(); + assert.strictEqual(undefined, m.op); + assert.deepEqual({}, m.options); + }) + }) + describe('criteria', function(){ + it('if collection-like is used as collection', function(){ + var m = mquery(col); + assert.equal(col, m._collection.collection); + }) + it('non-collection-like is used as criteria', function(){ + var m = mquery({ works: true }); + assert.ok(!m._collection); + assert.deepEqual({ works: true }, m._conditions); + }) + }) + describe('options', function(){ + it('are merged when passed', function(){ + var m = mquery(col, { safe: true }); + assert.deepEqual({ safe: true }, m.options); + var m = mquery({ name: 'mquery' }, { safe: true }); + assert.deepEqual({ safe: true }, m.options); + }) + }) + }) + + describe('toConstructor', function(){ + it('creates subclasses of mquery', function(){ + var opts = { safe: { w: 'majority' }, readPreference: 'p' }; + var match = { name: 'test', count: { $gt: 101 }}; + var select = { name: 1, count: 0 } + var update = { $set: { x: true }}; + var path = 'street'; + + var q = mquery().setOptions(opts); + q.where(match); + q.select(select); + q.update(update); + q.where(path); + q.find(); + + var M = q.toConstructor(); + var m = M(); + + assert.ok(m instanceof mquery); + assert.deepEqual(opts, m.options); + assert.deepEqual(match, m._conditions); + assert.deepEqual(select, m._fields); + assert.deepEqual(update, m._update); + assert.equal(path, m._path); + assert.equal('find', m.op); + }) + }) + + describe('setOptions', function(){ + it('calls associated methods', function(){ + var m = mquery(); + assert.equal(m._collection, null); + m.setOptions({ collection: col }); + assert.equal(m._collection.collection, col); + }) + it('directly sets option when no method exists', function(){ + var m = mquery(); + assert.equal(m.options.woot, null); + m.setOptions({ woot: 'yay' }); + assert.equal(m.options.woot, 'yay'); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.setOptions(); + assert.equal(m, n); + var n = m.setOptions({ x: 1 }); + assert.equal(m, n); + }) + }) + + describe('collection', function(){ + it('sets the _collection', function(){ + var m = mquery(); + m.collection(col); + assert.equal(m._collection.collection, col); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.collection(col); + assert.equal(m, n); + }) + }) + + describe('$where', function(){ + it('sets the $where condition', function(){ + var m = mquery(); + function go () {} + m.$where(go); + assert.ok(go === m._conditions.$where); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.$where('x'); + assert.equal(m, n); + }) + }) + + describe('where', function(){ + it('without arguments', function(){ + var m = mquery(); + m.where(); + assert.deepEqual({}, m._conditions); + }) + it('with non-string/object argument', function(){ + var m = mquery(); + + assert.throws(function(){ + m.where([]); + }, /path must be a string or object/); + }) + describe('with one argument', function(){ + it('that is an object', function(){ + var m = mquery(); + m.where({ name: 'flawed' }); + assert.strictEqual(m._conditions.name, 'flawed'); + }) + it('that is a query', function(){ + var m = mquery({ name: 'first' }); + var n = mquery({ name: 'changed' }); + m.where(n); + assert.strictEqual(m._conditions.name, 'changed'); + }) + it('that is a string', function(){ + var m = mquery(); + m.where('name'); + assert.equal('name', m._path); + assert.strictEqual(m._conditions.name, undefined); + }) + }) + it('with two arguments', function(){ + var m = mquery(); + m.where('name', 'The Great Pumpkin'); + assert.equal('name', m._path); + assert.strictEqual(m._conditions.name, 'The Great Pumpkin'); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.where('x', 'y'); + assert.equal(m, n); + var n = m.where() + assert.equal(m, n); + }) + }) + + describe('equals', function(){ + it('must be called after where()', function(){ + var m = mquery(); + assert.throws(function () { + m.equals(); + }, /must be used after where/) + }) + it('sets value of path set with where()', function(){ + var m = mquery(); + m.where('age').equals(1000); + assert.deepEqual({ age: 1000 }, m._conditions); + }) + it('is chainable', function(){ + var m = mquery(); + var n = m.where('x').equals(3); + assert.equal(m, n); + }) + }) + + describe('or', function(){ + it('pushes onto the internal $or condition', function(){ + var m = mquery(); + m.or({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$or) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.or(arg); + assert.deepEqual(arg, m._conditions.$or) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.or(arg); + m.or({ y: 1 }) + m.or([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$or) + }) + it('is chainable', function(){ + var m = mquery(); + m.or({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $or: [{ o: 'k' }] }, m._conditions) + }) + }) + + describe('nor', function(){ + it('pushes onto the internal $nor condition', function(){ + var m = mquery(); + m.nor({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$nor) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.nor(arg); + assert.deepEqual(arg, m._conditions.$nor) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.nor(arg); + m.nor({ y: 1 }) + m.nor([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$nor) + }) + it('is chainable', function(){ + var m = mquery(); + m.nor({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $nor: [{ o: 'k' }] }, m._conditions) + }) + }) + + describe('and', function(){ + it('pushes onto the internal $and condition', function(){ + var m = mquery(); + m.and({ 'Nightmare Before Christmas': true }); + assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$and) + }) + it('allows passing arrays', function(){ + var m = mquery(); + var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; + m.and(arg); + assert.deepEqual(arg, m._conditions.$and) + }) + it('allows calling multiple times', function(){ + var m = mquery(); + var arg = [{ looper: true }, { x: 1 }]; + m.and(arg); + m.and({ y: 1 }) + m.and([{ w: 'oo' }, { z: 'oo'} ]) + assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$and) + }) + it('is chainable', function(){ + var m = mquery(); + m.and({ o: "k"}).where('name', 'table'); + assert.deepEqual({ name: 'table', $and: [{ o: 'k' }] }, m._conditions) + }) + }) + + function generalCondition (type) { + return function () { + it('accepts 2 args', function(){ + var m = mquery()[type]('count', 3); + var check = {}; + check['$' + type] = 3; + assert.deepEqual(m._conditions.count, check); + }) + it('uses previously set `where` path if 1 arg passed', function(){ + var m = mquery().where('count')[type](3); + var check = {}; + check['$' + type] = 3; + assert.deepEqual(m._conditions.count, check); + }) + it('throws if 1 arg was passed but no previous `where` was used', function(){ + assert.throws(function(){ + mquery()[type](3); + }, /must be used after where/); + }) + it('is chainable', function(){ + var m = mquery().where('count')[type](3).where('x', 8); + var check = {x: 8, count: {}}; + check.count['$' + type] = 3; + assert.deepEqual(m._conditions, check); + }) + it('overwrites previous value', function(){ + var m = mquery().where('count')[type](3)[type](8); + var check = {}; + check['$' + type] = 8; + assert.deepEqual(m._conditions.count, check); + }) + } + } + + 'gt gte lt lte ne in nin regex size maxDistance'.split(' ').forEach(function (type) { + describe(type, generalCondition(type)) + }) + + describe('mod', function () { + describe('with 1 argument', function(){ + it('requires a previous where()', function(){ + assert.throws(function () { + mquery().mod([30, 10]) + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('madmen').mod([10,20]); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + }) + + describe('with 2 arguments and second is non-Array', function(){ + it('requires a previous where()', function(){ + assert.throws(function () { + mquery().mod('x', 10) + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('madmen').mod(10, 20); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + }) + + it('with 2 arguments and second is an array', function(){ + var m = mquery().mod('madmen', [10,20]); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + + it('with 3 arguments', function(){ + var m = mquery().mod('madmen', 10, 20); + assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) + }) + + it('is chainable', function(){ + var m = mquery().mod('madmen', 10, 20).where('x', 8); + var check = { madmen: { $mod: [10,20] }, x: 8}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('exists', function(){ + it('with 0 args', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().exists() + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('name').exists(); + var check = { name: { $exists: true }}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('with 1 arg', function(){ + describe('that is boolean', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().exists() + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().exists('name', false); + var check = { name: { $exists: false }}; + assert.deepEqual(m._conditions, check); + }) + }) + describe('that is not boolean', function(){ + it('sets the value to `true`', function(){ + var m = mquery().where('name').exists('yummy'); + var check = { yummy: { $exists: true }}; + assert.deepEqual(m._conditions, check); + }) + }) + }) + + describe('with 2 args', function(){ + it('works', function(){ + var m = mquery().exists('yummy', false); + var check = { yummy: { $exists: false }}; + assert.deepEqual(m._conditions, check); + }) + }) + + it('is chainable', function(){ + var m = mquery().where('name').exists().find({ x: 1 }); + var check = { name: { $exists: true }, x: 1}; + assert.deepEqual(m._conditions, check); + }) + }) + + describe('elemMatch', function(){ + describe('with null/undefined first argument', function(){ + assert.throws(function () { + mquery().elemMatch(); + }, /Invalid argument/); + assert.throws(function () { + mquery().elemMatch(null); + }, /Invalid argument/); + assert.doesNotThrow(function () { + mquery().elemMatch('', {}); + }); + }) + + describe('with 1 argument', function(){ + it('throws if not a function or object', function(){ + assert.throws(function () { + mquery().elemMatch([]); + }, /Invalid argument/); + }) + + describe('that is an object', function(){ + it('throws if no previous `where` was used', function(){ + assert.throws(function () { + mquery().elemMatch({}); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('comment').elemMatch({ author: 'joe', votes: {$gte: 3 }}); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + describe('that is a function', function(){ + it('throws if no previous `where` was used', function(){ + assert.throws(function () { + mquery().elemMatch(function(){}); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('comment').elemMatch(function (query) { + query.where({ author: 'joe', votes: {$gte: 3 }}) + }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + }) + + describe('with 2 arguments', function(){ + describe('and the 2nd is an object', function(){ + it('works', function(){ + var m = mquery().elemMatch('comment', { author: 'joe', votes: {$gte: 3 }}); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + describe('and the 2nd is a function', function(){ + it('works', function(){ + var m = mquery().elemMatch('comment', function (query) { + query.where({ author: 'joe', votes: {$gte: 3 }}) + }); + assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); + }) + }) + it('and the 2nd is not a function or object', function(){ + assert.throws(function () { + mquery().elemMatch('comment', []); + }, /Invalid argument/); + }) + }) + }) + + describe('within', function(){ + it('is chainable', function(){ + var m = mquery(); + assert.equal(m.where('a').within(), m); + }) + describe('when called with arguments', function(){ + it('must follow where()', function(){ + assert.throws(function () { + mquery().within([]); + }, /must be used after where/); + }) + + describe('of length 1', function(){ + it('throws if not a recognized shape', function(){ + assert.throws(function () { + mquery().where('loc').within({}); + }, /Invalid argument/) + assert.throws(function () { + mquery().where('loc').within(null); + }, /Invalid argument/) + }) + it('delegates to circle when center exists', function(){ + var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); + assert.deepEqual({ $geoWithin: {$center:[[10,10], 3]}}, m._conditions.loc); + }) + it('delegates to box when exists', function(){ + var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); + assert.deepEqual({ $geoWithin: {$box:[[10,10], [11,14]]}}, m._conditions.loc); + }) + it('delegates to polygon when exists', function(){ + var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $geoWithin: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); + }) + it('delegates to geometry when exists', function(){ + var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $geoWithin: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); + }) + }) + + describe('of length 2', function(){ + it('delegates to box()', function(){ + var m = mquery().where('loc').within([1,2],[2,5]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[2,5]]}}); + }) + }) + + describe('of length > 2', function(){ + it('delegates to polygon()', function(){ + var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); + }) + }) + }) + }) + + describe('geoWithin', function(){ + before(function(){ + mquery.use$geoWithin = false; + }) + after(function(){ + mquery.use$geoWithin = true; + }) + describe('when called with arguments', function(){ + describe('of length 1', function(){ + it('delegates to circle when center exists', function(){ + var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); + assert.deepEqual({ $within: {$center:[[10,10], 3]}}, m._conditions.loc); + }) + it('delegates to box when exists', function(){ + var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); + assert.deepEqual({ $within: {$box:[[10,10], [11,14]]}}, m._conditions.loc); + }) + it('delegates to polygon when exists', function(){ + var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $within: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); + }) + it('delegates to geometry when exists', function(){ + var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); + assert.deepEqual({ $within: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); + }) + }) + + describe('of length 2', function(){ + it('delegates to box()', function(){ + var m = mquery().where('loc').within([1,2],[2,5]); + assert.deepEqual(m._conditions.loc, { $within: { $box: [[1,2],[2,5]]}}); + }) + }) + + describe('of length > 2', function(){ + it('delegates to polygon()', function(){ + var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); + assert.deepEqual(m._conditions.loc, { $within: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); + }) + }) + }) + }) + + describe('box', function(){ + describe('with 1 argument', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().box('sometihng'); + }, /Invalid argument/); + }) + }) + describe('with > 3 arguments', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().box(1,2,3,4); + }, /Invalid argument/); + }) + }) + + describe('with 2 arguments', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().box([],[]); + }, /must be used after where/); + }) + it('works', function(){ + var m = mquery().where('loc').box([1,2],[3,4]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); + }) + }) + + describe('with 3 arguments', function(){ + it('works', function(){ + var m = mquery().box('loc', [1,2],[3,4]); + assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); + }) + }) + }) + + describe('polygon', function(){ + describe('when first argument is not a string', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().polygon({}); + }, /must be used after where/); + + assert.doesNotThrow(function () { + mquery().where('loc').polygon([1,2], [2,3], [3,6]); + }); + }) + + it('assigns arguments to within polygon condition', function(){ + var m = mquery().where('loc').polygon([1,2], [2,3], [3,6]); + assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); + }) + }) + + describe('when first arg is a string', function(){ + it('assigns remaining arguments to within polygon condition', function(){ + var m = mquery().polygon('loc', [1,2], [2,3], [3,6]); + assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); + }) + }) + }) + + describe('circle', function(){ + describe('with one arg', function(){ + it('must follow where()', function(){ + assert.throws(function () { + mquery().circle('x'); + }, /must be used after where/); + assert.doesNotThrow(function () { + mquery().where('loc').circle({center:[0,0], radius: 3 }); + }); + }) + it('works', function(){ + var m = mquery().where('loc').circle({center:[0,0], radius: 3 }); + assert.deepEqual(m._conditions, { loc: { $geoWithin: {$center: [[0,0],3] }}}); + }) + }) + describe('with 3 args', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().where('loc').circle(1,2,3); + }, /Invalid argument/); + }) + }) + describe('requires radius and center', function(){ + assert.throws(function () { + mquery().circle('loc', { center: 1 }); + }, /center and radius are required/); + assert.throws(function () { + mquery().circle('loc', { radius: 1 }); + }, /center and radius are required/); + assert.doesNotThrow(function () { + mquery().circle('loc', { center: [1,2], radius: 1 }); + }); + }) + }) + + describe('geometry', function(){ + // within + intersects + var point = { type: 'Point', coordinates: [[0,0],[1,1]] }; + + it('must be called after within or intersects', function(done){ + assert.throws(function () { + mquery().where('a').geometry(point); + }, /must come after/); + + assert.doesNotThrow(function () { + mquery().where('a').within().geometry(point); + }); + + assert.doesNotThrow(function () { + mquery().where('a').intersects().geometry(point); + }); + + done(); + }) + + describe('when called with one argument', function(){ + describe('after within()', function(){ + it('and arg quacks like geoJSON', function(done){ + var m = mquery().where('a').within().geometry(point); + assert.deepEqual({ a: { $geoWithin: { $geometry: point }}}, m._conditions); + done(); + }) + }) + + describe('after intersects()', function(){ + it('and arg quacks like geoJSON', function(done){ + var m = mquery().where('a').intersects().geometry(point); + assert.deepEqual({ a: { $geoIntersects: { $geometry: point }}}, m._conditions); + done(); + }) + }) + + it('and arg does not quack like geoJSON', function(done){ + assert.throws(function () { + mquery().where('b').within().geometry({type:1, coordinates:2}); + }, /Invalid argument/); + done(); + }) + }) + + describe('when called with zero arguments', function(){ + it('throws', function(done){ + assert.throws(function () { + mquery().where('a').within().geometry(); + }, /Invalid argument/); + + done(); + }) + }) + + describe('when called with more than one arguments', function(){ + it('throws', function(done){ + assert.throws(function () { + mquery().where('a').within().geometry({type:'a',coordinates:[]}, 2); + }, /Invalid argument/); + done(); + }) + }) + }) + + describe('intersects', function(){ + it('must be used after where()', function(done){ + var m = mquery(); + assert.throws(function () { + m.intersects(); + }, /must be used after where/) + done(); + }) + + it('sets geo comparison to "$intersects"', function(done){ + var n = mquery().where('a').intersects(); + assert.equal('$geoIntersects', n._geoComparison); + done(); + }) + + it('is chainable', function(){ + var m = mquery(); + assert.equal(m.where('a').intersects(), m); + }) + + it('calls geometry if argument quacks like geojson', function(done){ + var m = mquery(); + var o = { type: 'LineString', coordinates: [[0,1],[3,40]] }; + var ran = false; + + m.geometry = function (arg) { + ran = true; + assert.deepEqual(o, arg); + } + + m.where('a').intersects(o); + assert.ok(ran); + + done(); + }) + + it('throws if argument is not geometry-like', function(done){ + var m = mquery().where('a'); + + assert.throws(function () { + m.intersects(null); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(undefined); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(false); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects({}); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects([]); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(function(){}); + }, /Invalid argument/); + + assert.throws(function () { + m.intersects(NaN); + }, /Invalid argument/); + + done(); + }) + }) + + describe('near', function(){ + // near nearSphere + describe('with 0 args', function(){ + it('is compatible with geometry()', function(done){ + var q = mquery().where('x').near().geometry({ type: 'Point', coordinates: [180, 11] }); + assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [180,11]}}}, q._conditions.x); + done(); + }) + }) + + describe('with 1 arg', function(){ + it('throws if not used after where()', function(){ + assert.throws(function () { + mquery().near(1); + }, /must be used after where/) + }) + it('does not throw if used after where()', function(){ + assert.doesNotThrow(function () { + mquery().where('loc').near({center:[1,1]}); + }) + }) + }) + describe('with > 2 args', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().near(1,2,3); + }, /Invalid argument/) + }) + }) + + it('creates $geometry args for GeoJSON', function(){ + var m = mquery().where('loc').near({ center: { type: 'Point', coordinates: [10,10] }}); + assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [10,10]}}}, m._conditions.loc); + }) + + it('expects `center`', function(){ + assert.throws(function () { + mquery().near('loc', { maxDistance: 3 }); + }, /center is required/) + assert.doesNotThrow(function () { + mquery().near('loc', { center: [3,4] }); + }) + }) + + it('accepts spherical conditions', function(){ + var m = mquery().where('loc').near({ center: [1,2], spherical: true }); + assert.deepEqual(m._conditions, { loc: { $nearSphere: [1,2]}}); + }) + + it('is non-spherical by default', function(){ + var m = mquery().where('loc').near({ center: [1,2] }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2]}}); + }) + + it('supports maxDistance', function(){ + var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}}); + }) + + it('is chainable', function(){ + var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }).find({ x: 1 }); + assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}, x: 1}); + }) + + describe('supports passing GeoJSON, gh-13', function(){ + it('with center', function(){ + var m = mquery().where('loc').near({ + center: { type: 'Point', coordinates: [1,1] } + , maxDistance: 2 + }); + + var expect = { + loc: { + $near: { + $geometry: { + type: 'Point' + , coordinates : [1,1] + } + , $maxDistance : 2 + } + } + } + + assert.deepEqual(m._conditions, expect); + }) + }) + }) + + // fields + + describe('select', function(){ + describe('with 0 args', function(){ + it('is chainable', function(){ + var m = mquery() + assert.equal(m, m.select()); + }) + }) + + it('accepts an object', function(){ + var o = { x: 1, y: 1 } + var m = mquery().select(o); + assert.deepEqual(m._fields, o); + }) + + it('accepts a string', function(){ + var o = 'x -y'; + var m = mquery().select(o); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + }) + + it('does not accept an array', function(done){ + assert.throws(function () { + var o = ['x', '-y']; + var m = mquery().select(o); + }, /Invalid select/); + done(); + }) + + it('merges previous arguments', function(){ + var o = { x: 1, y: 0, a: 1 } + var m = mquery().select(o); + m.select('z -u w').select({ x: 0 }) + assert.deepEqual(m._fields, { + x: 0 + , y: 0 + , z: 1 + , u: 0 + , w: 1 + , a: 1 + }); + }) + + it('rejects non-string, object, arrays', function(){ + assert.throws(function () { + mquery().select(function(){}); + }, /Invalid select\(\) argument/); + }) + + it('accepts aguments objects', function(){ + var m = mquery(); + function t () { + m.select(arguments); + assert.deepEqual(m._fields, { x: 1, y: 0 }); + } + t('x', '-y'); + }) + + noDistinct('select'); + no('count', 'select'); + }) + + describe('selected', function() { + it('returns true when fields have been selected', function(done) { + var m = mquery().select({ name: 1 }); + assert.ok(m.selected()); + + var m = mquery().select('name'); + assert.ok(m.selected()); + + done(); + }); + + it('returns false when no fields have been selected', function(done) { + var m = mquery(); + assert.strictEqual(false, m.selected()); + done(); + }); + }); + + describe('selectedInclusively', function() { + describe('returns false', function(){ + it('when no fields have been selected', function(done) { + assert.strictEqual(false, mquery().selectedInclusively()); + assert.equal(false, mquery().select({}).selectedInclusively()); + done(); + }); + it('when any fields have been excluded', function(done) { + assert.strictEqual(false, mquery().select('-name').selectedInclusively()); + assert.strictEqual(false, mquery().select({ name: 0 }).selectedInclusively()); + assert.strictEqual(false, mquery().select('name bio -_id').selectedInclusively()); + assert.strictEqual(false, mquery().select({ name: 1, _id: 0 }).selectedInclusively()); + done(); + }); + it('when using $meta', function(done) { + assert.strictEqual(false, mquery().select({ name: { $meta: 'textScore' } }).selectedInclusively()); + done(); + }); + }); + + describe('returns true', function() { + it('when fields have been included', function(done) { + assert.equal(true, mquery().select('name').selectedInclusively()); + assert.equal(true, mquery().select({ name:1 }).selectedInclusively()); + done(); + }); + }); + }); + + describe('selectedExclusively', function() { + describe('returns false', function(){ + it('when no fields have been selected', function(done) { + assert.equal(false, mquery().selectedExclusively()); + assert.equal(false, mquery().select({}).selectedExclusively()); + done(); + }); + it('when fields have only been included', function(done) { + assert.equal(false, mquery().select('name').selectedExclusively()); + assert.equal(false, mquery().select({ name: 1 }).selectedExclusively()); + done(); + }); + }); + + describe('returns true', function() { + it('when any field has been excluded', function(done) { + assert.equal(true, mquery().select('-name').selectedExclusively()); + assert.equal(true, mquery().select({ name:0 }).selectedExclusively()); + assert.equal(true, mquery().select('-_id').selectedExclusively()); + assert.strictEqual(true, mquery().select('name bio -_id').selectedExclusively()); + assert.strictEqual(true, mquery().select({ name: 1, _id: 0 }).selectedExclusively()); + done(); + }); + }); + }); + + describe('slice', function(){ + describe('with 0 args', function(){ + it('is chainable', function(){ + var m = mquery() + assert.equal(m, m.slice()); + }) + it('is a noop', function(){ + var m = mquery().slice(); + assert.deepEqual(m._fields, undefined); + }) + }) + + describe('with 1 arg', function(){ + it('throws if not called after where()', function(){ + assert.throws(function () { + mquery().slice(1); + }, /must be used after where/); + assert.doesNotThrow(function () { + mquery().where('a').slice(1); + }); + }) + it('that is a number', function(){ + var query = mquery(); + query.where('collection').slice(5); + assert.deepEqual(query._fields, {collection: {$slice: 5}}); + }) + it('that is an array', function(){ + var query = mquery(); + query.where('collection').slice([5,10]); + assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); + }) + it('that is an object', function() { + var query = mquery(); + query.slice({ collection: [5, 10] }); + assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); + }) + }) + + describe('with 2 args', function(){ + describe('and first is a number', function(){ + it('throws if not called after where', function(){ + assert.throws(function () { + mquery().slice(2,3); + }, /must be used after where/); + }) + it('does not throw if used after where', function(){ + var query = mquery(); + query.where('collection').slice(2,3); + assert.deepEqual(query._fields, {collection: {$slice: [2,3]}}); + }) + }) + it('and first is not a number', function(){ + var query = mquery().slice('collection', [-5, 2]); + assert.deepEqual(query._fields, {collection: {$slice: [-5,2]}}); + }) + }) + + describe('with 3 args', function(){ + it('works', function(){ + var query = mquery(); + query.slice('collection', 14, 10); + assert.deepEqual(query._fields, {collection: {$slice: [14, 10]}}); + }) + }) + + noDistinct('slice'); + no('count', 'slice'); + }) + + // options + + describe('sort', function(){ + describe('with 0 args', function(){ + it('chains', function(){ + var m = mquery(); + assert.equal(m, m.sort()); + }) + it('has no affect', function(){ + var m = mquery(); + assert.equal(m.options.sort, undefined); + }) + }) + + it('works', function(){ + var query = mquery(); + query.sort('a -c b'); + assert.deepEqual(query.options.sort, { a : 1, b: 1, c : -1}); + + query = mquery(); + query.sort({'a': 1, 'c': -1, 'b': 'asc', e: 'descending', f: 'ascending'}); + assert.deepEqual(query.options.sort, {'a': 1, 'c': -1, 'b': 1, 'e': -1, 'f': 1}); + + query = mquery(); + var e= undefined; + try { + query.sort(['a', 1]); + } catch (err) { + e= err; + } + assert.ok(e, 'uh oh. no error was thrown'); + assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); + + e= undefined; + try { + query.sort('a', 1, 'c', -1, 'b', 1); + } catch (err) { + e= err; + } + assert.ok(e, 'uh oh. no error was thrown'); + assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); + }) + + it('handles $meta sort options', function(){ + var query = mquery(); + query.sort({ score: { $meta : "textScore" } }); + assert.deepEqual(query.options.sort, { score : { $meta : "textScore" } }); + }) + + no('count', 'sort'); + }) + + function simpleOption (type, options) { + describe(type, function(){ + it('sets the ' + type + ' option', function(){ + var m = mquery()[type](2); + var optionName = options.name || type; + assert.equal(2, m.options[optionName]); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m[type](3), m); + }) + + if (!options.distinct) noDistinct(type); + if (!options.count) no('count', type); + }) + } + + var negated = { + limit: {distinct: false, count: true} + , skip: {distinct: false, count: true} + , maxScan: {distinct: false, count: false} + , batchSize: {distinct: false, count: false} + , maxTime: {distinct: true, count: true, name: 'maxTimeMS' } + , comment: {distinct: false, count: false} + }; + Object.keys(negated).forEach(function (key) { + simpleOption(key, negated[key]); + }) + + describe('snapshot', function(){ + it('works', function(){ + var query = mquery(); + query.snapshot(); + assert.equal(true, query.options.snapshot); + + var query = mquery() + query.snapshot(true); + assert.equal(true, query.options.snapshot); + + var query = mquery() + query.snapshot(false); + assert.equal(false, query.options.snapshot); + }) + noDistinct('snapshot'); + no('count', 'snapshot'); + }) + + describe('hint', function(){ + it('accepts an object', function(){ + var query2 = mquery(); + query2.hint({'a': 1, 'b': -1}); + assert.deepEqual(query2.options.hint, {'a': 1, 'b': -1}); + }) + + it('rejects everything else', function(){ + assert.throws(function(){ + mquery().hint('c'); + }, /Invalid hint./); + assert.throws(function(){ + mquery().hint(['c']); + }, /Invalid hint./); + assert.throws(function(){ + mquery().hint(1); + }, /Invalid hint./); + }) + + describe('does not have side affects', function(){ + it('on invalid arg', function(){ + var m = mquery(); + try { + m.hint(1); + } catch (err) { + // ignore + } + assert.equal(undefined, m.options.hint); + }) + it('on missing arg', function(){ + var m = mquery().hint(); + assert.equal(undefined, m.options.hint); + }) + }) + + noDistinct('hint'); + }) + + describe('slaveOk', function(){ + it('works', function(){ + var query = mquery(); + query.slaveOk(); + assert.equal(true, query.options.slaveOk); + + var query = mquery() + query.slaveOk(true); + assert.equal(true, query.options.slaveOk); + + var query = mquery() + query.slaveOk(false); + assert.equal(false, query.options.slaveOk); + }) + }) + + describe('read', function(){ + it('sets associated readPreference option', function(){ + var m = mquery(); + m.read('p'); + assert.equal('primary', m.options.readPreference); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m, m.read('sp')); + }) + }) + + describe('tailable', function(){ + it('works', function(){ + var query = mquery(); + query.tailable(); + assert.equal(true, query.options.tailable); + + var query = mquery() + query.tailable(true); + assert.equal(true, query.options.tailable); + + var query = mquery() + query.tailable(false); + assert.equal(false, query.options.tailable); + }) + it('is chainable', function(){ + var m = mquery(); + assert.equal(m, m.tailable()); + }) + noDistinct('tailable'); + no('count', 'tailable'); + }) + + // query utilities + + describe('merge', function(){ + describe('with falsy arg', function(){ + it('returns itself', function(){ + var m = mquery(); + assert.equal(m, m.merge()); + assert.equal(m, m.merge(null)); + assert.equal(m, m.merge(0)); + }) + }) + describe('with an argument', function(){ + describe('that is not a query or plain object', function(){ + it('throws', function(){ + assert.throws(function () { + mquery().merge([]); + }, /Invalid argument/); + assert.throws(function () { + mquery().merge('merge'); + }, /Invalid argument/); + assert.doesNotThrow(function () { + mquery().merge({}); + }, /Invalid argument/); + }) + }) + + describe('that is a query', function(){ + it('merges conditions, field selection, and options', function(){ + var m = mquery({ x: 'hi' }, { select: 'x y', another: true }) + var n = mquery().merge(m); + assert.deepEqual(n._conditions, m._conditions); + assert.deepEqual(n._fields, m._fields); + assert.deepEqual(n.options, m.options); + }) + it('clones update arguments', function(done){ + var original = { $set: { iTerm: true }} + var m = mquery().update(original); + var n = mquery().merge(m); + m.update({ $set: { x: 2 }}) + assert.notDeepEqual(m._update, n._update); + done(); + }) + it('is chainable', function(){ + var m = mquery({ x: 'hi' }); + var n = mquery(); + assert.equal(n, n.merge(m)); + }) + }) + + describe('that is an object', function(){ + it('merges', function(){ + var m = { x: 'hi' }; + var n = mquery().merge(m); + assert.deepEqual(n._conditions, { x: 'hi' }); + }) + it('clones update arguments', function(done){ + var original = { $set: { iTerm: true }} + var m = mquery().update(original); + var n = mquery().merge(original); + m.update({ $set: { x: 2 }}) + assert.notDeepEqual(m._update, n._update); + done(); + }) + it('is chainable', function(){ + var m = { x: 'hi' }; + var n = mquery(); + assert.equal(n, n.merge(m)); + }) + }) + }) + }) + + // queries + + describe('find', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.find() + }) + assert.doesNotThrow(function () { + m.find({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery().find({ x: 1 }).find().find({ y: 2 }); + assert.deepEqual(m._conditions, {x:1,y:2}); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.tailable(); + m.select('_id'); + var a = mquery().find(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).find({ name: 'mquery' }, function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery({ name: 'mquery' }); + mquery(col).find(m, function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery' }).collection(col).find(function (err, docs) { + assert.ifError(err); + assert.equal(1, docs.length); + done(); + }); + }) + }) + }) + + describe('findOne', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.findOne() + }) + assert.doesNotThrow(function () { + m.findOne({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery(); + var n = m.findOne({ x: 1 }).findOne().findOne({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(m._conditions, {x:1,y:2}); + assert.equal('findOne', m.op); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.read('nearest'); + m.select('_id'); + var a = mquery().findOne(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery findone' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery findone' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).findOne({ name: 'mquery findone' }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery(col).where({ name: 'mquery findone' }); + mquery(col).findOne(m, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery findone' }).collection(col).findOne(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('mquery findone', doc.name); + done(); + }); + }) + }) + }) + + describe('count', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.count() + }) + assert.doesNotThrow(function () { + m.count({ x: 1 }) + }) + }) + }) + + it('is chainable', function(){ + var m = mquery(); + var n = m.count({ x: 1 }).count().count({ y: 2 }); + assert.equal(m, n); + assert.deepEqual(m._conditions, {x:1,y:2}); + assert.equal('count', m.op); + }) + + it('merges other queries', function(){ + var m = mquery({ name: 'mquery' }); + m.read('nearest'); + m.select('_id'); + var a = mquery().count(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery count' }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery count' }, done); + }) + + it('when criteria is passed with a callback', function(done){ + mquery(col).count({ name: 'mquery count' }, function (err, count) { + assert.ifError(err); + assert.ok(count); + assert.ok(1 === count); + done(); + }) + }) + it('when Query is passed with a callback', function(done){ + var m = mquery({ name: 'mquery count' }); + mquery(col).count(m, function (err, count) { + assert.ifError(err); + assert.ok(count); + assert.ok(1 === count); + done(); + }) + }) + it('when just a callback is passed', function(done){ + mquery({ name: 'mquery count' }).collection(col).count(function (err, count) { + assert.ifError(err); + assert.ok(1 === count); + done(); + }); + }) + }) + + describe('validates its option', function(){ + it('sort', function(done){ + assert.throws(function(){ + var m = mquery().sort('x').count(); + }, /sort cannot be used with count/); + done(); + }) + + it('select', function(done){ + assert.throws(function(){ + var m = mquery().select('x').count(); + }, /field selection and slice cannot be used with count/); + done(); + }) + + it('slice', function(done){ + assert.throws(function(){ + var m = mquery().where('x').slice(-3).count(); + }, /field selection and slice cannot be used with count/); + done(); + }) + + it('limit', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().limit(3).count(); + }) + done(); + }) + + it('skip', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().skip(3).count(); + }) + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 }).count(); + }, /batchSize cannot be used with count/); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery').count(); + }, /comment cannot be used with count/); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300).count(); + }, /maxScan cannot be used with count/); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot().count(); + }, /snapshot cannot be used with count/); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable().count(); + }, /tailable cannot be used with count/); + done(); + }) + }) + }) + + describe('distinct', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.distinct() + }) + assert.doesNotThrow(function () { + m.distinct('name') + }) + assert.doesNotThrow(function () { + m.distinct({ name: 'mquery distinct' }) + }) + assert.doesNotThrow(function () { + m.distinct({ name: 'mquery distinct' }, 'name') + }) + }) + }) + + it('is chainable', function(){ + var m = mquery({x:1}).distinct('name'); + var n = m.distinct({y:2}); + assert.equal(m, n); + assert.deepEqual(n._conditions, {x:1, y:2}); + assert.equal('name', n._distinct); + assert.equal('distinct', n.op); + }); + + it('overwrites field', function(){ + var m = mquery({ name: 'mquery' }).distinct('name'); + m.distinct('rename'); + assert.equal(m._distinct, 'rename'); + m.distinct({x:1}, 'renamed'); + assert.equal(m._distinct, 'renamed'); + }) + + it('merges other queries', function(){ + var m = mquery().distinct({ name: 'mquery' }, 'age') + m.read('nearest'); + var a = mquery().distinct(m); + assert.deepEqual(a._conditions, m._conditions); + assert.deepEqual(a.options, m.options); + assert.deepEqual(a._fields, m._fields); + assert.deepEqual(a._distinct, m._distinct); + }) + + describe('executes', function(){ + before(function (done) { + col.insert({ name: 'mquery distinct', age: 1 }, { safe: true }, done); + }); + + after(function(done){ + col.remove({ name: 'mquery distinct' }, done); + }) + + it('when distinct arg is passed with a callback', function(done){ + mquery(col).distinct('distinct', function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + describe('when criteria is passed with a callback', function(){ + it('if distinct arg was declared', function(done){ + mquery(col).distinct('age').distinct({ name: 'mquery distinct' }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + it('but not if distinct arg was not declared', function(){ + assert.throws(function(){ + mquery(col).distinct({ name: 'mquery distinct' }, function(){}) + }, /No value for `distinct`/) + }) + }) + describe('when Query is passed with a callback', function(){ + var m = mquery({ name: 'mquery distinct' }); + it('if distinct arg was declared', function(done){ + mquery(col).distinct('age').distinct(m, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }) + }) + it('but not if distinct arg was not declared', function(){ + assert.throws(function(){ + mquery(col).distinct(m, function(){}) + }, /No value for `distinct`/) + }) + }) + describe('when just a callback is passed', function(done){ + it('if distinct arg was declared', function(done){ + var m = mquery({ name: 'mquery distinct' }); + m.collection(col); + m.distinct('age'); + m.distinct(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + done(); + }); + }) + it('but not if no distinct arg was declared', function(){ + var m = mquery(); + m.collection(col); + assert.throws(function () { + m.distinct(function(){}); + }, /No value for `distinct`/); + }) + }) + }) + + describe('validates its option', function(){ + it('sort', function(done){ + assert.throws(function(){ + var m = mquery().sort('x').distinct(); + }, /sort cannot be used with distinct/); + done(); + }) + + it('select', function(done){ + assert.throws(function(){ + var m = mquery().select('x').distinct(); + }, /field selection and slice cannot be used with distinct/); + done(); + }) + + it('slice', function(done){ + assert.throws(function(){ + var m = mquery().where('x').slice(-3).distinct(); + }, /field selection and slice cannot be used with distinct/); + done(); + }) + + it('limit', function(done){ + assert.throws(function(){ + var m = mquery().limit(3).distinct(); + }, /limit cannot be used with distinct/); + done(); + }) + + it('skip', function(done){ + assert.throws(function(){ + var m = mquery().skip(3).distinct(); + }, /skip cannot be used with distinct/); + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 }).distinct(); + }, /batchSize cannot be used with distinct/); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery').distinct(); + }, /comment cannot be used with distinct/); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300).distinct(); + }, /maxScan cannot be used with distinct/); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot().distinct(); + }, /snapshot cannot be used with distinct/); + done(); + }) + + it('hint', function(done){ + assert.throws(function(){ + var m = mquery().hint({ x: 1 }).distinct(); + }, /hint cannot be used with distinct/); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable().distinct(); + }, /tailable cannot be used with distinct/); + done(); + }) + }) + }) + + describe('update', function(){ + describe('with no callback', function(){ + it('does not execute', function(){ + var m = mquery(); + assert.doesNotThrow(function () { + m.update({ name: 'old' }, { name: 'updated' }, { multi: true }) + }) + assert.doesNotThrow(function () { + m.update({ name: 'old' }, { name: 'updated' }) + }) + assert.doesNotThrow(function () { + m.update({ name: 'updated' }) + }) + assert.doesNotThrow(function () { + m.update() + }) + }) + }) + + it('is chainable', function(){ + var m = mquery({x:1}).update({ y: 2 }); + var n = m.where({y:2}); + assert.equal(m, n); + assert.deepEqual(n._conditions, {x:1, y:2}); + assert.deepEqual({ y: 2 }, n._update); + assert.equal('update', n.op); + }); + + it('merges update doc arg', function(){ + var a = [1,2]; + var m = mquery().where({ name: 'mquery' }).update({ x: 'stuff', a: a }); + m.update({ z: 'stuff' }); + assert.deepEqual(m._update, { z: 'stuff', x: 'stuff', a: a }); + assert.deepEqual(m._conditions, { name: 'mquery' }); + assert.ok(!m.options.overwrite); + m.update({}, { z: 'renamed' }, { overwrite: true }); + assert.ok(m.options.overwrite === true); + assert.deepEqual(m._conditions, { name: 'mquery' }); + assert.deepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); + a.push(3); + assert.notDeepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); + }) + + it('merges other options', function(){ + var m = mquery(); + m.setOptions({ overwrite: true }); + m.update({ age: 77 }, { name: 'pagemill' }, { multi: true }) + assert.deepEqual({ age: 77 }, m._conditions); + assert.deepEqual({ name: 'pagemill' }, m._update); + assert.deepEqual({ overwrite: true, multi: true }, m.options); + }) + + describe('executes', function(){ + var id; + before(function (done) { + col.insert({ name: 'mquery update', age: 1 }, { safe: true }, function (err, docs) { + var elem = docs[0]; + id = elem._id; + done(); + }); + }); + + after(function(done){ + col.remove({ _id: id }, done); + }) + + describe('when conds + doc + opts + callback passed', function(){ + it('works', function(done){ + var m = mquery(col).where({ _id: id }) + m.update({}, { name: 'Sparky' }, { safe: true }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'Sparky'); + done(); + }) + }) + }) + }) + + describe('when conds + doc + callback passed', function(){ + it('works', function (done) { + var m = mquery(col).update({ _id: id }, { name: 'fairgrounds' }, function (err, num, doc) { + assert.ifError(err); + assert.ok(1, num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'fairgrounds'); + done(); + }) + }) + }) + }) + + describe('when doc + callback passed', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }).update({ name: 'changed' }, function (err, num, doc) { + assert.ifError(err); + assert.ok(1, num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'changed'); + done(); + }) + }) + }) + }) + + describe('when just callback passed', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true }); + m.update({ name: 'Frankenweenie' }); + m.update(function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(doc.name, 'Frankenweenie'); + done(); + }) + }) + }) + }) + + describe('without a callback', function(){ + it('when forced by exec()', function(done){ + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, multi: true }); + m.update({ name: 'forced' }); + + var update = m._collection.update; + m._collection.update = function (conds, doc, opts, cb) { + m._collection.update = update; + + assert.ok(!opts.safe); + assert.ok(true === opts.multi); + assert.equal('forced', doc.$set.name); + done(); + } + + m.exec() + }) + }) + + describe('except when update doc is empty and missing overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true }); + m.update({ }, function (err, num) { + assert.ifError(err); + assert.ok(0 === num); + setTimeout(function(){ + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(3, mquery.utils.keys(doc).length); + assert.equal(id, doc._id.toString()); + assert.equal('Frankenweenie', doc.name); + done(); + }) + }, 300); + }) + }) + }); + + describe('when update doc is set with overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, overwrite: true }); + m.update({ all: 'yep', two: 2 }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(3, mquery.utils.keys(doc).length); + assert.equal('yep', doc.all); + assert.equal(2, doc.two); + assert.equal(id, doc._id.toString()); + done(); + }) + }) + }) + }) + + describe('when update doc is empty with overwrite flag', function(){ + it('works', function (done) { + var m = mquery(col).where({ _id: id }); + m.setOptions({ safe: true, overwrite: true }); + m.update({ }, function (err, num) { + assert.ifError(err); + assert.ok(1 === num); + m.findOne(function (err, doc) { + assert.ifError(err); + assert.equal(1, mquery.utils.keys(doc).length); + assert.equal(id, doc._id.toString()); + done(); + }) + }) + }) + }) + + describe('when boolean (true) - exec()', function(){ + it('works', function(done){ + var m = mquery(col).where({ _id: id }); + m.update({ name: 'bool' }).update(true); + setTimeout(function () { + m.findOne(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal('bool', doc.name); + done(); + }) + }, 300) + }) + }) + }) + }) + + describe('remove', function(){ + describe('with 0 args', function(){ + var name = 'remove: no args test' + before(function(done){ + col.insert({ name: name }, { safe: true }, done) + }) + after(function(done){ + col.remove({ name: name }, { safe: true }, done) + }) + + it('does not execute', function(done){ + var remove = col.remove; + col.remove = function () { + col.remove = remove; + done(new Error('remove executed!')); + } + + var m = mquery(col).where({ name: name }).remove() + setTimeout(function () { + col.remove = remove; + done(); + }, 10); + }) + + it('chains', function(){ + var m = mquery(); + assert.equal(m, m.remove()); + }) + }) + + describe('with 1 argument', function(){ + var name = 'remove: 1 arg test' + before(function(done){ + col.insert({ name: name }, { safe: true }, done) + }) + after(function(done){ + col.remove({ name: name }, { safe: true }, done) + }) + + describe('that is a', function(){ + it('plain object', function(){ + var m = mquery(col).remove({ name: 'Whiskers' }); + m.remove({ color: '#fff' }) + assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); + }) + + it('query', function(){ + var q = mquery({ color: '#fff' }); + var m = mquery(col).remove({ name: 'Whiskers' }); + m.remove(q) + assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); + }) + + it('function', function(done){ + mquery(col, { safe: true }).where({name: name}).remove(function (err) { + assert.ifError(err); + mquery(col).findOne({ name: name }, function (err, doc) { + assert.ifError(err); + assert.equal(null, doc); + done(); + }) + }); + }) + + it('boolean (true) - execute', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + mquery(col).findOne({ name: name }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + mquery(col).remove(true); + setTimeout(function () { + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(0, docs.length); + done(); + }) + }, 300) + }) + }) + }) + }) + }) + + describe('with 2 arguments', function(){ + var name = 'remove: 2 arg test' + beforeEach(function(done){ + col.remove({}, { safe: true }, function (err) { + assert.ifError(err); + col.insert([{ name: 'shelly' }, { name: name }], { safe: true }, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + }) + }) + + describe('plain object + callback', function(){ + it('works', function(done){ + mquery(col).remove({ name: name }, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(1, docs.length); + assert.equal('shelly', docs[0].name); + done(); + }) + }); + }) + }) + + describe('mquery + callback', function(){ + it('works', function(done){ + var m = mquery({ name: name }); + mquery(col).remove(m, function (err) { + assert.ifError(err); + mquery(col).find(function (err, docs) { + assert.ifError(err); + assert.ok(docs); + assert.equal(1, docs.length); + assert.equal('shelly', docs[0].name); + done(); + }) + }); + }) + }) + }) + }) + + function validateFindAndModifyOptions (method) { + describe('validates its option', function(){ + it('sort', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().sort('x')[method](); + }) + done(); + }) + + it('select', function(done){ + assert.doesNotThrow(function(){ + var m = mquery().select('x')[method](); + }) + done(); + }) + + it('limit', function(done){ + assert.throws(function(){ + var m = mquery().limit(3)[method](); + }, new RegExp('limit cannot be used with ' + method)); + done(); + }) + + it('skip', function(done){ + assert.throws(function(){ + var m = mquery().skip(3)[method](); + }, new RegExp('skip cannot be used with ' + method)); + done(); + }) + + it('batchSize', function(done){ + assert.throws(function(){ + var m = mquery({}, { batchSize: 3 })[method](); + }, new RegExp('batchSize cannot be used with ' + method)); + done(); + }) + + it('maxScan', function(done){ + assert.throws(function(){ + var m = mquery().maxScan(300)[method](); + }, new RegExp('maxScan cannot be used with ' + method)); + done(); + }) + + it('snapshot', function(done){ + assert.throws(function(){ + var m = mquery().snapshot()[method](); + }, new RegExp('snapshot cannot be used with ' + method)); + done(); + }) + + it('hint', function(done){ + assert.throws(function(){ + var m = mquery().hint({ x: 1 })[method](); + }, new RegExp('hint cannot be used with ' + method)); + done(); + }) + + it('tailable', function(done){ + assert.throws(function(){ + var m = mquery().tailable()[method](); + }, new RegExp('tailable cannot be used with ' + method)); + done(); + }) + + it('comment', function(done){ + assert.throws(function(){ + var m = mquery().comment('mquery')[method](); + }, new RegExp('comment cannot be used with ' + method)); + done(); + }) + }) + } + + describe('findOneAndUpdate', function(){ + var name = 'findOneAndUpdate + fn' + + validateFindAndModifyOptions('findOneAndUpdate'); + + describe('with 0 args', function(){ + it('makes no changes', function(){ + var m = mquery(); + var n = m.findOneAndUpdate(); + assert.deepEqual(m, n); + }) + }) + describe('with 1 arg', function(){ + describe('that is an object', function(){ + it('updates the doc', function(){ + var m = mquery(); + var n = m.findOneAndUpdate({ $set: { name: '1 arg' }}); + assert.deepEqual(n._update, { $set: { name: '1 arg' }}); + }) + }) + describe('that is a query', function(){ + it('updates the doc', function(){ + var m = mquery({ name: name }).update({ x: 1 }); + var n = mquery().findOneAndUpdate(m); + assert.deepEqual(n._update, { x: 1 }); + }) + }) + it('that is a function', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery({ name: name }).collection(col); + name = '1 arg'; + var n = m.update({ $set: { name: name }}); + n.findOneAndUpdate(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + describe('with 2 args', function(){ + it('conditions + update', function(){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { age: 100 }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ age: 100 }, m._update); + }) + it('query + update', function(){ + var n = mquery({ name: name }); + var m = mquery(col); + m.findOneAndUpdate(n, { age: 100 }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ age: 100 }, m._update); + }) + it('update + callback', function(done){ + var m = mquery(col).where({ name: name }); + m.findOneAndUpdate({ $inc: { age: 10 }}, function (err, doc) { + assert.ifError(err); + assert.equal(10, doc.age); + done(); + }); + }) + }) + describe('with 3 args', function(){ + it('conditions + update + options', function(){ + var m = mquery(); + var n = m.findOneAndUpdate({ name: name }, { works: true }, { new: false }); + assert.deepEqual({ name: name}, n._conditions); + assert.deepEqual({ works: true }, n._update); + assert.deepEqual({ new: false }, n.options); + }) + it('conditions + update + callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { works: true }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + assert.ok(true === doc.works); + done(); + }); + }) + }) + describe('with 4 args', function(){ + it('conditions + update + options + callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: name }, { works: false }, { new: false }, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + assert.ok(true === doc.works); + done(); + }); + }) + }) + }) + + describe('findOneAndRemove', function(){ + var name = 'findOneAndRemove' + + validateFindAndModifyOptions('findOneAndRemove'); + + describe('with 0 args', function(){ + it('makes no changes', function(){ + var m = mquery(); + var n = m.findOneAndRemove(); + assert.deepEqual(m, n); + }) + }) + describe('with 1 arg', function(){ + describe('that is an object', function(){ + it('updates the doc', function(){ + var m = mquery(); + var n = m.findOneAndRemove({ name: '1 arg' }); + assert.deepEqual(n._conditions, { name: '1 arg' }); + }) + }) + describe('that is a query', function(){ + it('updates the doc', function(){ + var m = mquery({ name: name }); + var n = m.findOneAndRemove(m); + assert.deepEqual(n._conditions, { name: name }); + }) + }) + it('that is a function', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery({ name: name }).collection(col); + m.findOneAndRemove(function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + describe('with 2 args', function(){ + it('conditions + options', function(){ + var m = mquery(col); + m.findOneAndRemove({ name: name }, { new: false }); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ new: false }, m.options); + }) + it('query + options', function(){ + var n = mquery({ name: name }); + var m = mquery(col); + m.findOneAndRemove(n, { sort: { x: 1 }}); + assert.deepEqual({ name: name }, m._conditions); + assert.deepEqual({ sort: { 'x': 1 }}, m.options); + }) + it('conditions + callback', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var m = mquery(col); + m.findOneAndRemove({ name: name }, function (err, doc) { + assert.ifError(err); + assert.equal(name, doc.name); + done(); + }); + }); + }) + it('query + callback', function(done){ + col.insert({ name: name }, { safe: true }, function (err) { + assert.ifError(err); + var n = mquery({ name: name }) + var m = mquery(col); + m.findOneAndRemove(n, function (err, doc) { + assert.ifError(err); + assert.equal(name, doc.name); + done(); + }); + }); + }) + }) + describe('with 3 args', function(){ + it('conditions + options + callback', function(done){ + name = 'findOneAndRemove + conds + options + cb'; + col.insert([{ name: name }, { name: 'a' }], { safe: true }, function (err) { + assert.ifError(err); + var m = mquery(col); + m.findOneAndRemove({ name: name }, { sort: { name: 1 }}, function (err, doc) { + assert.ifError(err); + assert.ok(doc); + assert.equal(name, doc.name); + done(); + }); + }) + }) + }) + }) + + describe('exec', function(){ + beforeEach(function(done){ + col.insert([{ name: 'exec', age: 1 }, { name: 'exec', age: 2 }], done); + }) + + afterEach(function(done){ + mquery(col).remove(done); + }) + + it('requires an op', function(){ + assert.throws(function () { + mquery().exec() + }, /Missing query type/); + }) + + describe('find', function() { + it('works', function(done){ + var m = mquery(col).find({ name: 'exec' }); + m.exec(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + + it('works with readPreferences', function (done) { + var m = mquery(col).find({ name: 'exec' }); + try { + var rp = new require('mongodb').ReadPreference('primary'); + m.read(rp); + } catch (e) { + if (e.code === 'MODULE_NOT_FOUND') + e = null; + done(e); + return; + } + m.exec(function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }) + }); + + it('findOne', function(done){ + var m = mquery(col).findOne({ age: 2 }); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal(2, doc.age); + done(); + }) + }) + + it('count', function(done){ + var m = mquery(col).count({ name: 'exec' }); + m.exec(function (err, count) { + assert.ifError(err); + assert.equal(2, count); + done(); + }) + }) + + it('distinct', function(done){ + var m = mquery({ name: 'exec' }); + m.collection(col); + m.distinct('age'); + m.exec(function (err, array) { + assert.ifError(err); + assert.ok(Array.isArray(array)); + assert.equal(2, array.length); + assert(~array.indexOf(1)); + assert(~array.indexOf(2)); + done(); + }); + }) + + describe('update', function(){ + var num; + + it('with a callback', function(done){ + var m = mquery(col); + m.where({ name: 'exec' }) + + m.count(function (err, _num) { + assert.ifError(err); + num = _num; + m.setOptions({ multi: true }) + m.update({ name: 'exec + update' }); + m.exec(function (err, res) { + assert.ifError(err); + assert.equal(num, res); + mquery(col).find({ name: 'exec + update' }, function (err, docs) { + assert.ifError(err); + assert.equal(num, docs.length); + done(); + }) + }) + }) + }) + + it('without a callback', function(done){ + var m = mquery(col) + m.where({ name: 'exec + update' }).setOptions({ multi: true }) + m.update({ name: 'exec' }); + + // unsafe write + m.exec(); + + setTimeout(function () { + mquery(col).find({ name: 'exec' }, function (err, docs) { + assert.ifError(err); + assert.equal(2, docs.length); + done(); + }) + }, 200) + }) + it('preserves key ordering', function(done) { + var m = mquery(col); + + var m2 = m.update({ _id : 'something' }, { '1' : 1, '2' : 2, '3' : 3}); + var doc = m2._updateForExec().$set; + var count = 0; + for (var i in doc) { + if (count == 0) { + assert.equal('1', i); + } else if (count == 1) { + assert.equal('2', i); + } else if (count ==2) { + assert.equal('3', i); + } + count++; + } + done(); + }); + }) + + describe('remove', function(){ + it('with a callback', function(done){ + var m = mquery(col).where({ age: 2 }).remove(); + m.exec(function (err, num) { + assert.ifError(err); + assert.equal(1, num); + done(); + }) + }) + + it('without a callback', function(done){ + var m = mquery(col).where({ age: 1 }).remove(); + m.exec(); + + setTimeout(function () { + mquery(col).where('name', 'exec').count(function(err, num) { + assert.equal(1, num); + done(); + }) + }, 200) + }) + }) + + describe('findOneAndUpdate', function(){ + it('with a callback', function(done){ + var m = mquery(col); + m.findOneAndUpdate({ name: 'exec', age: 1 }, { $set: { name: 'findOneAndUpdate' }}); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal('findOneAndUpdate', doc.name); + done(); + }); + }) + }) + + describe('findOneAndRemove', function(){ + it('with a callback', function(done){ + var m = mquery(col); + m.findOneAndRemove({ name: 'exec', age: 2 }); + m.exec(function (err, doc) { + assert.ifError(err); + assert.equal('exec', doc.name); + assert.equal(2, doc.age); + mquery(col).count({ name: 'exec' }, function (err, num) { + assert.ifError(err); + assert.equal(1, num); + done(); + }); + }); + }) + }) + }) + + describe('setTraceFunction', function() { + beforeEach(function(done){ + col.insert([{ name: 'trace', age: 93 }], done); + }) + + it('calls trace function when executing query', function(done) { + var m = mquery(col); + + var resultTraceCalled; + + m.setTraceFunction(function (method, queryInfo) { + try { + assert.equal('findOne', method); + assert.equal('trace', queryInfo.conditions.name); + } catch (e) { + done(e); + } + + return function(err, result, millis) { + try { + assert.equal(93, result.age); + } catch (e) { + done(e); + } + resultTraceCalled = true; + }; + }); + + m.findOne({name: 'trace'}, function (err, doc) { + assert.ifError(err); + assert.equal(resultTraceCalled, true); + assert.equal(93, doc.age); + done(); + }); + }); + + it('inherits trace function when calling toConstructor', function(done) { + function traceFunction () { return function() {} }; + + var tracedQuery = mquery().setTraceFunction(traceFunction).toConstructor(); + + var query = tracedQuery(); + assert.equal(traceFunction, query._traceFunction); + + done(); + }); + }); + + describe('thunk', function() { + it('returns a function', function(done) { + assert.equal('function', typeof mquery().thunk()); + done(); + }); + + it('passes the fn arg to `exec`', function(done) { + function cb() {} + var m = mquery(); + + m.exec = function testing(fn) { + assert.equal(this, m); + assert.equal(cb, fn); + done(); + } + + m.thunk()(cb); + }); + }); + + describe('then', function() { + before(function(done){ + col.insert([{ name: 'then', age: 1 }, { name: 'then', age: 2 }], done); + }) + + after(function(done){ + mquery(col).remove({ name: 'then' }).exec(done); + }) + + it('returns a promise A+ compat object', function(done) { + var m = mquery(col).find(); + assert.equal('function', typeof m.then); + done(); + }); + + it('creates a promise that is resolved on success', function(done) { + var promise = mquery(col).count({ name: 'then' }).then(); + promise.then(function(count){ + assert.equal(2, count); + done(); + }, done); + }); + + it('supports exec() cb being called synchronously #66', function(done) { + var query = mquery(col).count({ name: 'then' }); + query.exec = function(cb) { + cb(null, 66); + } + + query.then(success, done); + function success(count){ + assert.equal(66, count); + done(); + } + }); + + it('supports other Promise libs', function(done) { + var bluebird = mquery.Promise; + + // hack for testing + mquery.Promise = function P() { + mquery.Promise = bluebird; + this.then = function(x, y) { + return x + y; + } + } + + var val = mquery(col).count({ name: 'exec' }).then(1, 2); + assert.equal(val, 3); + done(); + }); + }); + + describe('stream', function() { + before(function(done){ + col.insert([{ name: 'stream', age: 1 }, { name: 'stream', age: 2 }], done); + }) + + after(function(done){ + mquery(col).remove({ name: 'stream' }).exec(done); + }) + + describe('throws', function() { + describe('if used with non-find operations', function() { + var ops = ['update', 'findOneAndUpdate', 'remove', 'count', 'distinct']; + + ops.forEach(function(op) { + assert.throws(function(){ + mquery(col)[op]().stream(); + }); + }); + }); + }); + + it('returns a stream', function(done) { + var stream = mquery(col).find({ name: 'stream' }).stream(); + var count = 0; + var err; + + stream.on('data', function(doc){ + assert.equal('stream', doc.name); + ++count; + }); + + stream.on('error', function(er) { + err = er; + }); + + stream.on('close', function(){ + if (err) return done(err); + assert.equal(2, count); + done(); + }); + }); + + it('supports find options', function(done) { + var stream = mquery(col) + .find({ name: 'stream' }) + .limit(1) + .select('-_id') + .stream({ transform: xform }); + + function xform(doc) { + doc.name = doc.name + '-xformed'; + return doc; + } + + var count = 0; + var err; + + stream.on('data', function(doc){ + assert(!doc._id); + assert.equal('stream-xformed', doc.name); + ++count; + }); + + stream.on('error', function(er) { + err = er; + }); + + stream.on('close', function(){ + if (err) return done(err); + assert.equal(1, count); + done(); + }); + }); + + }); + + function noDistinct (type) { + it('cannot be used with distinct()', function(done){ + assert.throws(function () { + mquery().distinct('name')[type](4); + }, new RegExp(type + ' cannot be used with distinct')); + done(); + }) + } + + function no (method, type) { + it('cannot be used with ' + method + '()', function(done){ + assert.throws(function () { + mquery()[method]()[type](4); + }, new RegExp(type + ' cannot be used with ' + method)); + done(); + }) + } + + // query internal + + describe('_updateForExec', function(){ + it('returns a clone of the update object with same key order #19', function(done){ + var update = {}; + update.$push = { n: { $each: [{x:10}], $slice: -1, $sort: {x:1}}}; + + var q = mquery().update({ x: 1 }, update); + + // capture original key order + var order = []; + for (var key in q._update.$push.n) { + order.push(key); + } + + // compare output + var doc = q._updateForExec(); + var i = 0; + for (var key in doc.$push.n) { + assert.equal(key, order[i]); + i++; + } + + done(); + }) + }) +}) diff --git a/6-2/node_modules/mongoose/node_modules/mquery/test/utils.test.js b/6-2/node_modules/mongoose/node_modules/mquery/test/utils.test.js new file mode 100644 index 0000000..fa5972a --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/mquery/test/utils.test.js @@ -0,0 +1,143 @@ + +var utils = require('../lib/utils'); +var assert = require('assert'); + +var mongo; +try { + mongo = new require('mongodb'); +} catch (e) {} + +describe('lib/utils', function() { + describe('clone', function() { + it('clones constructors named ObjectId', function(done) { + function ObjectId (id) { + this.id = id; + } + + var o1 = new ObjectId('1234'); + var o2 = utils.clone(o1); + assert.ok(o2 instanceof ObjectId); + + done(); + }); + + it('clones constructors named ObjectID', function(done) { + function ObjectID (id) { + this.id = id; + } + + var o1 = new ObjectID('1234'); + var o2 = utils.clone(o1); + + assert.ok(o2 instanceof ObjectID); + done(); + }); + + it('does not clone constructors named ObjectIdd', function(done) { + function ObjectIdd (id) { + this.id = id; + } + + var o1 = new ObjectIdd('1234'); + var o2 = utils.clone(o1); + assert.ok(!(o2 instanceof ObjectIdd)); + + done(); + }); + + it('optionally clones ObjectId constructors using its clone method', function(done) { + function ObjectID (id) { + this.id = id; + this.cloned = false; + } + + ObjectID.prototype.clone = function () { + var ret = new ObjectID(this.id); + ret.cloned = true; + return ret; + } + + var id = 1234; + var o1 = new ObjectID(id); + assert.equal(id, o1.id); + assert.equal(false, o1.cloned); + + var o2 = utils.clone(o1); + assert.ok(o2 instanceof ObjectID); + assert.equal(id, o2.id); + assert.ok(o2.cloned); + done(); + }); + + it('clones mongodb.ReadPreferences', function (done) { + if (!mongo) return done(); + + var tags = [ + {dc: 'tag1'} + ]; + var prefs = [ + new mongo.ReadPreference("primary"), + new mongo.ReadPreference(mongo.ReadPreference.PRIMARY_PREFERRED), + new mongo.ReadPreference("primary", tags), + mongo.ReadPreference("primary", tags) + ]; + + var prefsCloned = utils.clone(prefs); + + for (var i = 0; i < prefsCloned.length; i++) { + assert.notEqual(prefs[i], prefsCloned[i]); + assert.ok(prefsCloned[i] instanceof mongo.ReadPreference); + assert.ok(prefsCloned[i].isValid()); + if (prefs[i].tags) { + assert.ok(prefsCloned[i].tags); + assert.notEqual(prefs[i].tags, prefsCloned[i].tags); + assert.notEqual(prefs[i].tags[0], prefsCloned[i].tags[0]); + } else { + assert.equal(prefsCloned[i].tags, null); + } + } + + done(); + }); + + it('clones mongodb.Binary', function(done){ + if (!mongo) return done(); + + var buf = new Buffer('hi'); + var binary= new mongo.Binary(buf, 2); + var clone = utils.clone(binary); + assert.equal(binary.sub_type, clone.sub_type); + assert.equal(String(binary.buffer), String(buf)); + assert.ok(binary !== clone); + done(); + }) + + it('handles objects with no constructor', function(done) { + var name ='335'; + + var o = Object.create(null); + o.name = name; + + var clone; + assert.doesNotThrow(function() { + clone = utils.clone(o); + }); + + assert.equal(name, clone.name); + assert.ok(o != clone); + done(); + }); + + it('handles buffers', function(done){ + var buff = new Buffer(10); + buff.fill(1); + var clone = utils.clone(buff); + + for (var i = 0; i < buff.length; i++) { + assert.equal(buff[i], clone[i]); + } + + done(); + }); + }); +}); diff --git a/6-2/node_modules/mongoose/node_modules/ms/.npmignore b/6-2/node_modules/mongoose/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/6-2/node_modules/mongoose/node_modules/ms/History.md b/6-2/node_modules/mongoose/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/6-2/node_modules/mongoose/node_modules/ms/LICENSE b/6-2/node_modules/mongoose/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(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/6-2/node_modules/mongoose/node_modules/ms/README.md b/6-2/node_modules/mongoose/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# 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](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'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/6-2/node_modules/mongoose/node_modules/ms/index.js b/6-2/node_modules/mongoose/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * 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) { + 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': + 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/6-2/node_modules/mongoose/node_modules/ms/package.json b/6-2/node_modules/mongoose/node_modules/ms/package.json new file mode 100644 index 0000000..253335e --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/ms/package.json @@ -0,0 +1,48 @@ +{ + "name": "ms", + "version": "0.7.1", + "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": "713dcf26d9e6fd9dbc95affe7eff9783b7f1b909", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "homepage": "https://github.com/guille/ms.js", + "_id": "ms@0.7.1", + "scripts": {}, + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_from": "ms@0.7.1", + "_npmVersion": "2.7.5", + "_nodeVersion": "0.12.2", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + } + ], + "dist": { + "shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "tarball": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/6-2/node_modules/mongoose/node_modules/muri/.npmignore b/6-2/node_modules/mongoose/node_modules/muri/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/muri/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/6-2/node_modules/mongoose/node_modules/muri/.travis.yml b/6-2/node_modules/mongoose/node_modules/muri/.travis.yml new file mode 100644 index 0000000..895dbd3 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/muri/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/6-2/node_modules/mongoose/node_modules/muri/History.md b/6-2/node_modules/mongoose/node_modules/muri/History.md new file mode 100644 index 0000000..87b7053 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/muri/History.md @@ -0,0 +1,52 @@ + +1.0.0 / 2014-10-18 +================== + + * fixed; compatibility w/ strict mode #4 [vkarpov15](https://github.com/vkarpov15) + +0.3.1 / 2013-02-17 +================== + + * fixed; allow '#' in username and password #3 + +0.3.0 / 2013-01-14 +================== + + * fixed; default db logic #2 + +0.2.0 / 2013-01-09 +================== + + * changed; default db is now 'test' + +0.1.0 / 2012-12-18 +================== + + * changed; include .sock in UDS + +0.0.5 / 2012-12-18 +================== + + * fixed; unix domain sockets used with db names + +0.0.4 / 2012-12-01 +================== + + * handle multple specified protocols + +0.0.3 / 2012-11-29 +================== + + * validate mongodb:///db + * more detailed error message + +0.0.2 / 2012-11-02 +================== + + * add readPreferenceTags support + * add unix domain support + +0.0.1 / 2012-11-01 +================== + + * initial release diff --git a/6-2/node_modules/mongoose/node_modules/muri/LICENSE b/6-2/node_modules/mongoose/node_modules/muri/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/muri/LICENSE @@ -0,0 +1,22 @@ +(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/6-2/node_modules/mongoose/node_modules/muri/Makefile b/6-2/node_modules/mongoose/node_modules/muri/Makefile new file mode 100644 index 0000000..e6337bd --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/muri/Makefile @@ -0,0 +1,5 @@ + +test: + @node_modules/mocha/bin/mocha $(T) + +.PHONY: test diff --git a/6-2/node_modules/mongoose/node_modules/muri/README.md b/6-2/node_modules/mongoose/node_modules/muri/README.md new file mode 100644 index 0000000..3757419 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/muri/README.md @@ -0,0 +1,46 @@ +#Meet Muri! + +Muri is your friendly neighborhood [MongoDB URI](http://www.mongodb.org/display/DOCS/Connections) parser for Node.js. + + +###Install + + $ npm install muri + +###Use + +```js + var muri = require('muri'); + var o = muri('mongodb://user:pass@local,remote:27018,japan:27019/neatdb?replicaSet=myreplset&journal=true&w=2&wtimeoutMS=50'); + + console.log(o); + + { hosts: [ { host: 'local', port: 27017 }, + { host: 'remote', port: 27018 }, + { host: 'japan', port: 27019 } ], + db: 'neatdb', + options: { + replicaSet: 'myreplset', + journal: true, + w: 2, + wtimeoutMS: 50 + }, + auth: { + user: 'user', + pass: 'pass' + } + } +``` + +### Details + +The returned object contains the following properties: + +- db: the name of the database. defaults to "admin" if not specified +- auth: if auth is specified, this object will exist `{ user: 'username', pass: 'password' }` +- hosts: array of host/port objects, one for each specified `[{ host: 'local', port: 27107 }, { host: '..', port: port }]` + - if a port is not specified for a given host, the default port (27017) is used + - if a unix domain socket is passed, host/port will be undefined and `ipc` will be set to the value specified `[{ ipc: '/tmp/mongodb-27017' }]` +- options: this is a hash of all options specified in the querystring + +[LICENSE](https://github.com/aheckmann/muri/blob/master/LICENSE) diff --git a/6-2/node_modules/mongoose/node_modules/muri/index.js b/6-2/node_modules/mongoose/node_modules/muri/index.js new file mode 100644 index 0000000..f7b65dd --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/muri/index.js @@ -0,0 +1 @@ +module.exports = exports = require('./lib'); diff --git a/6-2/node_modules/mongoose/node_modules/muri/lib/index.js b/6-2/node_modules/mongoose/node_modules/muri/lib/index.js new file mode 100644 index 0000000..59cb396 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/muri/lib/index.js @@ -0,0 +1,241 @@ +// muri + +/** + * MongoDB URI parser as described here: + * http://www.mongodb.org/display/DOCS/Connections + */ + +/** + * Module dependencies + */ + +var qs = require('querystring'); + +/** + * Defaults + */ + +var DEFAULT_PORT = 27017; +var DEFAULT_DB = 'test'; +var ADMIN_DB = 'admin'; + +/** + * Muri + */ + +module.exports = exports = function muri (str) { + if (!/^mongodb:\/\//.test(str)) { + throw new Error('Invalid mongodb uri. Must begin with "mongodb://"' + + '\n Received: ' + str); + } + + var ret = { + hosts: [] + , db: DEFAULT_DB + , options: {} + } + + var match = /^mongodb:\/\/([^?]+)(\??.*)$/.exec(str); + if (!match || '/' == match[1]) { + throw new Error('Invalid mongodb uri. Missing hostname'); + } + + var uris = match[1]; + var path = match[2]; + var db; + + uris.split(',').forEach(function (uri) { + var o = parse(uri); + + if (o.host) { + ret.hosts.push({ + host: o.host + , port: parseInt(o.port, 10) + }) + + if (!db && o.db) { + db = o.db; + } + } else if (o.ipc) { + ret.hosts.push({ ipc: o.ipc }); + } + + if (o.auth) { + ret.auth = { + user: o.auth.user + , pass: o.auth.pass + } + } + }) + + if (!ret.hosts.length) { + throw new Error('Invalid mongodb uri. Missing hostname'); + } + + var parts = path.split('?'); + + if (!db) { + if (parts[0]) { + db = parts[0].replace(/^\//, ''); + } else { + // deal with ipc formats + db = /\/([^\.]+)$/.exec(match[1]); + if (db && db[1]) { + db = db[1]; + } + } + } + + if (db) { + ret.db = db; + } else if (ret.auth) { + ret.db = ADMIN_DB; + } + + if (parts[1]) { + ret.options = options(parts[1]); + } + + return ret; +} + +/** + * Parse str into key/val pairs casting values appropriately. + */ + +function options (str) { + var sep = /;/.test(str) + ? ';' + : '&'; + + var ret = qs.parse(str, sep); + + Object.keys(ret).forEach(function (key) { + var val = ret[key]; + if ('readPreferenceTags' == key) { + val = readPref(val); + if (val) { + ret[key] = Array.isArray(val) + ? val + : [val]; + } + } else { + ret[key] = format(val); + } + }); + + return ret; +} + +function format (val) { + var num; + + if ('true' == val) { + return true; + } else if ('false' == val) { + return false; + } else { + num = parseInt(val, 10); + if (!isNaN(num)) { + return num; + } + } + + return val; +} + +function readPref (val) { + var ret; + + if (Array.isArray(val)) { + ret = val.map(readPref).filter(Boolean); + return ret.length + ? ret + : undefined + } + + var pair = val.split(','); + var hasKeys; + ret = {}; + + pair.forEach(function (kv) { + kv = (kv || '').trim(); + if (!kv) return; + hasKeys = true; + var split = kv.split(':'); + ret[split[0]] = format(split[1]); + }); + + return hasKeys && ret; +} + +var ipcRgx = /\.sock/; + +function parse (uriString) { + // do not use require('url').parse b/c it can't handle # in username or pwd + // mongo uris are strange + + var uri = uriString; + var ret = {}; + var parts; + var auth; + var ipcs; + + // skip protocol + uri = uri.replace(/^mongodb:\/\//, ''); + + // auth + if (/@/.test(uri)) { + parts = uri.split(/@/); + auth = parts[0]; + uri = parts[1]; + + parts = auth.split(':'); + ret.auth = {}; + ret.auth.user = parts[0]; + ret.auth.pass = parts[1]; + } + + // unix domain sockets + if (ipcRgx.test(uri)) { + ipcs = uri.split(ipcRgx); + ret.ipc = ipcs[0] + '.sock'; + + // included a database? + if (ipcs[1]) { + // strip leading / from database name + ipcs[1] = ipcs[1].replace(/^\//, ''); + + if (ipcs[1]) { + ret.db = ipcs[1]; + } + } + + return ret; + } + + // database name + parts = uri.split('/'); + if (parts[1]) ret.db = parts[1]; + + // ipv6, [ip]:host + if (/^\[[^\]]+\]:\d+/.test(parts[0])) { + ret.host = parts[0].substring(1, parts[0].indexOf(']:')); + ret.port = parts[0].substring(parts[0].indexOf(']:') + ']:'.length); + } else { + // host:port + parts = parts[0].split(':'); + ret.host = parts[0]; + ret.port = parts[1] || DEFAULT_PORT; + } + + return ret; +} + +/** + * Version + */ + +module.exports.version = JSON.parse( + require('fs').readFileSync(__dirname + '/../package.json', 'utf8') +).version; diff --git a/6-2/node_modules/mongoose/node_modules/muri/package.json b/6-2/node_modules/mongoose/node_modules/muri/package.json new file mode 100644 index 0000000..1d8e74d --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/muri/package.json @@ -0,0 +1,57 @@ +{ + "name": "muri", + "version": "1.1.0", + "description": "MongoDB URI parser", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/muri.git" + }, + "keywords": [ + "mongodb", + "uri", + "parser" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.21.5" + }, + "gitHead": "8f373948ef317865044994aaa98a013e769b2952", + "bugs": { + "url": "https://github.com/aheckmann/muri/issues" + }, + "homepage": "https://github.com/aheckmann/muri", + "_id": "muri@1.1.0", + "_shasum": "a3a6d74e68a880f433a249a74969cbb665cc0add", + "_from": "muri@1.1.0", + "_npmVersion": "2.5.1", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "vkarpov15", + "email": "valkar207@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "vkarpov15", + "email": "val@karpov.io" + } + ], + "dist": { + "shasum": "a3a6d74e68a880f433a249a74969cbb665cc0add", + "tarball": "http://registry.npmjs.org/muri/-/muri-1.1.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/muri/-/muri-1.1.0.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/6-2/node_modules/mongoose/node_modules/muri/test/index.js b/6-2/node_modules/mongoose/node_modules/muri/test/index.js new file mode 100644 index 0000000..65a4cfc --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/muri/test/index.js @@ -0,0 +1,321 @@ + +var muri = require('../') +var assert = require('assert') + +describe('muri', function(){ + it('must begin with mongodb://', function(done){ + assert.throws(function () { + muri('localhost:27017'); + }, /Invalid mongodb uri/); + assert.doesNotThrow(function () { + muri('mongodb://localhost:27017'); + }) + done(); + }) + + describe('user:password', function(done){ + it('is optional', function(done){ + var uri = 'mongodb://local:27017'; + var val = muri(uri); + assert.ok(!val.auth); + done(); + }) + + it('parses properly', function(done){ + var uri = 'mongodb://user:password@local:27017'; + var val = muri(uri); + assert.ok(val.auth); + assert.equal('user', val.auth.user); + assert.equal('password', val.auth.pass); + done(); + }) + + it('handles # in the username', function(done){ + var uri = 'mongodb://us#er:password@local:27017'; + var val = muri(uri); + assert.ok(val.auth); + assert.equal('us#er', val.auth.user); + assert.equal('password', val.auth.pass); + done(); + }) + + it('handles # in the password', function(done){ + var uri = 'mongodb://user:pa#ssword@local:27017'; + var val = muri(uri); + assert.ok(val.auth); + assert.equal('user', val.auth.user); + assert.equal('pa#ssword', val.auth.pass); + done(); + }) + }) + + describe('host', function(){ + it('must be specified', function(done){ + assert.throws(function () { + muri('mongodb://'); + }, /Missing host/) + assert.throws(function () { + muri('mongodb:///fake'); + }, /Missing host/) + assert.throws(function () { + muri('mongodb://?yep'); + }, /Missing host/) + assert.throws(function () { + muri('mongodb:///?yep'); + }, /Missing host/) + + var val = muri('mongodb://local'); + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal('local', val.hosts[0].host); + done(); + }) + + it('supports replica sets', function(done){ + var val = muri('mongodb://local:27017,remote:27018,japan:99999'); + assert.ok(Array.isArray(val.hosts)); + assert.equal(3, val.hosts.length); + assert.equal('local', val.hosts[0].host); + assert.equal(27017, val.hosts[0].port); + assert.equal('remote', val.hosts[1].host); + assert.equal(27018, val.hosts[1].port); + assert.equal('japan', val.hosts[2].host); + assert.equal(99999, val.hosts[2].port); + done(); + }) + }) + + describe('port', function(){ + + describe('with single host', function(){ + it('defaults to 27017 if not specified', function(done){ + var val = muri('mongodb://local/'); + assert.equal(27017, val.hosts[0].port); + done(); + }) + + it('uses what is specified', function(done){ + var val = muri('mongodb://local:27018'); + assert.equal(27018, val.hosts[0].port); + done(); + }) + }) + + describe('with replica sets', function(){ + var val; + + before(function(){ + val = muri('mongodb://local,remote:27018,another'); + }) + + it('defaults to 27017 if not specified', function(done){ + assert.equal(27017, val.hosts[0].port); + assert.equal(27017, val.hosts[2].port); + done(); + }) + + it('uses what is specified', function(done){ + assert.equal(27018, val.hosts[1].port); + done(); + }) + }) + }) + + describe('database', function(){ + it('default', function(done){ + var val = muri('mongodb://localhost/'); + assert.equal('test', val.db); + var val = muri('mongodb://localhost'); + assert.equal('test', val.db); + done(); + }) + it('is overridable', function(done){ + var val = muri('mongodb://localhost,a,x:34343,b/muri'); + assert.equal('muri', val.db); + done(); + }) + it('works with multiple specified protocols', function(done){ + var uri = 'mongodb://localhost:27020/testing,mongodb://localhost:27019,mongodb://localhost:27018' + var val = muri(uri); + assert.equal('testing', val.db); + done(); + }) + }) + + describe('querystring separator', function(){ + it('can be ; ', function(done){ + var val = muri('mongodb://muri/?replicaSet=myreplset;slaveOk=true;x=1'); + assert.ok(val.options); + assert.equal(true, val.options.slaveOk); + assert.equal('myreplset', val.options.replicaSet); + assert.equal(1, val.options.x); + done(); + }) + it('can be & ', function(done){ + var val = muri('mongodb://muri/?replicaSet=myreplset&slaveOk=true&x=1'); + assert.ok(val.options); + assert.equal(true, val.options.slaveOk); + assert.equal('myreplset', val.options.replicaSet); + assert.equal(1, val.options.x); + done(); + }) + }) + + describe('readPref tags', function(){ + describe('with & ', function(){ + it('mongodb://localhost/?readPreferenceTags=dc:ny', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny'); + assert.equal('test', val.db); + assert.deepEqual([{ dc: 'ny' }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1'); + assert.deepEqual([{ dc: 'ny', rack: 1 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2'); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2&readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:sf,rack:2&readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny&readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny&readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'ny' }], val.options.readPreferenceTags); + done(); + }) + }) + describe('with ; ', function(){ + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2'); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2;readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/db?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:sf,rack:2;readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'sf', rack: 2 }], val.options.readPreferenceTags); + done(); + }) + it('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=', function(done){ + var val = muri('mongodb://localhost/?readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags='); + assert.deepEqual([{ dc: 'ny', rack: 1 }, { dc: 'ny' }], val.options.readPreferenceTags); + done(); + }) + }) + }) + + describe('unix domain sockets', function(){ + it('without auth', function(done){ + var val = muri('mongodb:///tmp/mongodb-27017.sock?safe=false'); + assert.equal(val.db, 'test') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('without auth with a database name', function(done){ + var val = muri('mongodb:///tmp/mongodb-27017.sock/tester?safe=false'); + assert.equal(val.db, 'tester') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock?safe=false'); + assert.equal(val.db, 'admin') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth with a db name', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock/tester?safe=false'); + assert.equal(val.db, 'tester') + assert.ok(Array.isArray(val.hosts)); + assert.equal(1, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth + repl sets', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock,/tmp/another-27018.sock?safe=false'); + assert.equal(val.db, 'admin') + assert.ok(Array.isArray(val.hosts)); + assert.equal(2, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(val.hosts[1].ipc, '/tmp/another-27018.sock') + assert.equal(val.hosts[1].host, undefined); + assert.equal(val.hosts[1].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + it('with auth + repl sets with a db name', function(done){ + var val = muri('mongodb://user:password@/tmp/mongodb-27017.sock,/tmp/another-27018.sock/tester?safe=false'); + assert.equal(val.db, 'tester') + assert.ok(Array.isArray(val.hosts)); + assert.equal(2, val.hosts.length); + assert.equal(val.hosts[0].ipc, '/tmp/mongodb-27017.sock') + assert.equal(val.hosts[0].host, undefined); + assert.equal(val.hosts[0].port, undefined); + assert.equal(val.hosts[1].ipc, '/tmp/another-27018.sock') + assert.equal(val.hosts[1].host, undefined); + assert.equal(val.hosts[1].port, undefined); + assert.equal(false, val.options.safe); + done(); + }) + }) + + it('all together now', function(done){ + var uri = 'mongodb://u#ser:pas#s@local,remote:27018,japan:27019/neatdb' + uri += '?replicaSet=myreplset&journal=true&w=2&wtimeoutMS=50' + var val = muri(uri); + + assert.equal('u#ser', val.auth.user); + assert.equal('pas#s', val.auth.pass); + assert.equal('neatdb', val.db); + assert.equal(3, val.hosts.length); + assert.equal('local', val.hosts[0].host); + assert.strictEqual(27017, val.hosts[0].port); + assert.equal('remote', val.hosts[1].host); + assert.strictEqual(27018, val.hosts[1].port); + assert.equal('japan', val.hosts[2].host); + assert.strictEqual(27019, val.hosts[2].port); + assert.equal('myreplset', val.options.replicaSet); + assert.equal(true, val.options.journal); + assert.equal(50, val.options.wtimeoutMS); + done(); + }); + + it('ipv6', function(done) { + var uri = 'mongodb://[::1]:27017/test'; + var val = muri(uri); + assert.equal(1, val.hosts.length); + assert.equal('::1', val.hosts[0].host); + assert.equal(27017, val.hosts[0].port); + done(); + }); + + it('has a version', function(done){ + assert.ok(muri.version); + done(); + }) +}) diff --git a/6-2/node_modules/mongoose/node_modules/regexp-clone/.npmignore b/6-2/node_modules/mongoose/node_modules/regexp-clone/.npmignore new file mode 100644 index 0000000..be106ca --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/regexp-clone/.npmignore @@ -0,0 +1,2 @@ +*.sw* +node_modules/ diff --git a/6-2/node_modules/mongoose/node_modules/regexp-clone/.travis.yml b/6-2/node_modules/mongoose/node_modules/regexp-clone/.travis.yml new file mode 100644 index 0000000..58f2371 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/regexp-clone/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.6 + - 0.8 + - 0.10 diff --git a/6-2/node_modules/mongoose/node_modules/regexp-clone/History.md b/6-2/node_modules/mongoose/node_modules/regexp-clone/History.md new file mode 100644 index 0000000..0beedfc --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/regexp-clone/History.md @@ -0,0 +1,5 @@ + +0.0.1 / 2013-04-17 +================== + + * initial commit diff --git a/6-2/node_modules/mongoose/node_modules/regexp-clone/LICENSE b/6-2/node_modules/mongoose/node_modules/regexp-clone/LICENSE new file mode 100644 index 0000000..98c7c89 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/regexp-clone/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2013 [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/6-2/node_modules/mongoose/node_modules/regexp-clone/Makefile b/6-2/node_modules/mongoose/node_modules/regexp-clone/Makefile new file mode 100644 index 0000000..6c8fb75 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/regexp-clone/Makefile @@ -0,0 +1,5 @@ + +test: + @./node_modules/.bin/mocha $(T) --async-only $(TESTS) + +.PHONY: test diff --git a/6-2/node_modules/mongoose/node_modules/regexp-clone/README.md b/6-2/node_modules/mongoose/node_modules/regexp-clone/README.md new file mode 100644 index 0000000..2aabe5c --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/regexp-clone/README.md @@ -0,0 +1,18 @@ +#regexp-clone +============== + +Clones RegExps with flag preservation + +```js +var regexpClone = require('regexp-clone'); + +var a = /somethin/g; +console.log(a.global); // true + +var b = regexpClone(a); +console.log(b.global); // true +``` + +## License + +[MIT](https://github.com/aheckmann/regexp-clone/blob/master/LICENSE) diff --git a/6-2/node_modules/mongoose/node_modules/regexp-clone/index.js b/6-2/node_modules/mongoose/node_modules/regexp-clone/index.js new file mode 100644 index 0000000..e5850ca --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/regexp-clone/index.js @@ -0,0 +1,20 @@ + +var toString = Object.prototype.toString; + +function isRegExp (o) { + return 'object' == typeof o + && '[object RegExp]' == toString.call(o); +} + +module.exports = exports = function (regexp) { + if (!isRegExp(regexp)) { + throw new TypeError('Not a RegExp'); + } + + var flags = []; + if (regexp.global) flags.push('g'); + if (regexp.multiline) flags.push('m'); + if (regexp.ignoreCase) flags.push('i'); + return new RegExp(regexp.source, flags.join('')); +} + diff --git a/6-2/node_modules/mongoose/node_modules/regexp-clone/package.json b/6-2/node_modules/mongoose/node_modules/regexp-clone/package.json new file mode 100644 index 0000000..29b6d17 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/regexp-clone/package.json @@ -0,0 +1,51 @@ +{ + "name": "regexp-clone", + "version": "0.0.1", + "description": "Clone RegExps with options", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/regexp-clone.git" + }, + "keywords": [ + "RegExp", + "clone" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.8.1" + }, + "readme": "#regexp-clone\n==============\n\nClones RegExps with flag preservation\n\n```js\nvar regexpClone = require('regexp-clone');\n\nvar a = /somethin/g;\nconsole.log(a.global); // true\n\nvar b = regexpClone(a);\nconsole.log(b.global); // true\n```\n\n## License\n\n[MIT](https://github.com/aheckmann/regexp-clone/blob/master/LICENSE)\n", + "readmeFilename": "README.md", + "_id": "regexp-clone@0.0.1", + "dist": { + "shasum": "a7c2e09891fdbf38fbb10d376fb73003e68ac589", + "tarball": "http://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz" + }, + "_from": "regexp-clone@0.0.1", + "_npmVersion": "1.2.14", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "directories": {}, + "_shasum": "a7c2e09891fdbf38fbb10d376fb73003e68ac589", + "_resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz", + "bugs": { + "url": "https://github.com/aheckmann/regexp-clone/issues" + }, + "homepage": "https://github.com/aheckmann/regexp-clone#readme" +} diff --git a/6-2/node_modules/mongoose/node_modules/regexp-clone/test/index.js b/6-2/node_modules/mongoose/node_modules/regexp-clone/test/index.js new file mode 100644 index 0000000..264a776 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/regexp-clone/test/index.js @@ -0,0 +1,112 @@ + +var assert = require('assert') +var clone = require('../'); + +describe('regexp-clone', function(){ + function hasEqualSource (a, b) { + assert.ok(a !== b); + assert.equal(a.source, b.source); + } + + function isInsensitive (a) { + assert.ok(a.ignoreCase); + } + + function isGlobal (a) { + assert.ok(a.global); + } + + function isMultiline (a) { + assert.ok(a.multiline); + } + + function insensitiveFlag (a) { + var b = clone(a); + hasEqualSource(a, b); + isInsensitive(a); + isInsensitive(b); + } + + function globalFlag (a) { + var b = clone(a); + hasEqualSource(a, b); + isGlobal(a); + isGlobal(b); + } + + function multilineFlag (a) { + var b = clone(a); + hasEqualSource(a, b); + isMultiline(a); + isMultiline(b); + } + + describe('literals', function(){ + it('insensitive flag', function(done){ + var a = /hello/i; + insensitiveFlag(a); + done(); + }) + it('global flag', function(done){ + var a = /hello/g; + globalFlag(a); + done(); + }) + it('multiline flag', function(done){ + var a = /hello/m; + multilineFlag(a); + done(); + }) + it('no flags', function(done){ + var a = /hello/; + var b = clone(a); + hasEqualSource(a, b); + assert.ok(!a.insensitive); + assert.ok(!a.global); + assert.ok(!a.global); + done(); + }) + it('all flags', function(done){ + var a = /hello/gim; + insensitiveFlag(a); + globalFlag(a); + multilineFlag(a); + done(); + }) + }) + + describe('instances', function(){ + it('insensitive flag', function(done){ + var a = new RegExp('hello', 'i'); + insensitiveFlag(a); + done(); + }) + it('global flag', function(done){ + var a = new RegExp('hello', 'g'); + globalFlag(a); + done(); + }) + it('multiline flag', function(done){ + var a = new RegExp('hello', 'm'); + multilineFlag(a); + done(); + }) + it('no flags', function(done){ + var a = new RegExp('hmm'); + var b = clone(a); + hasEqualSource(a, b); + assert.ok(!a.insensitive); + assert.ok(!a.global); + assert.ok(!a.global); + done(); + }) + it('all flags', function(done){ + var a = new RegExp('hello', 'gim'); + insensitiveFlag(a); + globalFlag(a); + multilineFlag(a); + done(); + }) + }) +}) + diff --git a/6-2/node_modules/mongoose/node_modules/sliced/History.md b/6-2/node_modules/mongoose/node_modules/sliced/History.md new file mode 100644 index 0000000..e45cefe --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/sliced/History.md @@ -0,0 +1,41 @@ + +1.0.1 / 2015-07-14 +================== + + * fixed; missing file introduced in 4f5cea1 + +1.0.0 / 2015-07-12 +================== + + * Remove unnecessary files from npm package - #6 via joaquimserafim + * updated readme stats + +0.0.5 / 2013-02-05 +================== + + * optimization: remove use of arguments [jkroso](https://github.com/jkroso) + * add scripts to component.json [jkroso](https://github.com/jkroso) + * tests; remove time for travis + +0.0.4 / 2013-01-07 +================== + + * added component.json #1 [jkroso](https://github.com/jkroso) + * reversed array loop #1 [jkroso](https://github.com/jkroso) + * remove fn params + +0.0.3 / 2012-09-29 +================== + + * faster with negative start args + +0.0.2 / 2012-09-29 +================== + + * support full [].slice semantics + +0.0.1 / 2012-09-29 +=================== + + * initial release + diff --git a/6-2/node_modules/mongoose/node_modules/sliced/LICENSE b/6-2/node_modules/mongoose/node_modules/sliced/LICENSE new file mode 100644 index 0000000..38c529d --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/sliced/LICENSE @@ -0,0 +1,22 @@ +(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/6-2/node_modules/mongoose/node_modules/sliced/README.md b/6-2/node_modules/mongoose/node_modules/sliced/README.md new file mode 100644 index 0000000..b6ff85e --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/sliced/README.md @@ -0,0 +1,62 @@ +#sliced +========== + +A faster alternative to `[].slice.call(arguments)`. + +[![Build Status](https://secure.travis-ci.org/aheckmann/sliced.png)](http://travis-ci.org/aheckmann/sliced) + +Example output from [benchmark.js](https://github.com/bestiejs/benchmark.js) + + Array.prototype.slice.call x 1,401,820 ops/sec ±2.16% (90 runs sampled) + [].slice.call x 1,313,116 ops/sec ±2.04% (96 runs sampled) + cached slice.call x 10,297,910 ops/sec ±1.81% (96 runs sampled) + sliced x 19,906,019 ops/sec ±1.23% (89 runs sampled) + fastest is sliced + + Array.prototype.slice.call(arguments, 1) x 1,373,238 ops/sec ±1.84% (95 runs sampled) + [].slice.call(arguments, 1) x 1,395,336 ops/sec ±1.36% (93 runs sampled) + cached slice.call(arguments, 1) x 9,926,018 ops/sec ±1.67% (92 runs sampled) + sliced(arguments, 1) x 20,747,990 ops/sec ±1.16% (93 runs sampled) + fastest is sliced(arguments, 1) + + Array.prototype.slice.call(arguments, -1) x 1,319,908 ops/sec ±2.12% (91 runs sampled) + [].slice.call(arguments, -1) x 1,336,170 ops/sec ±1.33% (97 runs sampled) + cached slice.call(arguments, -1) x 10,078,718 ops/sec ±1.21% (98 runs sampled) + sliced(arguments, -1) x 20,471,474 ops/sec ±1.81% (92 runs sampled) + fastest is sliced(arguments, -1) + + Array.prototype.slice.call(arguments, -2, -10) x 1,369,246 ops/sec ±1.68% (97 runs sampled) + [].slice.call(arguments, -2, -10) x 1,387,935 ops/sec ±1.70% (95 runs sampled) + cached slice.call(arguments, -2, -10) x 9,593,428 ops/sec ±1.23% (97 runs sampled) + sliced(arguments, -2, -10) x 23,178,931 ops/sec ±1.70% (92 runs sampled) + fastest is sliced(arguments, -2, -10) + + Array.prototype.slice.call(arguments, -2, -1) x 1,441,300 ops/sec ±1.26% (98 runs sampled) + [].slice.call(arguments, -2, -1) x 1,410,326 ops/sec ±1.96% (93 runs sampled) + cached slice.call(arguments, -2, -1) x 9,854,419 ops/sec ±1.02% (97 runs sampled) + sliced(arguments, -2, -1) x 22,550,801 ops/sec ±1.86% (91 runs sampled) + fastest is sliced(arguments, -2, -1) + +_Benchmark [source](https://github.com/aheckmann/sliced/blob/master/bench.js)._ + +##Usage + +`sliced` accepts the same arguments as `Array#slice` so you can easily swap it out. + +```js +function zing () { + var slow = [].slice.call(arguments, 1, 8); + var args = slice(arguments, 1, 8); + + var slow = Array.prototype.slice.call(arguments); + var args = slice(arguments); + // etc +} +``` + +## install + + npm install sliced + + +[LICENSE](https://github.com/aheckmann/sliced/blob/master/LICENSE) diff --git a/6-2/node_modules/mongoose/node_modules/sliced/index.js b/6-2/node_modules/mongoose/node_modules/sliced/index.js new file mode 100644 index 0000000..d88c85b --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/sliced/index.js @@ -0,0 +1,33 @@ + +/** + * An Array.prototype.slice.call(arguments) alternative + * + * @param {Object} args something with a length + * @param {Number} slice + * @param {Number} sliceEnd + * @api public + */ + +module.exports = function (args, slice, sliceEnd) { + var ret = []; + var len = args.length; + + if (0 === len) return ret; + + var start = slice < 0 + ? Math.max(0, slice + len) + : slice || 0; + + if (sliceEnd !== undefined) { + len = sliceEnd < 0 + ? sliceEnd + len + : sliceEnd + } + + while (len-- > start) { + ret[len - start] = args[len]; + } + + return ret; +} + diff --git a/6-2/node_modules/mongoose/node_modules/sliced/package.json b/6-2/node_modules/mongoose/node_modules/sliced/package.json new file mode 100644 index 0000000..8eaec88 --- /dev/null +++ b/6-2/node_modules/mongoose/node_modules/sliced/package.json @@ -0,0 +1,60 @@ +{ + "name": "sliced", + "version": "1.0.1", + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "main": "index.js", + "files": [ + "LICENSE", + "README.md", + "index.js" + ], + "scripts": { + "test": "make test" + }, + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/sliced.git" + }, + "keywords": [ + "arguments", + "slice", + "array" + ], + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "license": "MIT", + "devDependencies": { + "mocha": "1.5.0", + "benchmark": "~1.0.0" + }, + "dependencies": {}, + "gitHead": "e7c989016d2062995cd102322b65784ba8977ee3", + "bugs": { + "url": "https://github.com/aheckmann/sliced/issues" + }, + "homepage": "https://github.com/aheckmann/sliced", + "_id": "sliced@1.0.1", + "_shasum": "0b3a662b5d04c3177b1926bea82b03f837a2ef41", + "_from": "sliced@1.0.1", + "_npmVersion": "2.8.3", + "_nodeVersion": "1.8.1", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "dist": { + "shasum": "0b3a662b5d04c3177b1926bea82b03f837a2ef41", + "tarball": "http://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/sliced/-/sliced-1.0.1.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/6-2/node_modules/mongoose/package.json b/6-2/node_modules/mongoose/package.json new file mode 100644 index 0000000..9d66d03 --- /dev/null +++ b/6-2/node_modules/mongoose/package.json @@ -0,0 +1,134 @@ +{ + "name": "mongoose", + "description": "Mongoose MongoDB ODM", + "version": "4.4.3", + "author": { + "name": "Guillermo Rauch", + "email": "guillermo@learnboost.com" + }, + "keywords": [ + "mongodb", + "document", + "model", + "schema", + "database", + "odm", + "data", + "datastore", + "query", + "nosql", + "orm", + "db" + ], + "license": "MIT", + "dependencies": { + "async": "1.5.2", + "bson": "0.4.21", + "hooks-fixed": "1.1.0", + "kareem": "1.0.1", + "mongodb": "2.1.6", + "mpath": "0.2.1", + "mpromise": "0.5.5", + "mquery": "1.6.3", + "ms": "0.7.1", + "muri": "1.1.0", + "regexp-clone": "0.0.1", + "sliced": "1.0.1" + }, + "devDependencies": { + "acquit": "0.4.1", + "acquit-ignore": "0.0.3", + "benchmark": "2.0.0", + "bluebird": "3.1.4", + "co": "4.6.0", + "dox": "0.3.1", + "eslint": "2.0.0-beta.3", + "highlight.js": "7.0.1", + "istanbul": "0.4.2", + "jade": "0.26.3", + "markdown": "0.3.1", + "marked": "0.3.5", + "mocha": "2.3.4", + "node-static": "0.7.7", + "power-assert": "1.2.0", + "q": "1.4.1", + "tbd": "0.6.4", + "uglify-js": "2.6.1", + "underscore": "1.8.3" + }, + "browserDependencies": { + "browserify": "4.1.10", + "chai": "3.5.0", + "karma": "0.12.16", + "karma-chai": "0.1.0", + "karma-mocha": "0.1.4", + "karma-chrome-launcher": "0.1.4", + "karma-sauce-launcher": "0.2.8" + }, + "directories": { + "lib": "./lib/mongoose" + }, + "scripts": { + "fix-lint": "eslint . --fix", + "install-browser": "npm install `node format_deps.js`", + "test": "mocha test/*.test.js test/**/*.test.js", + "posttest": "eslint . --quiet", + "test-cov": "istanbul cover --report text --report html _mocha test/*.test.js" + }, + "main": "./index.js", + "engines": { + "node": ">=0.6.19" + }, + "bugs": { + "url": "https://github.com/Automattic/mongoose/issues/new", + "email": "mongoose-orm@googlegroups.com" + }, + "repository": { + "type": "git", + "url": "git://github.com/Automattic/mongoose.git" + }, + "homepage": "http://mongoosejs.com", + "browser": "lib/browser.js", + "gitHead": "059520ff1c2242c02e1bf9f00ddb9a962947dd37", + "_id": "mongoose@4.4.3", + "_shasum": "0c7aeb37615cb631307cd2dff5d76c8681dac9ea", + "_from": "mongoose@*", + "_npmVersion": "3.3.12", + "_nodeVersion": "5.4.1", + "_npmUser": { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + "dist": { + "shasum": "0c7aeb37615cb631307cd2dff5d76c8681dac9ea", + "tarball": "http://registry.npmjs.org/mongoose/-/mongoose-4.4.3.tgz" + }, + "maintainers": [ + { + "name": "rauchg", + "email": "rauchg@gmail.com" + }, + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "vkarpov15", + "email": "val@karpov.io" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + } + ], + "_npmOperationalInternal": { + "host": "packages-6-west.internal.npmjs.com", + "tmp": "tmp/mongoose-4.4.3.tgz_1455061137802_0.8885454896371812" + }, + "_resolved": "https://registry.npmjs.org/mongoose/-/mongoose-4.4.3.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/6-2/node_modules/mongoose/release-items.md b/6-2/node_modules/mongoose/release-items.md new file mode 100644 index 0000000..3dc270e --- /dev/null +++ b/6-2/node_modules/mongoose/release-items.md @@ -0,0 +1,29 @@ +## mongoose release procedure + +1. tests must pass +2. update package.json version +3. update History.md using `git changelog` or similar. list the related ticket(s) # as well as a link to the github user who fixed it if applicable. +4. git commit -m 'release x.x.x' +5. git tag x.x.x +6. git push origin BRANCH --tags && npm publish +7. update mongoosejs.com (see "updating the website" below) +8. announce to google groups - include the relevant change log and links to issues +9. tweet google group announcement from [@mongoosejs](https://twitter.com/mongoosejs) +10. change package.json version to next patch version suffixed with '-pre' and commit "now working on x.x.x" +11. if this is a legacy release, `git merge` changes into master. + +## updating the website + +For 4.x + +0. Change to the master branch +1. execute `make docs` (when this process completes you'll be on the gh-pages branch) +2. `git commit -a -m 'website; regen <4.x.x>'` +3. `git push origin gh-pages` + +For 3.8.x: + +0. Change to the 3.8.x branch +1. execute `make docs_legacy` (when this process completes you'll be on the gh-pages branch) +2. `git commit -a -m 'website; regen '` +3. `git push origin gh-pages` diff --git a/6-2/node_modules/mongoose/static.js b/6-2/node_modules/mongoose/static.js new file mode 100644 index 0000000..d84e59f --- /dev/null +++ b/6-2/node_modules/mongoose/static.js @@ -0,0 +1,24 @@ + +var static = require('node-static'); +var server = new static.Server('.', {cache: 0}); + +require('http').createServer(function(req, res) { + if (req.url === '/favicon.ico') { + req.destroy(); + res.statusCode = 204; + return res.end(); + } + + req.on('end', function() { + server.serve(req, res, function(err) { + if (err) { + console.error(err, req.url); + res.writeHead(err.status, err.headers); + res.end(); + } + }); + }); + req.resume(); +}).listen(8088); + +console.error('now listening on http://localhost:8088'); diff --git a/6-2/node_modules/mongoose/website.js b/6-2/node_modules/mongoose/website.js new file mode 100644 index 0000000..a1186a5 --- /dev/null +++ b/6-2/node_modules/mongoose/website.js @@ -0,0 +1,87 @@ +var fs = require('fs'); +var jade = require('jade'); +var package = require('./package'); +var hl = require('./docs/helpers/highlight'); +var linktype = require('./docs/helpers/linktype'); +var href = require('./docs/helpers/href'); +var klass = require('./docs/helpers/klass'); + +// add custom jade filters +require('./docs/helpers/filters')(jade); + +function getVersion() { + var hist = fs.readFileSync('./History.md', 'utf8').replace(/\r/g, '\n').split('\n'); + for (var i = 0; i < hist.length; ++i) { + var line = (hist[i] || '').trim(); + if (!line) { + continue; + } + var match = /^\s*([^\s]+)\s/.exec(line); + if (match && match[1]) { + return match[1]; + } + } + throw new Error('no match found'); +} + +function getUnstable(ver) { + ver = ver.replace('-pre'); + var spl = ver.split('.'); + spl = spl.map(function(i) { + return parseInt(i, 10); + }); + spl[1]++; + spl[2] = 'x'; + return spl.join('.'); +} + +// use last release +package.version = getVersion(); +package.unstable = getUnstable(package.version); + +var filemap = require('./docs/source'); +var files = Object.keys(filemap); + +function jadeify(filename, options, newfile) { + options = options || {}; + options.package = package; + options.hl = hl; + options.linktype = linktype; + options.href = href; + options.klass = klass; + jade.renderFile(filename, options, function(err, str) { + if (err) { + console.error(err.stack); + return; + } + + newfile = newfile || filename.replace('.jade', '.html'); + fs.writeFile(newfile, str, function(err) { + if (err) { + console.error('could not write', err.stack); + } else { + console.log('%s : rendered ', new Date, newfile); + } + }); + }); +} + +files.forEach(function(file) { + var filename = __dirname + '/' + file; + jadeify(filename, filemap[file]); + + if (process.argv[2] === '--watch') { + fs.watchFile(filename, {interval: 1000}, function(cur, prev) { + if (cur.mtime > prev.mtime) { + jadeify(filename, filemap[file]); + } + }); + } +}); + +var acquit = require('./docs/source/acquit'); +var acquitFiles = Object.keys(acquit); +acquitFiles.forEach(function(file) { + var filename = __dirname + '/docs/acquit.jade'; + jadeify(filename, acquit[file], __dirname + '/docs/' + file); +}); diff --git a/6-2/node_modules/superagent/.npmignore b/6-2/node_modules/superagent/.npmignore new file mode 100644 index 0000000..90d998b --- /dev/null +++ b/6-2/node_modules/superagent/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +*.sock +lib-cov +coverage.html diff --git a/6-2/node_modules/superagent/.travis.yml b/6-2/node_modules/superagent/.travis.yml new file mode 100644 index 0000000..0262c01 --- /dev/null +++ b/6-2/node_modules/superagent/.travis.yml @@ -0,0 +1,18 @@ +sudo: false +language: node_js +node_js: + - "5.4" + - "4.2" + - "0.12" + - "0.10" + - "iojs" + +env: + global: + - SAUCE_USERNAME='shtylman-superagent' + - SAUCE_ACCESS_KEY='39a45464-cb1d-4b8d-aa1f-83c7c04fa673' + +matrix: + include: + - node_js: "4.2" + env: BROWSER=1 diff --git a/6-2/node_modules/superagent/.zuul.yml b/6-2/node_modules/superagent/.zuul.yml new file mode 100644 index 0000000..031c56a --- /dev/null +++ b/6-2/node_modules/superagent/.zuul.yml @@ -0,0 +1,15 @@ +ui: mocha-bdd +server: ./test/support/server.js +browsers: + - name: chrome + version: latest + - name: firefox + version: latest + - name: safari + version: latest + - name: iphone + version: latest + - name: android + version: latest + - name: ie + version: 9..latest diff --git a/6-2/node_modules/superagent/Contributing.md b/6-2/node_modules/superagent/Contributing.md new file mode 100644 index 0000000..1eca592 --- /dev/null +++ b/6-2/node_modules/superagent/Contributing.md @@ -0,0 +1,7 @@ +When submitting a PR, your chance of acceptance increases if you do the following: + +* Code style is consistent with existing in the file. +* Tests are passing (client and server). +* You add a test for the failing issue you are fixing. +* Code changes are focused on the area of discussion. +* Do not rebuild the distribution files or increment version numbers. diff --git a/6-2/node_modules/superagent/History.md b/6-2/node_modules/superagent/History.md new file mode 100644 index 0000000..8483f96 --- /dev/null +++ b/6-2/node_modules/superagent/History.md @@ -0,0 +1,532 @@ +# 1.7.2 (2016-01-26) + + * Fix case-sensitivity of header fields introduced by a4ddd6a. (Edward J. Jinotti) + * bump extend dependency, as former version did not contain any license information (Lukas Eipert) + +# 1.7.1 (2016-01-21) + + * Fixed a conflict with express when using npm 3.x (Glenn) + * Fixed redirects after a multipart/form-data POST request (cyclist2) + +# 1.7.0 (2016-01-18) + + * When attaching files, read default filename from the `File` object (JD Isaacks) + * Add `direction` property to `progress` events (Joseph Dykstra) + * Update component-emitter & formidable (Kornel Lesiński) + * Don't re-encode query string needlessly (Ruben Verborgh) + * ensure querystring is appended when doing `stream.pipe(request)` (Keith Grennan) + * change set header function, not call `this.request()` until call `this.end()` (vicanso) + * Add no-op `withCredentials` to Node API (markdalgleish) + * fix `delete` breaking on ie8 (kenjiokabe) + * Don't let request error override responses (Clay Reimann) + * Increased number of tests shared between node and client (Kornel Lesiński) + +# 1.6.0/1.6.1 (2015-12-09) + + * avoid misleading CORS error message + * added 'progress' event on file/form upload in Node (Olivier Lalonde) + * return raw response if the response parsing fails (Rei Colina) + * parse content-types ending with `+json` as JSON (Eiryyy) + * fix to avoid throwing errors on aborted requests (gjurgens) + * retain cookies on redirect when hosts match (Tom Conroy) + * added Bower manifest (Johnny Freeman) + * upgrade to latest cookiejar (Andy Burke) + +# 1.5.0 (2015-11-30) + + * encode array values as `key=1&key=2&key=3` etc... (aalpern, Davis Kim) + * avoid the error which is omitted from 'socket hang up' + * faster JSON parsing, handling of zlib errors (jbellenger) + * fix IE11 sends 'undefined' string if data was undefined (Vadim Goncharov) + * alias `del()` method as `delete()` (Aaron Krause) + * revert Request#parse since it was actually Response#parse + +# 1.4.0 (2015-09-14) + + * add Request#parse method to client library + * add missing statusCode in client response + * don't apply JSON heuristics if a valid parser is found + * fix detection of root object for webworkers + +# 1.3.0 (2015-08-05) + + * fix incorrect content-length of data set to buffer + * serialize request data takes into account charsets + * add basic promise support via a `then` function + +# 1.2.0 (2015-04-13) + + * add progress events to downlodas + * make usable in webworkers + * add support for 308 redirects + * update node-form-data dependency + * update to work in react native + * update node-mime dependency + +# 1.1.0 (2015-03-13) + + * Fix responseType checks without xhr2 and ie9 tests (rase-) + * errors have .status and .response fields if applicable (defunctzombie) + * fix end callback called before saving cookies (rase-) + +1.0.0 / 2015-03-08 +================== + + * All non-200 responses are treated as errors now. (The callback is called with an error when the response has a status < 200 or >= 300 now. In previous versions this would not have raised an error and the client would have to check the `res` object. See [#283](https://github.com/visionmedia/superagent/issues/283). + * keep timeouts intact across redirects (hopkinsth) + * handle falsy json values (themaarten) + * fire response events in browser version (Schoonology) + * getXHR exported in client version (KidsKilla) + * remove arity check on `.end()` callbacks (defunctzombie) + * avoid setting content-type for host objects (rexxars) + * don't index array strings in querystring (travisjeffery) + * fix pipe() with redirects (cyrilis) + * add xhr2 file download (vstirbu) + * set default response type to text/plain if not specified (warrenseine) + +0.21.0 / 2014-11-11 +================== + + * Trim text before parsing json (gjohnson) + * Update tests to express 4 (gaastonsr) + * Prevent double callback when error is thrown (pgn-vole) + * Fix missing clearTimeout (nickdima) + * Update debug (TooTallNate) + +0.20.0 / 2014-10-02 +================== + + * Add toJSON() to request and response instances. (yields) + * Prevent HEAD requests from getting parsed. (gjohnson) + * Update debug. (TooTallNate) + +0.19.1 / 2014-09-24 +================== + + * Fix basic auth issue when password is falsey value. (gjohnson) + +0.19.0 / 2014-09-24 +================== + + * Add unset() to browser. (shesek) + * Prefer XHR over ActiveX. (omeid) + * Catch parse errors. (jacwright) + * Update qs dependency. (wercker) + * Add use() to node. (Financial-Times) + * Add response text to errors. (yields) + * Don't send empty cookie headers. (undoZen) + * Don't parse empty response bodies. (DveMac) + * Use hostname when setting cookie host. (prasunsultania) + +0.18.2 / 2014-07-12 +================== + + * Handle parser errors. (kof) + * Ensure not to use default parsers when there is a user defined one. (kof) + +0.18.1 / 2014-07-05 +================== + + * Upgrade cookiejar dependency (juanpin) + * Support image mime types (nebulade) + * Make .agent chainable (kof) + * Upgrade debug (TooTallNate) + * Fix docs (aheckmann) + +0.18.0 / 2014-04-29 +=================== + +* Use "form-data" module for the multipart/form-data implementation. (TooTallNate) +* Add basic `field()` and `attach()` functions for HTML5 FormData. (TooTallNate) +* Deprecate `part()`. (TooTallNate) +* Set default user-agent header. (bevacqua) +* Add `unset()` method for removing headers. (bevacqua) +* Update cookiejar. (missinglink) +* Fix response error formatting. (shesek) + +0.17.0 / 2014-03-06 +=================== + + * supply uri malformed error to the callback (yields) + * add request event (yields) + * allow simple auth (yields) + * add request event (yields) + * switch to component/reduce (visionmedia) + * fix part content-disposition (mscdex) + * add browser testing via zuul (defunctzombie) + * adds request.use() (johntron) + +0.16.0 / 2014-01-07 +================== + + * remove support for 0.6 (superjoe30) + * fix CORS withCredentials (wejendorp) + * add "test" script (superjoe30) + * add request .accept() method (nickl-) + * add xml to mime types mappings (nickl-) + * fix parse body error on HEAD requests (gjohnson) + * fix documentation typos (matteofigus) + * fix content-type + charset (bengourley) + * fix null values on query parameters (cristiandouce) + +0.15.7 / 2013-10-19 +================== + + * pin should.js to 1.3.0 due to breaking change in 2.0.x + * fix browserify regression + +0.15.5 / 2013-10-09 +================== + + * add browser field to support browserify + * fix .field() value number support + +0.15.4 / 2013-07-09 +================== + + * node: add a Request#agent() function to set the http Agent to use + +0.15.3 / 2013-07-05 +================== + + * fix .pipe() unzipping on more recent nodes. Closes #240 + * fix passing an empty object to .query() no longer appends "?" + * fix formidable error handling + * update formidable + +0.15.2 / 2013-07-02 +================== + + * fix: emit 'end' when piping. + +0.15.1 / 2013-06-26 +================== + + * add try/catch around parseLinks + +0.15.0 / 2013-06-25 +================== + + * make `Response#toError()` have a more meaningful `message` + +0.14.9 / 2013-06-15 +================== + + * add debug()s to the node client + * add .abort() method to node client + +0.14.8 / 2013-06-13 +================== + + * set .agent = false always + * remove X-Requested-With. Closes #189 + +0.14.7 / 2013-06-06 +================== + + * fix unzip error handling + +0.14.6 / 2013-05-23 +================== + + * fix HEAD unzip bug + +0.14.5 / 2013-05-23 +================== + + * add flag to ensure the callback is __never__ invoked twice + +0.14.4 / 2013-05-22 +================== + + * add superagent.js build output + * update qs + * update emitter-component + * revert "add browser field to support browserify" see GH-221 + +0.14.3 / 2013-05-18 +================== + + * add browser field to support browserify + +0.14.2/ 2013-05-07 +================== + + * add host object check to fix serialization of File/Blobs etc as json + +0.14.1 / 2013-04-09 +================== + + * update qs + +0.14.0 / 2013-04-02 +================== + + * add client-side basic auth + * fix retaining of .set() header field case + +0.13.0 / 2013-03-13 +================== + + * add progress events to client + * add simple example + * add res.headers as alias of res.header for browser client + * add res.get(field) to node/client + +0.12.4 / 2013-02-11 +================== + + * fix get content-type even if can't get other headers in firefox. fixes #181 + +0.12.3 / 2013-02-11 +================== + + * add quick "progress" event support + +0.12.2 / 2013-02-04 +================== + + * add test to check if response acts as a readable stream + * add ReadableStream in the Response prototype. + * add test to assert correct redirection when the host changes in the location header. + * add default Accept-Encoding. Closes #155 + * fix req.pipe() return value of original stream for node parity. Closes #171 + * remove the host header when cleaning headers to properly follow the redirection. + +0.12.1 / 2013-01-10 +================== + + * add x-domain error handling + +0.12.0 / 2013-01-04 +================== + + * add header persistence on redirects + +0.11.0 / 2013-01-02 +================== + + * add .error Error object. Closes #156 + * add forcing of res.text removal for FF HEAD responses. Closes #162 + * add reduce component usage. Closes #90 + * move better-assert dep to development deps + +0.10.0 / 2012-11-14 +================== + + * add req.timeout(ms) support for the client + +0.9.10 / 2012-11-14 +================== + + * fix client-side .query(str) support + +0.9.9 / 2012-11-14 +================== + + * add .parse(fn) support + * fix socket hangup with dates in querystring. Closes #146 + * fix socket hangup "error" event when a callback of arity 2 is provided + +0.9.8 / 2012-11-03 +================== + + * add emission of error from `Request#callback()` + * add a better fix for nodes weird socket hang up error + * add PUT/POST/PATCH data support to client short-hand functions + * add .license property to component.json + * change client portion to build using component(1) + * fix GET body support [guille] + +0.9.7 / 2012-10-19 +================== + + * fix `.buffer()` `res.text` when no parser matches + +0.9.6 / 2012-10-17 +================== + + * change: use `this` when `window` is undefined + * update to new component spec [juliangruber] + * fix emission of "data" events for compressed responses without encoding. Closes #125 + +0.9.5 / 2012-10-01 +================== + + * add field name to .attach() + * add text "parser" + * refactor isObject() + * remove wtf isFunction() helper + +0.9.4 / 2012-09-20 +================== + + * fix `Buffer` responses [TooTallNate] + * fix `res.type` when a "type" param is present [TooTallNate] + +0.9.3 / 2012-09-18 +================== + + * remove __GET__ `.send()` == `.query()` special-case (__API__ change !!!) + +0.9.2 / 2012-09-17 +================== + + * add `.aborted` prop + * add `.abort()`. Closes #115 + +0.9.1 / 2012-09-07 +================== + + * add `.forbidden` response property + * add component.json + * change emitter-component to 0.0.5 + * fix client-side tests + +0.9.0 / 2012-08-28 +================== + + * add `.timeout(ms)`. Closes #17 + +0.8.2 / 2012-08-28 +================== + + * fix pathname relative redirects. Closes #112 + +0.8.1 / 2012-08-21 +================== + + * fix redirects when schema is specified + +0.8.0 / 2012-08-19 +================== + + * add `res.buffered` flag + * add buffering of text/*, json and forms only by default. Closes #61 + * add `.buffer(false)` cancellation + * add cookie jar support [hunterloftis] + * add agent functionality [hunterloftis] + +0.7.0 / 2012-08-03 +================== + + * allow `query()` to be called after the internal `req` has been created [tootallnate] + +0.6.0 / 2012-07-17 +================== + + * add `res.send('foo=bar')` default of "application/x-www-form-urlencoded" + +0.5.1 / 2012-07-16 +================== + + * add "methods" dep + * add `.end()` arity check to node callbacks + * fix unzip support due to weird node internals + +0.5.0 / 2012-06-16 +================== + + * Added "Link" response header field parsing, exposing `res.links` + +0.4.3 / 2012-06-15 +================== + + * Added 303, 305 and 307 as redirect status codes [slaskis] + * Fixed passing an object as the url + +0.4.2 / 2012-06-02 +================== + + * Added component support + * Fixed redirect data + +0.4.1 / 2012-04-13 +================== + + * Added HTTP PATCH support + * Fixed: GET / HEAD when following redirects. Closes #86 + * Fixed Content-Length detection for multibyte chars + +0.4.0 / 2012-03-04 +================== + + * Added `.head()` method [browser]. Closes #78 + * Added `make test-cov` support + * Added multipart request support. Closes #11 + * Added all methods that node supports. Closes #71 + * Added "response" event providing a Response object. Closes #28 + * Added `.query(obj)`. Closes #59 + * Added `res.type` (browser). Closes #54 + * Changed: default `res.body` and `res.files` to {} + * Fixed: port existing query-string fix (browser). Closes #57 + +0.3.0 / 2012-01-24 +================== + + * Added deflate/gzip support [guillermo] + * Added `res.type` (Content-Type void of params) + * Added `res.statusCode` to mirror node + * Added `res.headers` to mirror node + * Changed: parsers take callbacks + * Fixed optional schema support. Closes #49 + +0.2.0 / 2012-01-05 +================== + + * Added url auth support + * Added `.auth(username, password)` + * Added basic auth support [node]. Closes #41 + * Added `make test-docs` + * Added guillermo's EventEmitter. Closes #16 + * Removed `Request#data()` for SS, renamed to `send()` + * Removed `Request#data()` from client, renamed to `send()` + * Fixed array support. [browser] + * Fixed array support. Closes #35 [node] + * Fixed `EventEmitter#emit()` + +0.1.3 / 2011-10-25 +================== + + * Added error to callback + * Bumped node dep for 0.5.x + +0.1.2 / 2011-09-24 +================== + + * Added markdown documentation + * Added `request(url[, fn])` support to the client + * Added `qs` dependency to package.json + * Added options for `Request#pipe()` + * Added support for `request(url, callback)` + * Added `request(url)` as shortcut for `request.get(url)` + * Added `Request#pipe(stream)` + * Added inherit from `Stream` + * Added multipart support + * Added ssl support (node) + * Removed Content-Length field from client + * Fixed buffering, `setEncoding()` to utf8 [reported by stagas] + * Fixed "end" event when piping + +0.1.1 / 2011-08-20 +================== + + * Added `res.redirect` flag (node) + * Added redirect support (node) + * Added `Request#redirects(n)` (node) + * Added `.set(object)` header field support + * Fixed `Content-Length` support + +0.1.0 / 2011-08-09 +================== + + * Added support for multiple calls to `.data()` + * Added support for `.get(uri, obj)` + * Added GET `.data()` querystring support + * Added IE{6,7,8} support [alexyoung] + +0.0.1 / 2011-08-05 +================== + + * Initial commit + diff --git a/6-2/node_modules/superagent/LICENSE b/6-2/node_modules/superagent/LICENSE new file mode 100644 index 0000000..1b188ba --- /dev/null +++ b/6-2/node_modules/superagent/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/6-2/node_modules/superagent/Makefile b/6-2/node_modules/superagent/Makefile new file mode 100644 index 0000000..bac2be5 --- /dev/null +++ b/6-2/node_modules/superagent/Makefile @@ -0,0 +1,57 @@ + +NODETESTS ?= test/*.js test/node/*.js +BROWSERTESTS ?= test/*.js test/client/*.js +REPORTER = spec + +all: superagent.js + +test: + @if [ "x$(BROWSER)" = "x" ]; then make test-node; else make test-browser; fi + +test-node: + @NODE_ENV=test NODE_TLS_REJECT_UNAUTHORIZED=0 ./node_modules/.bin/mocha \ + --require should \ + --reporter $(REPORTER) \ + --timeout 5000 \ + --growl \ + $(NODETESTS) + +test-cov: lib-cov + SUPERAGENT_COV=1 $(MAKE) test REPORTER=html-cov > coverage.html + +test-browser: + ./node_modules/.bin/zuul -- $(BROWSERTESTS) + +test-browser-local: + ./node_modules/.bin/zuul --local 4000 -- $(BROWSERTESTS) + +lib-cov: + jscoverage lib lib-cov + +superagent.js: lib/node/*.js lib/node/parsers/*.js + @./node_modules/.bin/browserify \ + --standalone superagent \ + --outfile superagent.js . + +test-server: + @node test/server + +docs: index.html test-docs + +index.html: docs/index.md + marked < $< \ + | cat docs/head.html - docs/tail.html \ + > $@ + +docclean: + rm -f index.html test.html + +test-docs: + make test REPORTER=doc \ + | cat docs/head.html - docs/tail.html \ + > test.html + +clean: + rm -fr superagent.js components + +.PHONY: test-cov test docs test-docs clean test-browser-local diff --git a/6-2/node_modules/superagent/Readme.md b/6-2/node_modules/superagent/Readme.md new file mode 100644 index 0000000..56eac0c --- /dev/null +++ b/6-2/node_modules/superagent/Readme.md @@ -0,0 +1,113 @@ +# SuperAgent [![Build Status](https://travis-ci.org/visionmedia/superagent.svg?branch=master)](https://travis-ci.org/visionmedia/superagent) + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/shtylman-superagent.svg)](https://saucelabs.com/u/shtylman-superagent) + +SuperAgent is a small progressive __client-side__ HTTP request library, and __Node.js__ module with the same API, sporting many high-level HTTP client features. View the [docs](http://visionmedia.github.io/superagent/). + +![super agent](http://f.cl.ly/items/3d282n3A0h0Z0K2w0q2a/Screenshot.png) + +## Installation + +node: + +``` +$ npm install superagent +``` + +component: + +``` +$ component install visionmedia/superagent +``` + +Works with [browserify](https://github.com/substack/node-browserify) and should work with [webpack](https://github.com/visionmedia/superagent/wiki/Superagent-for-Webpack) + +```js +request + .post('/api/pet') + .send({ name: 'Manny', species: 'cat' }) + .set('X-API-Key', 'foobar') + .set('Accept', 'application/json') + .end(function(err, res){ + // Calling the end function will send the request + }); +``` + +## Supported browsers + +Tested browsers: + +- Latest Android +- Latest Firefox +- Latest Chrome +- IE9 through latest +- Latest iPhone +- Latest Safari + +Even though IE9 is supported, a polyfill `window.btoa` is needed to use basic auth. + +# Plugins + +Superagent is easily extended via plugins. + +```js +var nocache = require('superagent-no-cache'); +var request = require('superagent'); +var prefix = require('superagent-prefix')('/static'); + +request +.get('/some-url') +.use(prefix) // Prefixes *only* this request +.use(nocache) // Prevents caching of *only* this request +.end(function(err, res){ + // Do something +}); +``` + +Existing plugins: + * [superagent-no-cache](https://github.com/johntron/superagent-no-cache) - prevents caching by including Cache-Control header + * [superagent-prefix](https://github.com/johntron/superagent-prefix) - prefixes absolute URLs (useful in test environment) + * [superagent-mock](https://github.com/M6Web/superagent-mock) - simulate HTTP calls by returning data fixtures based on the requested URL + * [superagent-mocker](https://github.com/shuvalov-anton/superagent-mocker) — simulate REST API + * [superagent-cache](https://github.com/jpodwys/superagent-cache) - superagent with built-in, flexible caching + * [superagent-jsonapify](https://github.com/alex94puchades/superagent-jsonapify) - A lightweight [json-api](http://jsonapi.org/format/) client addon for superagent + * [superagent-serializer](https://github.com/zzarcon/superagent-serializer) - Converts server payload into different cases + +Please prefix your plugin with `superagent-*` so that it can easily be found by others. + +For superagent extensions such as couchdb and oauth visit the [wiki](https://github.com/visionmedia/superagent/wiki). + +## Running node tests + +Install dependencies: + +```shell +$ npm install +``` +Run em! + +```shell +$ make test +``` + +## Running browser tests + +Install dependencies: + +```shell +$ npm install +``` + +Start the test runner: + +```shell +$ make test-browser-local +``` + +Visit `http://localhost:4000/__zuul` in your browser. + +Edit tests and refresh your browser. You do not have to restart the test runner. + +## License + +MIT diff --git a/6-2/node_modules/superagent/bower.json b/6-2/node_modules/superagent/bower.json new file mode 100644 index 0000000..f1f1eb5 --- /dev/null +++ b/6-2/node_modules/superagent/bower.json @@ -0,0 +1,4 @@ +{ + "name": "superagent", + "main": "lib/client.js" +} \ No newline at end of file diff --git a/6-2/node_modules/superagent/component.json b/6-2/node_modules/superagent/component.json new file mode 100644 index 0000000..e5ec7d4 --- /dev/null +++ b/6-2/node_modules/superagent/component.json @@ -0,0 +1,21 @@ +{ + "name": "superagent", + "repo": "visionmedia/superagent", + "description": "awesome http requests", + "version": "1.2.0", + "keywords": [ + "http", + "ajax", + "request", + "agent" + ], + "scripts": [ + "lib/client.js" + ], + "main": "lib/client.js", + "dependencies": { + "component/emitter": "*", + "component/reduce": "*" + }, + "license": "MIT" +} diff --git a/6-2/node_modules/superagent/docs/head.html b/6-2/node_modules/superagent/docs/head.html new file mode 100644 index 0000000..4d3bc50 --- /dev/null +++ b/6-2/node_modules/superagent/docs/head.html @@ -0,0 +1,21 @@ + + + + SuperAgent - Ajax with less suck + + + + + + + + + +
diff --git a/6-2/node_modules/superagent/docs/highlight.js b/6-2/node_modules/superagent/docs/highlight.js new file mode 100644 index 0000000..b37eefb --- /dev/null +++ b/6-2/node_modules/superagent/docs/highlight.js @@ -0,0 +1,17 @@ + +$(function(){ + $('code').each(function(){ + $(this).html(highlight($(this).text())); + }); +}); + +function highlight(js) { + return js + .replace(//g, '>') + .replace(/('.*?')/gm, '$1') + .replace(/(\d+\.\d+)/gm, '$1') + .replace(/(\d+)/gm, '$1') + .replace(/\bnew *(\w+)/gm, 'new $1') + .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') +} \ No newline at end of file diff --git a/6-2/node_modules/superagent/docs/images/bg.png b/6-2/node_modules/superagent/docs/images/bg.png new file mode 100644 index 0000000..ca3d267 Binary files /dev/null and b/6-2/node_modules/superagent/docs/images/bg.png differ diff --git a/6-2/node_modules/superagent/docs/index.md b/6-2/node_modules/superagent/docs/index.md new file mode 100644 index 0000000..3dc9843 --- /dev/null +++ b/6-2/node_modules/superagent/docs/index.md @@ -0,0 +1,448 @@ + +# SuperAgent + + Super Agent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs. It also works with Node.js! + + request + .post('/api/pet') + .send({ name: 'Manny', species: 'cat' }) + .set('X-API-Key', 'foobar') + .set('Accept', 'application/json') + .end(function(err, res){ + if (err || !res.ok) { + alert('Oh no! error'); + } else { + alert('yay got ' + JSON.stringify(res.body)); + } + }); + +## Test documentation + + The following [test documentation](docs/test.html) was generated with [Mocha's](http://visionmedia.github.com/mocha) "doc" reporter, and directly reflects the test suite. This provides an additional source of documentation. + +## Request basics + + A request can be initiated by invoking the appropriate method on the `request` object, then calling `.end()` to send the request. For example a simple GET request: + + request + .get('/search') + .end(function(err, res){ + + }); + + A method string may also be passed: + + request('GET', '/search').end(callback); + + The __node__ client may also provide absolute urls: + + request + .get('http://example.com/search') + .end(function(err, res){ + + }); + + __DELETE__, __HEAD__, __POST__, __PUT__ and other __HTTP__ verbs may also be used, simply change the method name: + + request + .head('/favicon.ico') + .end(function(err, res){ + + }); + + __DELETE__ is a special-case, as it's a reserved word, so the method is named `.del()`: + + request + .del('/user/1') + .end(function(err, res){ + + }); + + The HTTP method defaults to __GET__, so if you wish, the following is valid: + + request('/search', function(err, res){ + + }); + +## Setting header fields + + Setting header fields is simple, invoke `.set()` with a field name and value: + + request + .get('/search') + .set('API-Key', 'foobar') + .set('Accept', 'application/json') + .end(callback); + + You may also pass an object to set several fields in a single call: + + request + .get('/search') + .set({ 'API-Key': 'foobar', Accept: 'application/json' }) + .end(callback); + +## GET requests + + The `.query()` method accepts objects, which when used with the __GET__ method will form a query-string. The following will produce the path `/search?query=Manny&range=1..5&order=desc`. + + request + .get('/search') + .query({ query: 'Manny' }) + .query({ range: '1..5' }) + .query({ order: 'desc' }) + .end(function(err, res){ + + }); + + Or as a single object: + + request + .get('/search') + .query({ query: 'Manny', range: '1..5', order: 'desc' }) + .end(function(err, res){ + + }); + + The `.query()` method accepts strings as well: + + request + .get('/querystring') + .query('search=Manny&range=1..5') + .end(function(err, res){ + + }); + + Or joined: + + request + .get('/querystring') + .query('search=Manny') + .query('range=1..5') + .end(function(err, res){ + + }); + +## HEAD requests + +You can also use the `.query()` method for HEAD requests. The following will produce the path `/users?email=joe@smith.com`. + + request + .head('/users') + .query({ email: 'joe@smith.com' }) + .end(function(err, res){ + + }); + +## POST / PUT requests + + A typical JSON __POST__ request might look a little like the following, where we set the Content-Type header field appropriately, and "write" some data, in this case just a JSON string. + + request.post('/user') + .set('Content-Type', 'application/json') + .send('{"name":"tj","pet":"tobi"}') + .end(callback) + + Since JSON is undoubtably the most common, it's the _default_! The following example is equivalent to the previous. + + request.post('/user') + .send({ name: 'tj', pet: 'tobi' }) + .end(callback) + + Or using multiple `.send()` calls: + + request.post('/user') + .send({ name: 'tj' }) + .send({ pet: 'tobi' }) + .end(callback) + + By default sending strings will set the Content-Type to `application/x-www-form-urlencoded`, + multiple calls will be concatenated with `&`, here resulting in `name=tj&pet=tobi`: + + request.post('/user') + .send('name=tj') + .send('pet=tobi') + .end(callback); + + SuperAgent formats are extensible, however by default "json" and "form" are supported. To send the data as `application/x-www-form-urlencoded` simply invoke `.type()` with "form", where the default is "json". This request will POST the body "name=tj&pet=tobi". + + request.post('/user') + .type('form') + .send({ name: 'tj' }) + .send({ pet: 'tobi' }) + .end(callback) + + Note: "form" is aliased as "form-data" and "urlencoded" for backwards compat. + +## Setting the Content-Type + + The obvious solution is to use the `.set()` method: + + request.post('/user') + .set('Content-Type', 'application/json') + + As a short-hand the `.type()` method is also available, accepting + the canonicalized MIME type name complete with type/subtype, or + simply the extension name such as "xml", "json", "png", etc: + + request.post('/user') + .type('application/json') + + request.post('/user') + .type('json') + + request.post('/user') + .type('png') + +## Setting Accept + +In a similar fashion to the `.type()` method it is also possible to set the Accept header via the short hand method `.accept()`. Which references `request.types` as well allowing you to specify either the full canonicalized MIME type name as type/subtype, or the extension suffix form as "xml", "json", "png", etc for convenience: + + request.get('/user') + .accept('application/json') + + request.get('/user') + .accept('json') + + request.post('/user') + .accept('png') + +## Query strings + + `res.query(obj)` is a method which may be used to build up a query-string. For example populating `?format=json&dest=/login` on a __POST__: + + request + .post('/') + .query({ format: 'json' }) + .query({ dest: '/login' }) + .send({ post: 'data', here: 'wahoo' }) + .end(callback); + +## Parsing response bodies + + Super Agent will parse known response-body data for you, currently supporting _application/x-www-form-urlencoded_, _application/json_, and _multipart/form-data_. + +### JSON / Urlencoded + + The property `res.body` is the parsed object, for example if a request responded with the JSON string '{"user":{"name":"tobi"}}', `res.body.user.name` would be "tobi". Likewise the x-www-form-urlencoded value of "user[name]=tobi" would yield the same result. + +### Multipart + + The Node client supports _multipart/form-data_ via the [Formidable](https://github.com/felixge/node-formidable) module. When parsing multipart responses, the object `res.files` is also available to you. Suppose for example a request responds with the following multipart body: + + --whoop + Content-Disposition: attachment; name="image"; filename="tobi.png" + Content-Type: image/png + + ... data here ... + --whoop + Content-Disposition: form-data; name="name" + Content-Type: text/plain + + Tobi + --whoop-- + + You would have the values `res.body.name` provided as "Tobi", and `res.files.image` as a `File` object containing the path on disk, filename, and other properties. + +## Response properties + + Many helpful flags and properties are set on the `Response` object, ranging from the response text, parsed response body, header fields, status flags and more. + +### Response text + + The `res.text` property contains the unparsed response body string. This + property is always present for the client API, and only when the mime type + matches "text/*", "*/json", or "x-www-form-urlencoding" by default for node. The + reasoning is to conserve memory, as buffering text of large bodies such as multipart files or images is extremely inefficient. + + To force buffering see the "Buffering responses" section. + +### Response body + + Much like SuperAgent can auto-serialize request data, it can also automatically parse it. When a parser is defined for the Content-Type, it is parsed, which by default includes "application/json" and "application/x-www-form-urlencoded". The parsed object is then available via `res.body`. + +### Response header fields + + The `res.header` contains an object of parsed header fields, lowercasing field names much like node does. For example `res.header['content-length']`. + +### Response Content-Type + + The Content-Type response header is special-cased, providing `res.type`, which is void of the charset (if any). For example the Content-Type of "text/html; charset=utf8" will provide "text/html" as `res.type`, and the `res.charset` property would then contain "utf8". + +### Response status + + The response status flags help determine if the request was a success, among other useful information, making SuperAgent ideal for interacting with RESTful web services. These flags are currently defined as: + + var type = status / 100 | 0; + + // status / class + res.status = status; + res.statusType = type; + + // basics + res.info = 1 == type; + res.ok = 2 == type; + res.clientError = 4 == type; + res.serverError = 5 == type; + res.error = 4 == type || 5 == type; + + // sugar + res.accepted = 202 == status; + res.noContent = 204 == status || 1223 == status; + res.badRequest = 400 == status; + res.unauthorized = 401 == status; + res.notAcceptable = 406 == status; + res.notFound = 404 == status; + res.forbidden = 403 == status; + +## Aborting requests + + To abort requests simply invoke the `req.abort()` method. + +## Request timeouts + + A timeout can be applied by invoking `req.timeout(ms)`, after which an error + will be triggered. To differentiate between other errors the `err.timeout` property + is set to the `ms` value. __NOTE__ that this is a timeout applied to the request + and all subsequent redirects, not per request. + +## Basic authentication + + Basic auth is currently provided by the _node_ client in two forms, first via the URL as "user:pass": + + request.get('http://tobi:learnboost@local').end(callback); + + As well as via the `.auth()` method: + + request + .get('http://local') + .auth('tobi', 'learnboost') + .end(callback); + +## Following redirects + + By default up to 5 redirects will be followed, however you may specify this with the `res.redirects(n)` method: + + request + .get('/some.png') + .redirects(2) + .end(callback); + +## Piping data + + The Node client allows you to pipe data to and from the request. For example piping a file's contents as the request: + + var request = require('superagent') + , fs = require('fs'); + + var stream = fs.createReadStream('path/to/my.json'); + var req = request.post('/somewhere'); + req.type('json'); + stream.pipe(req); + + Or piping the response to a file: + + var request = require('superagent') + , fs = require('fs'); + + var stream = fs.createWriteStream('path/to/my.json'); + var req = request.get('/some.json'); + req.pipe(stream); + +## Multipart requests + + Super Agent is also great for _building_ multipart requests for which it provides methods `.attach()` and `.field()`. + +### Attaching files + + As mentioned a higher-level API is also provided, in the form of `.attach(name, [path], [filename])` and `.field(name, value)`. Attaching several files is simple, you can also provide a custom filename for the attachment, otherwise the basename of the attached file is used. + + request + .post('/upload') + .attach('avatar', 'path/to/tobi.png', 'user.png') + .attach('image', 'path/to/loki.png') + .attach('file', 'path/to/jane.png') + .end(callback); + +### Field values + + Much like form fields in HTML, you can set field values with the `.field(name, value)` method. Suppose you want to upload a few images with your name and email, your request might look something like this: + + request + .post('/upload') + .field('user[name]', 'Tobi') + .field('user[email]', 'tobi@learnboost.com') + .attach('image', 'path/to/tobi.png') + .end(callback); + +## Compression + + The node client supports compressed responses, best of all, you don't have to do anything! It just works. + +## Buffering responses + + To force buffering of response bodies as `res.text` you may invoke `req.buffer()`. To undo the default of buffering for text responses such + as "text/plain", "text/html" etc you may invoke `req.buffer(false)`. + + When buffered the `res.buffered` flag is provided, you may use this to + handle both buffered and unbuffered responses in the same callback. + +## CORS + + The `.withCredentials()` method enables the ability to send cookies + from the origin, however only when "Access-Control-Allow-Origin" is + _not_ a wildcard ("*"), and "Access-Control-Allow-Credentials" is "true". + + request + .get('http://localhost:4001/') + .withCredentials() + .end(function(err, res){ + assert(200 == res.status); + assert('tobi' == res.text); + next(); + }) + +## Error handling + +Your callback function will always be passed two arguments: error and response. If no error occurred, the first argument will be null: + + request + .post('/upload') + .attach('image', 'path/to/tobi.png') + .end(function(err, res){ + + }); + + An "error" event is also emitted, with you can listen for: + + request + .post('/upload') + .attach('image', 'path/to/tobi.png') + .on('error', handle) + .end(function(err, res){ + + }); + + Note that a 4xx or 5xx response with super agent **are** considered an error by default. For example if you get a 500 or 403 response, this status information will be available via `err.status`. Errors from such responses also contain an `err.response` field with all of the properties mentioned in "Response properties". The library behaves in this way to handle the common case of wanting success responses and treating HTTP error status codes as errors while still allowing for custom logic around specific error conditions. + + Network failures, timeouts, and other errors that produce no response will contain no `err.status` or `err.response` fields. + + If you wish to handle 404 or other HTTP error responses, you can query the `err.status` property. + When an HTTP error occurs (4xx or 5xx response) the `res.error` property is an `Error` object, + this allows you to perform checks such as: + + if (err && err.status === 404) { + alert('oh no ' + res.body.message); + } + else if (err) { + // all other error types we handle generically + } + +## Generator support + +Superagent now supports easier control flow using generators. By using a generator control flow +like [co](https://github.com/tj/co) or a web framework like [koa](https://github.com/koajs/koa), +you can `yield` on any superagent method: + + var res = yield request + .get('http://local') + .auth('tobi', 'learnboost') diff --git a/6-2/node_modules/superagent/docs/jquery-ui.min.js b/6-2/node_modules/superagent/docs/jquery-ui.min.js new file mode 100644 index 0000000..932f867 --- /dev/null +++ b/6-2/node_modules/superagent/docs/jquery-ui.min.js @@ -0,0 +1,6 @@ +/*! jQuery UI - v1.11.4 - 2015-11-20 +* http://jqueryui.com +* Includes: widget.js +* Copyright jQuery Foundation and other contributors; Licensed MIT */ + +(function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){var t=0,i=Array.prototype.slice;e.cleanData=function(t){return function(i){var s,n,a;for(a=0;null!=(n=i[a]);a++)try{s=e._data(n,"events"),s&&s.remove&&e(n).triggerHandler("remove")}catch(o){}t(i)}}(e.cleanData),e.widget=function(t,i,s){var n,a,o,r,h={},l=t.split(".")[0];return t=t.split(".")[1],n=l+"-"+t,s||(s=i,i=e.Widget),e.expr[":"][n.toLowerCase()]=function(t){return!!e.data(t,n)},e[l]=e[l]||{},a=e[l][t],o=e[l][t]=function(e,t){return this._createWidget?(arguments.length&&this._createWidget(e,t),void 0):new o(e,t)},e.extend(o,a,{version:s.version,_proto:e.extend({},s),_childConstructors:[]}),r=new i,r.options=e.widget.extend({},r.options),e.each(s,function(t,s){return e.isFunction(s)?(h[t]=function(){var e=function(){return i.prototype[t].apply(this,arguments)},n=function(e){return i.prototype[t].apply(this,e)};return function(){var t,i=this._super,a=this._superApply;return this._super=e,this._superApply=n,t=s.apply(this,arguments),this._super=i,this._superApply=a,t}}(),void 0):(h[t]=s,void 0)}),o.prototype=e.widget.extend(r,{widgetEventPrefix:a?r.widgetEventPrefix||t:t},h,{constructor:o,namespace:l,widgetName:t,widgetFullName:n}),a?(e.each(a._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete a._childConstructors):i._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){for(var s,n,a=i.call(arguments,1),o=0,r=a.length;r>o;o++)for(s in a[o])n=a[o][s],a[o].hasOwnProperty(s)&&void 0!==n&&(t[s]=e.isPlainObject(n)?e.isPlainObject(t[s])?e.widget.extend({},t[s],n):e.widget.extend({},n):n);return t},e.widget.bridge=function(t,s){var n=s.prototype.widgetFullName||t;e.fn[t]=function(a){var o="string"==typeof a,r=i.call(arguments,1),h=this;return o?this.each(function(){var i,s=e.data(this,n);return"instance"===a?(h=s,!1):s?e.isFunction(s[a])&&"_"!==a.charAt(0)?(i=s[a].apply(s,r),i!==s&&void 0!==i?(h=i&&i.jquery?h.pushStack(i.get()):i,!1):void 0):e.error("no such method '"+a+"' for "+t+" widget instance"):e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+a+"'")}):(r.length&&(a=e.widget.extend.apply(null,[a].concat(r))),this.each(function(){var t=e.data(this,n);t?(t.option(a||{}),t._init&&t._init()):e.data(this,n,new s(a,this))})),h}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"
",options:{disabled:!1,create:null},_createWidget:function(i,s){s=e(s||this.defaultElement||this)[0],this.element=e(s),this.uuid=t++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=e(),this.hoverable=e(),this.focusable=e(),s!==this&&(e.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===s&&this.destroy()}}),this.document=e(s.style?s.ownerDocument:s.document||s),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this.options=e.widget.extend({},this.options,this._getCreateOptions(),i),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(t,i){var s,n,a,o=t;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof t)if(o={},s=t.split("."),t=s.shift(),s.length){for(n=o[t]=e.widget.extend({},this.options[t]),a=0;s.length-1>a;a++)n[s[a]]=n[s[a]]||{},n=n[s[a]];if(t=s.pop(),1===arguments.length)return void 0===n[t]?null:n[t];n[t]=i}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=i}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,i,s){var n,a=this;"boolean"!=typeof t&&(s=i,i=t,t=!1),s?(i=n=e(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),e.each(s,function(s,o){function r(){return t||a.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?a[o]:o).apply(a,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||e.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+a.eventNamespace,u=h[2];u?n.delegate(u,l,r):i.bind(l,r)})},_off:function(t,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(i).undelegate(i),this.bindings=e(this.bindings.not(t).get()),this.focusable=e(this.focusable.not(t).get()),this.hoverable=e(this.hoverable.not(t).get())},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var n,a,o=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(e.isFunction(o)&&o.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,n,a){"string"==typeof n&&(n={effect:n});var o,r=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),o=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),o&&e.effects&&e.effects.effect[r]?s[t](n):r!==t&&s[r]?s[r](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}}),e.widget}); \ No newline at end of file diff --git a/6-2/node_modules/superagent/docs/jquery.js b/6-2/node_modules/superagent/docs/jquery.js new file mode 100644 index 0000000..d2424e6 --- /dev/null +++ b/6-2/node_modules/superagent/docs/jquery.js @@ -0,0 +1,4 @@ +/*! jQuery v1.7 jquery.com | jquery.org/license */ +(function(a,b){function cA(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cx(a){if(!cm[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cn||(cn=c.createElement("iframe"),cn.frameBorder=cn.width=cn.height=0),b.appendChild(cn);if(!co||!cn.createElement)co=(cn.contentWindow||cn.contentDocument).document,co.write((c.compatMode==="CSS1Compat"?"":"")+""),co.close();d=co.createElement(a),co.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cn)}cm[a]=e}return cm[a]}function cw(a,b){var c={};f.each(cs.concat.apply([],cs.slice(0,b)),function(){c[this]=a});return c}function cv(){ct=b}function cu(){setTimeout(cv,0);return ct=f.now()}function cl(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ck(){try{return new a.XMLHttpRequest}catch(b){}}function ce(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bB(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function br(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bi,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bq(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bp(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bp)}function bp(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bo(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bn(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bm(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d=0===c})}function V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(){return!0}function M(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z]|[0-9])/ig,x=/^-ms-/,y=function(a,b){return(b+"").toUpperCase()},z=d.userAgent,A,B,C,D=Object.prototype.toString,E=Object.prototype.hasOwnProperty,F=Array.prototype.push,G=Array.prototype.slice,H=String.prototype.trim,I=Array.prototype.indexOf,J={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=n.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7",length:0,size:function(){return this.length},toArray:function(){return G.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?F.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),B.add(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(G.apply(this,arguments),"slice",G.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:F,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;B.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!B){B=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",C,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",C),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&K()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return a!=null&&m.test(a)&&!isNaN(a)},type:function(a){return a==null?String(a):J[D.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!E.call(a,"constructor")&&!E.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||E.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(x,"ms-").replace(w,y)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
a",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,unknownElems:!!a.getElementsByTagName("nav").length,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",enctype:!!c.createElement("form").enctype,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.lastChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},m&&f.extend(p,{position:"absolute",left:"-999px",top:"-999px"});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="
",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="
t
",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;f(function(){var a,b,d,e,g,h,i=1,j="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",l="visibility:hidden;border:0;",n="style='"+j+"border:5px solid #000;padding:0;'",p="
"+""+"
";m=c.getElementsByTagName("body")[0];!m||(a=c.createElement("div"),a.style.cssText=l+"width:0;height:0;position:static;top:0;margin-top:"+i+"px",m.insertBefore(a,m.firstChild),o=c.createElement("div"),o.style.cssText=j+l,o.innerHTML=p,a.appendChild(o),b=o.firstChild,d=b.firstChild,g=b.nextSibling.firstChild.firstChild,h={doesNotAddBorder:d.offsetTop!==5,doesAddBorderForTableAndCells:g.offsetTop===5},d.style.position="fixed",d.style.top="20px",h.fixedPosition=d.offsetTop===20||d.offsetTop===15,d.style.position=d.style.top="",b.style.overflow="hidden",b.style.position="relative",h.subtractsBorderForOverflowNotVisible=d.offsetTop===-5,h.doesNotIncludeMarginInBodyOffset=m.offsetTop!==i,m.removeChild(a),o=a=null,f.extend(k,h))}),o.innerHTML="",n.removeChild(o),o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[f.expando]:a[f.expando]&&f.expando,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[f.expando]=n=++f.uuid:n=f.expando),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[f.expando]:f.expando;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)?b=b:b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" "));for(e=0,g=b.length;e-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];if(!arguments.length){if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}return b}e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!a||j===3||j===8||j===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g},removeAttr:function(a,b){var c,d,e,g,h=0;if(a.nodeType===1){d=(b||"").split(p),g=d.length;for(;h=0}})});var z=/\.(.*)$/,A=/^(?:textarea|input|select)$/i,B=/\./g,C=/ /g,D=/[^\w\s.|`]/g,E=/^([^\.]*)?(?:\.(.+))?$/,F=/\bhover(\.\S+)?/,G=/^key/,H=/^(?:mouse|contextmenu)|click/,I=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,J=function(a){var b=I.exec(a);b&& +(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},K=function(a,b){return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||a.id===b[2])&&(!b[3]||b[3].test(a.className))},L=function(a){return f.event.special.hover?a:a.replace(F,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=L(c).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"",(g||!e)&&c.preventDefault();if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,n=null;for(m=e.parentNode;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l=0:t===b&&(t=o[s]=r.quick?K(m,r.quick):f(m).is(s)),t&&q.push(r);q.length&&j.push({elem:m,matches:q})}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),G.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),H.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(V(c[0])||V(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var Y="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",Z=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,_=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,ba=/<([\w:]+)/,bb=/",""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bk=X(c);bj.optgroup=bj.option,bj.tbody=bj.tfoot=bj.colgroup=bj.caption=bj.thead,bj.th=bj.td,f.support.htmlSerialize||(bj._default=[1,"div
","
"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){f(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after" +,arguments);a.push.apply(a,f(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Z,""):null;if(typeof a=="string"&&!bd.test(a)&&(f.support.leadingWhitespace||!$.test(a))&&!bj[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(_,"<$1>");try{for(var c=0,d=this.length;c1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bn(a,d),e=bo(a),g=bo(d);for(h=0;e[h];++h)g[h]&&bn(e[h],g[h])}if(b){bm(a,d);if(c){e=bo(a),g=bo(d);for(h=0;e[h];++h)bm(e[h],g[h])}}e=g=null;return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!bc.test(k))k=b.createTextNode(k);else{k=k.replace(_,"<$1>");var l=(ba.exec(k)||["",""])[1].toLowerCase(),m=bj[l]||bj._default,n=m[0],o=b.createElement("div");b===c?bk.appendChild(o):X(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=bb.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]===""&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&$.test(k)&&o.insertBefore(b.createTextNode($.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bt.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bs,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bs.test(g)?g.replace(bs,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bB(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bC=function(a,c){var d,e,g;c=c.replace(bu,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bD=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bv.test(f)&&bw.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bB=bC||bD,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bF=/%20/g,bG=/\[\]$/,bH=/\r?\n/g,bI=/#.*$/,bJ=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bK=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bL=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bM=/^(?:GET|HEAD)$/,bN=/^\/\//,bO=/\?/,bP=/)<[^<]*)*<\/script>/gi,bQ=/^(?:select|textarea)/i,bR=/\s+/,bS=/([?&])_=[^&]*/,bT=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bU=f.fn.load,bV={},bW={},bX,bY,bZ=["*/"]+["*"];try{bX=e.href}catch(b$){bX=c.createElement("a"),bX.href="",bX=bX.href}bY=bT.exec(bX.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bU)return bU.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
").append(c.replace(bP,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bQ.test(this.nodeName)||bK.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bH,"\r\n")}}):{name:b.name,value:c.replace(bH,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?cb(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),cb(a,b);return a},ajaxSettings:{url:bX,isLocal:bL.test(bY[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bZ},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:b_(bV),ajaxTransport:b_(bW),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cd(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=ce(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bJ.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bI,"").replace(bN,bY[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bR),d.crossDomain==null&&(r=bT.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bY[1]&&r[2]==bY[2]&&(r[3]||(r[1]==="http:"?80:443))==(bY[3]||(bY[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),ca(bV,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bM.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bO.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bS,"$1_="+x);d.url=y+(y===d.url?(bO.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bZ+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=ca(bW,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){s<2?w(-1,z):f.error(z)}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)cc(g,a[g],c,e);return d.join("&").replace(bF,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cf=f.now(),cg=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cf++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cg.test(b.url)||e&&cg.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cg,l),b.url===j&&(e&&(k=k.replace(cg,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ch=a.ActiveXObject?function(){for(var a in cj)cj[a](0,1)}:!1,ci=0,cj;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ck()||cl()}:ck,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ch&&delete cj[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++ci,ch&&(cj||(cj={},f(a).unload(ch)),cj[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cm={},cn,co,cp=/^(?:toggle|show|hide)$/,cq=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cr,cs=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],ct;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cw("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cz.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cz.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cA(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cA(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window); \ No newline at end of file diff --git a/6-2/node_modules/superagent/docs/jquery.tocify.min.js b/6-2/node_modules/superagent/docs/jquery.tocify.min.js new file mode 100755 index 0000000..0fc0442 --- /dev/null +++ b/6-2/node_modules/superagent/docs/jquery.tocify.min.js @@ -0,0 +1,4 @@ +/*! jquery.tocify - v1.9.0 - 2013-10-01 +* http://gregfranko.com/jquery.tocify.js/ +* Copyright (c) 2013 Greg Franko; Licensed MIT*/ +(function(e){"use strict";e(window.jQuery,window,document)})(function(e,t,s){"use strict";var i="tocify",o="tocify-focus",n="tocify-hover",a="tocify-hide",l="tocify-header",h="."+l,r="tocify-subheader",d="."+r,c="tocify-item",f="."+c,u="tocify-extend-page",p="."+u;e.widget("toc.tocify",{version:"1.9.0",options:{context:"body",ignoreSelector:null,selectors:"h1, h2, h3",showAndHide:!0,showEffect:"slideDown",showEffectSpeed:"medium",hideEffect:"slideUp",hideEffectSpeed:"medium",smoothScroll:!0,smoothScrollSpeed:"medium",scrollTo:0,showAndHideOnScroll:!0,highlightOnScroll:!0,highlightOffset:40,theme:"bootstrap",extendPage:!0,extendPageOffset:100,history:!0,scrollHistory:!1,hashGenerator:"compact",highlightDefault:!0},_create:function(){var s=this;s.extendPageScroll=!0,s.items=[],s._generateToc(),s._addCSSClasses(),s.webkit=function(){for(var e in t)if(e&&-1!==e.toLowerCase().indexOf("webkit"))return!0;return!1}(),s._setEventHandlers(),e(t).load(function(){s._setActiveElement(!0),e("html, body").promise().done(function(){setTimeout(function(){s.extendPageScroll=!1},0)})})},_generateToc:function(){var t,s,o=this,n=o.options.ignoreSelector;return t=-1!==this.options.selectors.indexOf(",")?e(this.options.context).find(this.options.selectors.replace(/ /g,"").substr(0,this.options.selectors.indexOf(","))):e(this.options.context).find(this.options.selectors.replace(/ /g,"")),t.length?(o.element.addClass(i),t.each(function(t){e(this).is(n)||(s=e("